Home > Mobile >  JQuery/Javascript: Build URL string from multiple selects
JQuery/Javascript: Build URL string from multiple selects

Time:05-26

I have the following selects:

<select name="wpf2750_20">
  <option value="200">AAA</option>
  <option value="400">BBB</option>
</select>
<select name="wpf2750_27">
  <option value="600">CCC</option>
  <option value="800">DDD</option>
</select>

And then the following script:

<script>
  jQuery('select').on('change', function() {
    var url = 'http://example.com/file.html'   '?'   this.name   '='   this.value;
    alert(url);
  });
</script>

This gives me the correct URL with the name of the select once changed as well as the value. As there are multiple selects how do I build a URL with the complete string?

Currently it gives me: http://example.com/file.html?wpf2750_20=AAA

What I want to give me is: http://example.com/file.html?wpf2750_20=AAA?wpf2750_27=CCC

So with each select it builds on the URL. If they change the option then the URL also needs to change to reflect this.

CodePudding user response:

It is because your event only triggered when you change the input, and your code only capture the element that triggered event.

If you want to capture every select element, then instead of use this, you need to select every select element when the select input has changed.

You can try this

<script>
  $('select').on('change', function () {
      let params = [] 
      $('select').each((i,e)=>{
          params.push(`${$(e).prop("name")}=${$(e).val()}`)
      })
      var url = 'http://example.com/file.html'   '?'   params.join("&"); //suppose params on url join with & symbol but you are joining with ?

      alert(url);
  });
</script>

Replace the $ with your jQuery

CodePudding user response:

Collect all the names and values into an object. Construct your string by indexing into that object.

const $selects = $('select');
$selects.on('change', event => {
  const fragments = Object.fromEntries(
    $selects.map((i,e) => ([e.name, e.value])).get()
  );
  const url = `http://example.com/file.html?${fragments['wpf2750_20']}=${fragments['wpf2750_27']}`;
  console.log(url);
});

Or, more generally, build a query string from the selects and then append it to the url prefix:

const $selects = $('select');
$selects.on('change', event => {
  const query = $selects.map((i,e) => `${e.name}=${e.value}`).get().join('&');
  const url = `http://example.com/file.html?${query}`;
  console.log(url);
});

References:

  • Related