跳至主要内容

jquery change the select box value

we can do this at first:
$("#simple_search_bar .cat option[value=0]").prop('selected',true);
and there is an article talke about this:

The right way to do this depends upon your circumstances.

Case 1: No value attributes on the option elements

If your option elements don't have value attributes (and you're not worried about the possibility of somebody adding them later and inadvertently breaking your existing code), then just use the .val()method of the jQuery object wrapping your select element.
For instance, in the OP's case...
$select = $('#cbCategory');
$select.val(cat); // Selects the option with text `cat`, as long as the options don't have
                  // 'value' attributes.

Case 2: Option elements have value attributes

If your option elements have value attributes (or value attributes might be added in the future and you don't want your code to break), then there's no method built into jQuery to select options by text. In that case, use this function, or take what you need from the code:
/*
  Selects the 
function selectOptionByText(selectElement, targetText) {
    var $selectElement, $options, $targetOption;

    $selectElement = jQuery(selectElement);
    $options = $selectElement.find('option');
    $targetOption = $options.filter(
        function () {return jQuery(this).text() == targetText}
    );

    // We use `.prop` if it's available (which it should be for any jQuery versions above
    // and including 1.6), and fall back on `.attr` (which was used for changing DOM
    // properties in pre-1.6) otherwise.
    if (jQuery().prop) {
        $targetOption.prop('selected', true);
    } 
    else {
        $targetOption.attr('selected', 'true');
    }
}
Here we use filter to pick out only the option matching the targetText, and select it using either.attr or .prop, depending upon jQuery version (see .prop() vs .attr() for explanation).

How not to do this

There are a few approaches to selecting options by their text content that I've seen suggested on StackOverflow or elsewhere that you probably shouldn't follow, unless you have a really good reason and know what you're doing. Here they are, together with why they're bad ideas.

DON'T use .val() to select options by their text content if any of the options have valueattributes.

Using .val is suggested in the currently accepted answer to this question (at the moment that I'm writing), but on modern jQuery it only works if your option elements have no value attributes, as noted above. Using .val to select options by their text content when they had value attributes worked prior to jQuery version 1.4, but was considered a bug at that time and has since been fixed. (Here is the commit that made the change.)

DON'T give all your option elements value attributes equal to their text content and thenuse .val()

I've sometimes seen HTML where option elements in selects were all given value attributes equal to their text content. This is usually pointless; the value property of the option element will be equal to its text content if you don't specify a value attribute, and you can use .val on a jQuery selectelement to select options by text without giving them value attributes. If you don't need value attributes that are distinct from the text content of the option, it's simpler (and in some scenarios, like hand-written HTML, less error-prone) to not have value attributes at all, rather than duplicating content.

DON'T use the jQuery :contains selector instead of a .filter() call

:contains(someText) matches any elements of which someText is a substring, but here what we need is an exact text match. Even if :contains would be sufficient for a particular case (because nooption's text is a substring of another's in your particular select element), I would advise against using it. If you do so, you're needlessly writing code that is less explicit, harder to extract into a reusable function, and can break if you change your content.

DON'T use .attr() instead of .prop() for selecting options unless you absolutely need to in order to support pre-1.6 jQuery

评论

此博客中的热门博文

jquery on 的问题

return false  from  within a jQuery event handler  is effectively the same as calling both  e.preventDefault and  e.stopPropagation  on the passed  jQuery.Event object. e.preventDefault()  will prevent the default event from occuring,  e.stopPropagation()  will prevent the evet from bubbling up and  return false  will do both. Note that this behaviour differs from  normal  (non-jQuery) event handlers, in which, notably,  return false   does  not  stop the event from bubbling up . 所以on前半部分的selector必须是静态的。

chrome extension Error: attempting to use a disconnected prot object

if you get this error: Port error: Could not establish connection. Receiving end does not exist. miscellaneous_bindings:236 chromeHidden.Port.dispatchOnDisconnect miscellaneous_bindings:236 Uncaught Error: Attempting to use a disconnected port object miscellaneous_bindings:58 PortImpl.postMessage miscellaneous_bindings:58 responseCallback miscellaneous_bindings:143 xhr.onreadystatechange That means you have make some mistake as this discussed: This is caused when a connection get closed. For example if you open a tab that has the content_script injected, it opens a connection, the tab is closed, and then the background_page tries to pass a message. It will fail because the tab is no longer active to receive the message. In your case I would guess that as tabs close and new tabs open you are attempting to post messages with the old tabId instead of creating a new connection to the new tab. I would recommend reading through the  long-lived connections s

记得很久以前,不知道是在跟谁发感慨,久到好像是上大学时候的事了。我说,我流过很多眼泪,看电影流眼泪,看小说流眼泪,听别人的故事留言了,听歌的时候流眼泪,晚上一个人的时候独自流眼泪。我似乎是一个是一个太不像男人的男人。可是我又说,这些眼泪都是为自己流的。于是我也问对面那个人,(嗯,我也记不起她是谁了): "你为别人流过眼泪么?",居然没有回答我. 也许看见这篇文章的人也不相信,但是我真的想问你一句,你为别人流过眼泪么?真真正正的是为别人的,不是可怜自己,不是觉得别人可怜而让自己也感到了可怜,仅仅是为了别人而悲伤,有过么?如果真的有,我想那也许才是爱吧。 也许您会觉得奇怪,这和爱有什么关系?是啊,流眼泪就是爱么?我们因为悲伤而流泪,流泪是因为,爱别离,求不得,这些的主体是什么?是自己。 我们都是爱自己的,只是99%的人是吧。所以我们流泪了,因为我们的那些种种原因,我们很少会因为别人“求不得,爱别离”而流泪吧。也许说,那又不是自己,对呀,你爱自己,你又不爱她,何苦要为她流这种泪? 我不是一个宽容的人,我也不是一个豁达的人,这是我一生的缺点。我们会为了爱去宽容,我们会因为爱而变的豁达,也许,这是因为我从来都没有真正的爱过谁吧,甚至,连自己。嘿,我现在都开始疑惑,我真的爱过你么,如果是,我为什么都没有宽容和豁达呢?