If I have this select box:
<select id="s" name="s">
<option value="0">-</option>
<option value="1">A</option>
<option value="2" selected>B</option>
<option value="3">C</option>
</select>
If I try to run $("#s").val("4")
, the selection changes to "0". (See behavior here: /) How can I make it so that if I attempt to set the select box to a value that does not exist in the select box that nothing changes?
If I have this select box:
<select id="s" name="s">
<option value="0">-</option>
<option value="1">A</option>
<option value="2" selected>B</option>
<option value="3">C</option>
</select>
If I try to run $("#s").val("4")
, the selection changes to "0". (See behavior here: http://jsfiddle/4NwN5/) How can I make it so that if I attempt to set the select box to a value that does not exist in the select box that nothing changes?
3 Answers
Reset to default 7You can try this way:
var toSel = 3; // Say your value is this
if($("#s option[value=" + toSel +"]").length > 0) //Check if an option exist with that value
{
$("#s").val(toSel); //Select the value
}
or Just use prop()
$("#s option[value='" + toSel +"']").prop('selected', true);
Demo
// grab the selected
var s = $("#s");
// cache the current selectedIndex
var idx = s[0].selectedIndex;
// set the value
s.val("4");
// If it was set to `0`, set it back to the original index
s[0].selectedIndex = s[0].selectedIndex || idx;
And you can roll this into a plugin:
jQuery.fn.selectVal = function (val) {
return this.each(function () {
if (this.nodeName === "SELECT") {
var idx = this.selectedIndex;
$(this).val(val);
var newOpt = this.options[this.selectedIndex];
if (newOpt.value !== ("" + val))
this.selectedIndex = idx;
}
})
};
$("#s").selectVal(4);
jsFiddle Demo
You would want to use a custom filter before you call jquery's val
$.fn.valScreen = function(value){
if( this.is("select") && this.find("option[value="+value+"]").length != 0 )
this.val(value);//call vanilla val
return this;//return jQuery object for chaining
};
You could then use it:
$("#s").valScreen("4");