अपने <option>
तत्वों value
गुण नहीं है, तो आप सिर्फ .val
उपयोग कर सकते हैं:
$selectElement.val("text_you're_looking_for")
हालांकि, मूल्य गुण आपके <option>
तत्वों अगर , या भविष्य में हो सकता है, तो यह काम नहीं करेगा, क्योंकि जब भी संभव हो .val
इसके बजाय इसके value
विशेषता द्वारा एक विकल्प का चयन करेगा पाठ सामग्री। कोई निर्मित jQuery विधि है कि उसकी टेक्स्ट सामग्री से एक विकल्प का चयन करता है, तो विकल्प value
विशेषताओं होगा, तो हम एक सरल प्लगइन के साथ एक अपने आप को जोड़ना होगा:
/*
Source: https://stackoverflow.com/a/16887276/1709587
Usage instructions:
Call
jQuery('#mySelectElement').selectOptionWithText('target_text');
to select the <option> element from within #mySelectElement whose text content
is 'target_text' (or do nothing if no such <option> element exists).
*/
jQuery.fn.selectOptionWithText = function selectOptionWithText(targetText) {
return this.each(function() {
var $selectElement, $options, $targetOption;
$selectElement = jQuery(this);
$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 ($targetOption.prop) {
$targetOption.prop('selected', true);
}
else {
$targetOption.attr('selected', 'true');
}
});
}
बस इस प्लगइन कहीं बाद में शामिल आप पृष्ठ पर jQuery जोड़ते हैं, और उसके बाद
jQuery('#someSelectElement').selectOptionWithText('Some Target Text');
विकल्प चुनने के लिए करें।
प्लगइन विधि filter
का उपयोग करता है केवल option
targetText मिलान बाहर लेने के लिए, और jQuery संस्करण पर निर्भर करता है, या तो .attr
या .prop
का उपयोग कर इसे का चयन करता है (विवरण के लिए .prop() vs .attr() देखें)।
यहाँ एक JSFiddle है आप इस प्रश्न है, जो यह दर्शाता है कि यह एक केवल एक ही मज़बूती से काम करने के लिए है करने के लिए दिया तीनों जवाब के साथ खेलने के लिए उपयोग कर सकते हैं: http://jsfiddle.net/3cLm5/1/
स्रोत
2013-06-02 21:01:06
[jQuery के संभावित डुप्लिकेट - एक के चयनित मान सेट अपने टेक्स्ट विवरण के माध्यम से नियंत्रण का चयन करें] (http://stackoverflow.com/questions/496052/jquery-setting-the-selected-value-of-a-select-control-via-its-text-description) –