ronk
ronk

Reputation: 203

Set select options with jQuery

How do I set an option value in select list with jQuery? I tried:

$('#SelectGroup :all').replace("tmp4", "abc");

I mean: Search for tmp4 string and replace it with abc. In the list, there are 4 items I don't mind going directly to entrance #4.

I will extend my question: I want to pass to the function that replaces a value from outside. I tried:

$('#SelectGroup option').each(function(fieldNum, newVal) { 
      this.text = this.text.replace('tmp4',$(newVal).text());
    });
});

and I tried:

$('#SelectGroup option').each(newVal, function() { 
      this.text = this.text.replace('tmp4',newVal);
    });
});

but here it says it fails! in the first line of .each

Why?

I don't understand! I pass a value to a function but it loses its value in the function and change

var newVal=  $(this).val();
$('#SelectGroup option').each(function(fieldNum, newVal) { 
    alert("final option text is:" + $(this).text());*/
    alert($(newVal).text());
    this.text = this.text.replace('tmp4',$(newVal).text());  
    });
});

but newVal is not what I pass to the function - it is what the for each gives it.

Upvotes: 2

Views: 5198

Answers (4)

Lachlan Roche
Lachlan Roche

Reputation: 25956

Do you mean to replace in the text or value of the options?

var replacement = 'abc';

$('#SelectGroup option').each(function() { 
    this.text = this.text.replace('tmp4', replacement );
    this.value = this.value.replace('tmp4', replacement );

});

Upvotes: 2

ronk
ronk

Reputation: 203

solve it another way:

$("input[name*=RELATIVE_symbol]").live("focusout", function(){
      var fieldNum =  $(this).attr('id').replace("RELATIVE_symbol_","");

      var newVal=  $(this).val();

      var a = $("#SelectGroup option[value='"+fieldNum+"']").attr('text').replace('tmp'+ fieldNum,newVal);
      $("#SelectGroup option[value='"+fieldNum+"']").text(a);

    });

Upvotes: 0

karim79
karim79

Reputation: 342745

It might be more efficient to include only the options which contain your search string, to reduce the number of iterations (thus reducing the number of replace calls):

$('#SelectGroup option[value*=tmp4]').each(function() { 
    $(this).val($(this).val().replace('tmp4', 'abc'));
});

See the attribute contains selector.

Upvotes: 0

Bjorn
Bjorn

Reputation: 71950

Doesen't $('option value=["' + value + '"]') work?

Upvotes: 1

Related Questions