简体   繁体   中英

How do I make the SELECT tag to change the URL

So i have this SELECT tags here

<select id="url">
  <option id="url1" >url 1</option>
  <option id="url2" >url 2</option>
</select>
<button onclick="go()">GO</button>

Then a script here

<script>
function go() {
                $.ajax({
                    url: 'url1.php?check=' + value,
                    type: 'GET',
                    async: true,
                })

Now, I want to change the line of code that says: url: 'url1.php?check=' + value, to say whatever the selected option's id is rather than the hardcoded "ur1.php" . How do I achieve these?

NOTE: I cut the code if you're wondering why is it like that.

The proper way to do this is to give each of your option 'sa value attribute. You can the get the select -element and get it's value (which will be the value of the selected option)

I added some code to help you:

 function go() { const select = document.getElementById('select'); const value = select.value; // <-- this here is the value you can use to make your request console.log(value); }
 <select id="select"> <option value="url1">URL 1</option> <option value="url2">URL 2</option> </select> <button onclick="go()">Go</button>

Here's a working demo of what you need. I changed the following to make it work:

1) give your <option> tags value attributes (as per documentation ) rather than id s. The one relating to the chosen option is then automatically read as being the value of the <select> .

2) get the currently selected URL value by using .val() to get the value of the <select>

3) (non-essential but good practice) using an unobtrusive event handler in the script itself rather than an inline "onclick".

4) (non-essential) you don't need async:true because that's already the default value.

 var value = "something"; $("#go").click(function() { var url = $("#url").val() + '.php?check=' + value; console.log(url); $.ajax({ url: url, type: 'GET', }); });
 <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <select id="url"> <option value="url1">url 1</option> <option value="url2">url 2</option> </select> <button type="button" id="go">GO</button>

HTML Code:

<SELECT id="url">
<option id="url1" >url 1</option>
<option id="url2" >url 2</option>
</SELECT>
<button id = "button_go">GO</button>

Script:

$("#button_go").click(go);

function go() {
  var value =$('#url').children("option:selected").attr('id');
  alert("You have selected the ID- " + value);

  // your ajax code 
}

Check the jsfiddle working code : https://jsfiddle.net/1eq29w6a/4/

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM