简体   繁体   中英

Why does jQuery return integer instead of object?

I am trying to preselect an option in a <select> tag based on a variable. However, when selecting the elements via jQuery and iterating on it with .each() it seems to be returning integers instead of objects, so .value etc. are not applicable.

this is my code:

$("#id option").each(function(option){
    if(option.value == "myValue") {
        option.value.selected = "true";
    }
});

Your each function is incorrect if you want the element reference then there should be second parameter in each as first parameter is the index reference parameter. Secondly, you can simply use the val() function to set the value of the dropdown.

 $("#id option").each(function(index,option){ if(option.value == "myValue") { $("#id").val('myValue'); } }); 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <select id='id'> <option value="volvo">volvo</option> <option value="saab">Saab</option> <option value="myValue">myValue</option> <option value="audi">Audi</option> </select> 

Or you can simply use $(this) as:

 $("#id option").each(function(){ //check value of each option if($(this).val() == "myValue") { $("#id").val('myValue'); } }); 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <select id='id'> <option value="volvo">volvo</option> <option value="saab">Saab</option> <option value="myValue">myValue</option> <option value="audi">Audi</option> </select> 

The first argument for jQuery's each is the index , not the object. Try this instead:

$("#id option").each(function(i, option){

(if you don't care for the index i , feel free not to use it, but if you want to use the value, you have to include an argument for the index first)

The native array iteration methods use a more sensible approach and list the element in question first, for example:

document.querySelectorAll('#id option').forEach((option) =>

So you have to keep careful track of which method you're using.

you can use $(this) inside for get each item

$("#id option").each(function () {
    console.log($(this).val());
});

Well just add index in your code

$("#id option").each(function(index, option){

Since each function takes 2 param index and object, if you add only 1 it will treat as first parameter ie index.

The first argument in the callback function for each is the index and the second is the element.

$("#id option").each(function(index, option){
if(option.value == "myValue") {
    option.value.selected = "true";
}
});

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