开发者

Set select options with jQuery

开发者 https://www.devze.com 2022-12-19 18:18 出处:网络
How do I set an option value in select list with jQuery? I tried: $(\'#SelectGroup :all\').replace("tmp4", "abc");

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);
    });
});
开发者_Python百科

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.


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

});


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


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.


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

    });
0

精彩评论

暂无评论...
验证码 换一张
取 消