最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Workaround jquery set val() behavior on SELECT when no matching value - Stack Overflow

programmeradmin2浏览0评论

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?

Share Improve this question asked Jun 14, 2013 at 17:58 adam0101adam0101 31.2k22 gold badges102 silver badges190 bronze badges
Add a ment  | 

3 Answers 3

Reset to default 7

You 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");
发布评论

评论列表(0)

  1. 暂无评论