[英]How do I get the first option of a select box to display in a div automatically when the page loads with JavaScript/jQuery?
[英]how do I get the value of a class in the select box option with jquery
我的代碼:
<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>
這是我的jQuery代碼:
$(".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);
});
結果在控制台中:
name and id = undefined
那么,如何顯示變量名稱和變量ID? 謝謝..
因此,將<span>
放在選項內實際上違反了HTML規范( 將<span />標記放在<option />標記內很不好,僅用於字符串操作而不是樣式設置? ),因此取決於用戶的瀏覽器,在dom中甚至不存在跨度(用包含跨度內容的文本類型節點代替)。
您可能想要使用類似這樣的東西
$(".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);
});
小提琴: http : //jsfiddle.net/9nn1rune/
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.