views:

282

answers:

6

Hi, 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. By the way: in the list there are 4 items I don't mind to go directly to entrance #4.

Thanks

+1  A: 

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

apphacker
You mean `'option[value="' + value + '"]'`.
Gumbo
I edited it like 2 seconds after I posted it.
apphacker
+2  A: 

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 );

});
Lachlan Roche
A: 

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.

karim79
A: 

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

ron
A: 

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

$('#SelectGroup option').each(function(fieldNum, newVal) {

      this.text = this.text.replace('tmp4',$(newVal).text());

    });

});

or 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? do u have an answer? please..

ron
@ron Responses to other answers should be made as a comment on that answer. And updates to the question should be made to the question.
Lachlan Roche
A: 

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);

    });
ron