LoginSignup
0
0

リセットボタンでJSが走る処理を書いたらうまくいかなかった

Posted at

たとえばこんなコード

<button type="reset" id="resetButton" name="resetButton" 
            class="btn btn-default">リセット</button>

<script>
$('#resetButton').click(function() {

const sampleValue = $("input[name='sampleselected']:checked").val();

    if (sampleselected === '0') {
        $('#sampletextbox').prop('disabled', true);
    } else {
        $('#sampletextbox').prop('disabled', false);
    }
});
</script>

リセットボタンがクリックされた時、「sampleselected」のチェック状態の値でテキストボックスの活性状態を制御しています
値をもたせているのは他の画面からの遷移状況でデフォルトの値が変化するからです。
リセットでチェック状態が初期に戻れば付随してテキストボックスの活性状態も変化する想定でしたが、想定通り変化しないパターンが発生しました。なぜ???

結論

これで直りました

<button type="button" id="resetButton" name="resetButton" 
            class="btn btn-default">リセット</button>
<script>
$('#resetButton').click(function() {
    $('#Sampleform')[0].reset();

    if ($("input[name='sampleselected']:checked").val() === '0') {
        $('#sampletextbox').prop('disabled', true);
    } else {
        $('##sampletextbox').prop('disabled', false);
    }
});
</script>

button typeを"button"へ変更し、フォームにIDを振って[0].reset();としていますが、
button type"reset"と同様フォームをリセットしてくれます。
type=resetをjsのイベントの呼び出しとして使うと処理がぶつかってうまくいかない場合があるようです。

こちらにも、「JavaScript を使用してカスタマイズしたいのであれば、 input type="button" またはよりよい button 要素を使用してください。」ときちんと書いてありますね。

0
0
2

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0