0

How can i make the option selected in jquery by Name

Here is the fiddle

Here is the script

<select name="zoom_cat[]" style="margin-left:15px;" id="contact_country">
    <option value=""  selected="selected">Nothing</option>

  <option value="0">Singam</option>
  <option value="1">Karadi</option>
  <option value="2">Poonai</option>
  <option value="3">Yaanai</option>
</select>

And here is the script

var myText = "Singam";
        $("#contact_country option:text=" + myText +"").prop("selected", "selected");
Cii Learner
  • 161
  • 1
  • 15

4 Answers4

2

Use :contains selector

$("#contact_country option:contains('" + myText +"')").prop("selected", "selected");

Demo: Fiddle


Note: Using contains can return partial results, so it might be safer to iterate and find the element ex: http://jsfiddle.net/arunpjohny/54w5rq5m/2/

So

var myText = "Singam";
$("#contact_country option").each(function () {
    if ($(this).text() == myText) {
        $(this).prop("selected", true);
        //since element is found no need to iterate further
        return false;
    }
});

Demo: Fiddle

Arun P Johny
  • 384,651
  • 66
  • 527
  • 531
0

You can also use a filter on options for a complete match. Contains gives you also partial match.

$('#contact_country option').filter(function() {
                    return $.trim($(this).text()) === myText;
                }).prop('selected', true);
SSA
  • 5,433
  • 4
  • 36
  • 50
0

Use :contains() instead of :text. Try with -

    var myText = "Singam";
    $("#contact_country option:contains(" + myText +")").attr("selected", true);
Sougata Bose
  • 31,517
  • 8
  • 49
  • 87
0

You can use something like:

HTML:

<a href="#" id="test" class="mytest">One</a>

Two Three

Javascript:

(function ($, window, document, undefined) {
$.scrollTo = function(el, options){
    // To avoid scope issues, use 'base' instead of 'this'
    // to reference this class from internal events and functions.
    var base = this;

    // Access to jQuery and DOM versions of element
    base.$el = $(el);
    base.el = el;

    base.init = function(){
        base.options = $.extend({},$.scrollTo.defaultOptions, options);

        // Put your initialization code here
    };

    // On click
  base.$el.click(function (event) {
        event.preventDefault(); 
        alert("clicked!");
    });    

    // Run initializer
    base.init();
};

$.scrollTo.defaultOptions = {};

$.fn.scrollTo = function(options){
    return this.each(function(){
        (new $.scrollTo(this, options));
    });
};

})(jQuery, window, document);

//Initialize plugin $('.mytest').scrollTo();

Thanks

Pratap Patil
  • 234
  • 1
  • 4