跳至主要内容

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

youtube script covid

[INTRO - Soft Music Playing] Narrator: "In August 2020, during the COVID-19 pandemic in China, I experienced a series of events that revealed the overbearing, unreasonable, and ignorant aspects of government policies. This story unfolds my observations and experiences in Xinjiang since April, presented in a neutral and factual manner." [Scene Transition - Music Shifts to a More Reflective Tone] Narrator: "April 8th marked the end of my nearly three-month-long home quarantine in Wuhan, as the lockdown was finally lifted. With Xinjiang gradually reopening since March, my work required me to return there as soon as possible." [Visuals: Scenes of Empty Streets in Wuhan, Transitioning to Busy Airports] Narrator: "My journey back to Xinjiang was fraught with delays. The direct flight on China Southern Airlines kept getting postponed. Reluctantly, I had to transit through Xi'an. Before leaving, I reported my health status to the community in Changji City, where I ...

survilliance in china

  Hello everyone, welcome to my YouTube channel. This is my first video, and I'm very happy to meet you all. I come from China, and looking back, time has passed so quickly. I've been in France for almost 20 years. Sometimes, when I chat with friends, I'm surprised at how little the French know about China. What's even more alarming is that the French media follows the narrative of the Chinese official media. This is why I decided to create a YouTube channel to talk to my French friends about the China I know. Since my parents and friends are still in China, and to avoid unnecessary impact on their lives, I've decided not to appear in person for now. This is how I fulfill my long-standing wish. My first episode is about "Digital Surveillance in China.",  Digital Surveillance: In China, using the official App Store is mandatory. Apple's App Store is China-specific, and all data is stored there. Google's App Store is simply inaccessible in China. If ...