简体   繁体   中英

How can i replace value from the option tag value attribute

I have a below scenario. Actually, by the process the after rendering the html dropdown box is display the value like below

 <select id="ht" class="input-box quick-jump-menu" name="ht">
<option selected="selected" value="">Jump straight to a below option</option>

<option value="<span id="_SE_CP" _SE_CPt="default"><a href="Google.co.uk"  alt="Lakeside" target="_self" class="">Lakeside</a></span>">
       Lakeside
</option>

<option value="<span id="_SE_CP" _SE_CPt="default"><a href="http://www.google.com" alt="Alvaston Hall" target="_self" class=""></a></span>">
       Alvaston
</option>

by some process, it is using some span tag there, i need only url in the value attribute like below

 <select id="ht" class="input-box quick-jump-menu" name="ht">
<option selected="selected" value="">Jump straight to a below option</option>

<option value="Google.co.uk">
       Lakeside
</option>

<option value="http://www.google.com">
       Alvaston
</option>

Here, i need only set the URL value in the "Value" attribute of the "option" tag. i think this can be done through jquery.

Please suggest any one if possible and help will be much appreciated

If you're rendering the option tag like this and you want to change it on the client side, here's a quick but dirty solution:

$("#ht option").each(function(){
    $(this).attr("value", $($(this).attr("value")).find("a").attr("href"));
});
​var tempDiv=$('<div/>');
$('#ht option').each(function(){
    tempDiv.html($(this).val());
    $(this).val(​​​​​​​​​​​​​​​​​​​​​​​​​​​tempDiv.find('a').attr('href'));
});

The above code uses a temporary div (tempDiv) to capture the html from the option value and extract the href value.

Demo (select an option): http://jsfiddle.net/A7nyd/

[Update] this is actually the same answer as @chrisgonzalez.

First off there is an error with the current HTML.. All the html inside of the value have double quotes.

Encase that inside single Quotes or escape the ones inside .

Try this

​$('#ht')​.after('<div id="check"></div>');

​$('#ht option').each(function(){
    if(this.value != ''){
       var $check = $('#check');
       var str = this.value;
       $check.append(str);
       var href = $check.find('a').attr('href');
       this.value = href;
       $check.empty();
    }        
});

$('#check').remove();

Check Fiddle

使用jQuery:

$('option').attr({value: 'new src'});

Try this:

$("#ht option").each(function()
{
    $(this).val($(this).val().find("a").attr("href"));
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM