The question has been asked multiple times, but this is not a repeat. I am using a for loop to search through a div of elements including select, input etc. It matches the class name to an objects parameter and if it matches it sets the value of the element.
for(var i in obj) {
if(obj.hasOwnProperty(i)) {
$(editClone).find('.' +i).val(obj[i]);
}
}
It works fine on input elements, but with the select element it removes all the options and simply sets the value on the actual element tag.
This is the select statement before I run my javascript:
<select class="type">
<option value="Home">Home</option>
<option value="Work">Work</option>
<option value="Mobile">Mobile</option>
<option value="Other">Other</option>
</select>
And after I run the code (inspected in firebug to verify):
<select class="type">Mobile</select>
Why does it do this? I thought val() was supposed to set a matching option tag to selected. The object value and option tags are matching, but it does not do what it is supposed to. What am I doing wrong here?
Turns out I had the DIV I was trying to clone nested in the wrong place in the HTML as well as a bad clone call in the javascript. Totally unrelated errors. The answer below is correct, it just didn’t work in my situation because I didn’t understand the problem I was having.
Is not valid. A select needs to have
optiontags inside of itHere’s a working version of your code:
DEMO
Script: