[英]Javascript, get element by multiple condition (id and value)
我想問題很簡單,但我找不到任何解決方案。 我想檢查單選按鈕是否被選中。 從這里可能的解決方案:
對於這些輸入
<input type="radio" name="gender" id="gender_Male" value="Male" />
<input type="radio" name="gender" id="gender_Female" value="Female" />
你可以簡單地
if(document.getElementById('gender_Male').checked) {
//Male radio button is checked
}else if(document.getElementById('gender_Female').checked) {
//Female radio button is checked
}
但是我的輸入是這樣的:
<label><input id="16" type="radio" value="14" name="Q3"></input>Yes</label>
<label><input id="16" type="radio" value="15" name="Q3"></input>No</label>
id
本身不是唯一的,而僅與value
結合使用。如何檢查是否選擇“是”或“否”?
正如@Markasoftware所說, id
應該始終是唯一的。 但是瀏覽器仍然使用相同的id
解析您的html。
因此,關鍵是您可以選擇不帶id
的元素。
嘗試document.querySelectorAll
或document.querySelector
。 這是代碼:
document.querySelectorAll('input[value="14"]') // you can select all the `value='14'` inputs
document.querySelectorAll('input[name="Q3"]') // you can select all the `value='Q3'` inputs
您可以組成這些css3選擇器並達到目標。
您可以嘗試下一個選擇器:
$('input#16.14').is(':checked'){
//YES is checked
}
$('input#16.15').is(':checked'){
//NO is checked
}
但是id應該是唯一的。
另一種檢查選擇哪個的方法是使用輸入名稱:
$('input[name=Q3]:checked').val()
這樣,如果選擇“是”,您將得到14
如果沒有,則得到15
假設yes / no元素是性別廣播的下一個元素,則可以嘗試以下操作:
$('[name="gender"]').change(function(){
if($(this).val() == 'Male'){
$(this).next('input[type="radio"][value="14"]').prop('checked',true);
}else{
//Female
}
});
將課程添加到您的單選按鈕。
$('.radioGroup').change(function(){
if($(this).val() == 'Male'){
///
} else {
//female
}
});
<html>
<head>
<meta charset="utf-8">
<link rel="stylesheet" href="//code.jquery.com/ui/1.10.4/themes/smoothness/jquery-ui.css">
<script src="//code.jquery.com/jquery-1.9.1.js"></script>
<script src="//code.jquery.com/ui/1.10.4/jquery-ui.js"></script>
</head>
<body>
<label><input id="16" type="radio" value="14" name="Q3"/>Yes</label>
<label><input id="16" type="radio" value="15" name="Q3"/>No</label>
<script type="text/javascript">
$('input[name=Q3]').change(function () {
if ($('input[name=Q3]:checked').length > 0) {
var k = $('input[name=Q3]:checked').val();
alert(k);
}
});
</script>
</body>
</html>
$(':radio').on('change',function() { if( this.checked && this.value === "14" ) { alert( "'Yes' was selected!" ); } else if( this.checked && this.value === "15" ) { alert( "'No' was selected!" ); } });
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <label><input id="Q3_1" type="radio" value="14" name="Q3">Yes</label> <label><input id="Q3_2" type="radio" value="15" name="Q3">No</label>
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.