简体   繁体   中英

How to add an attribute to an HTML string

I want to set the 'selected' attribute in a select option list with javascript/jquery. I have the select element in a jquery object, I just want to add the "selected" attribute to and item in the list.

$(mySelect).html() looks like this;

<option value="LININGER LAKE">LININGER LAKE</option>
<option value="MOOREDALE LAKE">MOOREDALE LAKE</option>
<option value="CARTER LAKE">CARTER LAKE</option>

I need to find the "CARTER LAKE" option and add the selected attribute to it so the HTML looks like this

<option value="LININGER LAKE">LININGER LAKE</option>
<option value="MOOREDALE LAKE">MOOREDALE LAKE</option>
<option value="CARTER LAKE" selected="selected">CARTER LAKE</option>

I know this can't be that hard, I'm just having a brain fart!

使用jQuery Attribute Equals选择器

$(mySelect).find('option[value="CARTER LAKE"]').prop("selected", "selected");

Try .contains() as shown

 $("select option:contains('CARTER LAKE')").attr('selected','selected')

OR

 $("select option:contains('CARTER LAKE')").prop('selected',true)

DEMO

$('option[value="CARTER LAKE"]').prop( "selected" );

要么

$('option[value="CARTER LAKE"]').attr( "selected", "selected" );

As simple as $(mySelect).val('CARTER LAKE')

Demo

Try by attr()

 $(document).ready(function(){ $('option[value="CARTER LAKE"]').attr( "selected", "selected" ); }); 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <select> <option value="LININGER LAKE">LININGER LAKE</option> <option value="MOOREDALE LAKE">MOOREDALE LAKE</option> <option value="CARTER LAKE">CARTER LAKE</option> </select> 

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