0

チェックボックスのみのフォームがあり、最後に他のオプションがあります。ユーザーが自分のテキストを書くことができる他のオプションをチェックして、テキストボックスまたはテキストエリアを開きたいです。

4

1 に答える 1

3

チェックボックスを使用したソリューション

方法 1 - その場で「入力」を作成し、チェックを外したら削除します。

シンプルです。次のようなチェックボックス グループがあります。

<h3>Which animal do you like the most?</h3>

<input type="checkbox" value="cats" id="cats" name="animals" class="animals" />
<label for="cats">cats</label>
<br/>
<!--extra checkboxes-->
<input type="checkbox" value="other" id="other" name="animals" class="animals" />
<label for="other">other</label>

次に、このための変更イベントを記述します。

$(".animals").change(function () {
    //check if its checked. If checked move inside and check for others value
    if (this.checked && this.value === "other") {
        //add a text box next to it
        $(this).next("label").after("<input id='other-text' placeholder='please enter animal' type='text'/>")
    } else {
        //remove if unchecked
        $("#other-text").remove();
    }
});

デモ: http://jsfiddle.net/hungerpain/KqRpM/

(より良い & よりクリーン) 方法 2 - DOM に「入力」を保持し、チェック/チェック解除時に非表示/表示

<input>マークアップには、 last の直後にextra がありますlabel

<input type="checkbox" value="other" id="other" name="animals" class="animals" />
<label for="other">other</label>
<input id='other-text' placeholder='please enter animal' type='text' />

other-text、開始時に css を使用して隠されています。

#other-text{
  display: none;
}

次に、JS は次のようになります。

$(".animals").change(function () {
    //check if the selected option is others
    if (this.value === "other") {
        //toggle textbox visibility
        $("#other-text").toggle();
    }
});

デモ: http://jsfiddle.net/hungerpain/KqRpM/1/

ラジオボタンを使用したソリューション

しかし、そうは言っても、あなたの場合、それがラジオボタングループであればより良いでしょう。type=checkboxマークアップを からに変更するだけtype=radioです。JS は方法 1 のチェックボックスと同じままです。

デモ: http://jsfiddle.net/hungerpain/XzaRP/

于 2013-08-03T14:54:30.413 に答える