简体   繁体   中英

how do I get the value of a class in the select box option with jquery

my code :

<select class='country'>
   <option value='usa'><span class='nameCountry'>America</span> <span class='idCountry'>1</span></option>
   <option value='sgd'><span class='nameCountry'>Singapura</span>  <span class='idCountry'>2</span></option>
   <option value='thi'><span class='nameCountry'>Thailand</span>  <span class='idCountry'>3</span></option>
</select>

<div class="result">
   <input type="text" name="kodeCountry" />
   <input type="text" name="idCountry" />
   <input type="text" name="nameCountry" />
</div>

here's my jquery code :

$(".country").change(function(){
    var kode = $(this).val();
    var name = $(".country option .nameCountry").html();
    var id = $(".country option .idCountry").html();
    console.log(kode);
    console.log(name);
    console.log(id);
});

result in console :

name and id = undefined

so, how to display the variable name and variable id? Thx..

So, putting <span> inside of an option actually violates the HTML spec ( It is bad to put <span /> tags inside <option /> tags, only for string manipulation not styling? ), so depending on the user's browser, the spans may not even be present in the dom (replaced instead with a text-type node containing the contents of the spans).

You'll probably want to use something like this instead

$(".country").on('change', function(e){
    var kode = $(this).val();
    var $selected = $('option:selected', this);
    var parts = $selected.text().split(/\W+/);
    var name = parts[0]
    var id = parts[1]
    console.log(kode);
    console.log(name);
    console.log(id);
});

fiddle: http://jsfiddle.net/9nn1rune/

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