変更イベントにラジオボタンが2つあります。変更ボタンが欲しいのですが、どうすればいいでしょうか? 私のコード
<input type="radio" name="bedStatus" id="allot" checked="checked" value="allot">Allot
<input type="radio" name="bedStatus" id="transfer" value="transfer">Transfer
脚本
<script>
$(document).ready(function () {
$('input:radio[name=bedStatus]:checked').change(function () {
if ($("input[name='bedStatus']:checked").val() == 'allot') {
alert("Allot Thai Gayo Bhai");
}
if ($("input[name='bedStatus']:checked").val() == 'transfer') {
alert("Transfer Thai Gayo");
}
});
});
</script>
ベストアンサー1
this
現在の要素を参照する which を使用できますinput
。
$('input[type=radio][name=bedStatus]').change(function() {
if (this.value == 'allot') {
// ...
}
else if (this.value == 'transfer') {
// ...
}
});
allot
両方の if ステートメントで値を比較しており、:radio
セレクターは非推奨であることに注意してください。
jQuery を使用していない場合は、次のメソッドdocument.querySelectorAll
とHTMLElement.addEventListener
メソッドを使用できます。
var radios = document.querySelectorAll('input[type=radio][name="bedStatus"]');
function changeHandler(event) {
if ( this.value === 'allot' ) {
console.log('value', 'allot');
} else if ( this.value === 'transfer' ) {
console.log('value', 'transfer');
}
}
Array.prototype.forEach.call(radios, function(radio) {
radio.addEventListener('change', changeHandler);
});