jQuery - Why won't select box info duplicate but the rest will
I'm using the code below to try 开发者_如何学Pythonand duplicate information from one set of address fields to another set when a checkbox is checked. All of it works except for the state select box (drop down box). It's driving me crazy.
//on page load
$(document).ready(function() {
//when the checkbox is checked or unchecked
$('#copyaddress').click(function() {
// If checked
if ($(this).is(":checked")) {
//for each input field
$('#cc input', ':visible', document.body).each(function(i) {
//copy the values from the billing_fields inputs
//to the equiv inputs on the shipping_fields
$(this).val($('#info input').eq(i).val());
});
//won't work on drop downs, so get those values
var c_state = $("select#c_state").val();
// special for the select
$('select#cc_state option[value=' + c_state + ']').attr('selected', 'selected');
} else {
//for each input field
$('#cc input', ':visible', document.body).each(function(i) {
// put default values back
$(this).val($(this)[0].defaultValue);
});
// special for the select
$('select#cc_state option[value=""]').attr('selected', 'selected');
}
});
});
When setting the value of a single value select element you simply need to pass the text value of the option you would like to select. Check out the jQuery Documentation here on .val(value)
This can be modified ...
//won't work on drop downs, so get those values
var c_state = $("select#c_state").val();
// special for the select
$('select#cc_state option[value=' + c_state + ']').attr('selected', 'selected');
to this
$('select#cc_state').val($("select#c_state").val());
精彩评论