Reputation: 373
For each select list in my form, I want to set the selected option to the value in record[]
that matches the id of the select. i.e. the field name, which is what I've labelled the select with.
This code doesnt work, it's setting something else (my select list doesnt switch to my value from record[]
, though record[this.id]
is what I am expecting, and of course when I invert the below to build up a record to post, all I get is what I had to start with, not the new value I selected from the dropdown).
I thought I could just use .val()
to set a select list value instead to churning through all the options.
$('#dialog-edit-'+tableName+'-form select').each(function() {
$('#'+this.id).val(record[this.id]);
});
Upvotes: 0
Views: 64
Reputation: 3079
I guess, you should try this: http://jsfiddle.net/maximgladkov/Emnt6
HTML
<select id="test1">
<option value="test1-1">Test 1</option>
<option value="test1-2">Test 2</option>
<option value="test1-3">Test 3</option>
</select>
<select id="test2">
<option value="test2-1">Test 1</option>
<option value="test2-2">Test 2</option>
<option value="test2-3">Test 3</option>
</select>
<select id="test3">
<option value="test3-1">Test 1</option>
<option value="test3-2">Test 2</option>
<option value="test3-3">Test 3</option>
</select>
JS
$(document).ready(function() {
var record = { test1: 'test1-1', test2: 'test2-3', test3: 'test3-2' };
$('select').each(function() {
var id = $(this).attr('id');
$(this).find('option[selected]').removeAttr('selected');
$(this).find('option[value='+record[id]+']').prop('selected', true);
});
});
Upvotes: 1