跳至主要内容

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

评论

此博客中的热门博文

My childhood

"Each person's life is like a book; some people prefer to savor it slowly, while others like to gradually forget it. Looking back, I want to see if I can discern the trajectory of the world from my seemingly insignificant life. I am a child from the countryside, and perhaps most people cannot understand what my so-called countryside looks like. Indeed, the impressions of the countryside can be very different depending on the country, and moreover, more than 40 years have passed, during these 40 years of rapid development in China. A phrase suddenly comes to mind, 'I see him building tall buildings, I see him feasting, I see everything collapsing.' The place where I was born is a small town in the southwest of China, a town so small that it only has one street, and the widest part is only 3 meters. Paved with stone slabs, worn by many years of use, the slabs are not flat but rather filled with small bumps and hollows, yet strangely smooth. At the end of the street is a ...

对于GFW的看法

谈到这个问题的人很多,讲的也非常详细,但我窃以为大多数人对此都不够重视。在这一点上来讲,国民党堪称楷模,我想台湾能有今日,很大程度上是因为他们最终也没有建立一个可以堪比中国的新闻审查制度。从权利集中的角度来讲,中国共产党并不比任何一个封建王朝差,从执行力度上来讲,那也和历史上最严酷的王朝可以评分秋色。至少,国民党还是讲点道德,尊重文化的。 如果说计划生育阉割了中国人的人口,那么GFW,和新闻出版署以及文化部阉割了中国人的精神。也许乐观的人说我们总可以翻墙,我们总可以通过这样那样的方法来获得信息。但是悲观的我并不这么认为,这种限制创造的是一种环境,是空气,你固然可以戴着口罩,但是你永远无法自由的呼吸,当大家都在这样的空气中活着的时候,戴着口罩的你是会被人另眼相看的。其实群体意识在掌握了所有媒体的政府面前就是一个面团,想怎么捏就怎么捏,本来就是信息不对称的更何况还是受到随意控制的。这是无解的,中国亟待提高公民意识,哲学思想,文化水平,等等,政府做的不过是又一轮的愚民罢了。鲁迅先生为之殚精极虑,奋斗一生的东西,过了一个世纪依然没有什么本质的改变,阿Q在国人里占的比例是在太大了。就好比是我以诚待国人,以心侍之,以身献之,奈何国人谓之以“傻逼”。你却又待何如?这样的文化封锁,信息封锁导致的唯一结果就是,你振臂一呼之时,便是阿Q们结队去看你被看头之日。 其实,中国政府早已脱离了共产主义这个哲学思想了。换句话说,这个哲学思想本身是没什么对错的,只是一旦应用起来就满不是那么回事了,几乎可以说,共产主义的集权必然导致共产主义的被抛弃。

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 connectio...