変更イベントでラジオを使用するにはどうすればいいですか? 質問する

変更イベントでラジオを使用するにはどうすればいいですか? 質問する

変更イベントにラジオボタンが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') {
        // ...
    }
});

http://jsfiddle.net/4gZAT/

allot両方の if ステートメントで値を比較しており、:radioセレクターは非推奨であることに注意してください。

jQuery を使用していない場合は、次のメソッドdocument.querySelectorAllHTMLElement.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);
});

おすすめ記事