2016-05-08 26 views
1

ラジオボタンに特定の値がある場合、HTMLの入力フィールドを無効にしようとしています。私は同じもののJavascript関数を使用しています。ラジオに基づいてテキストボックスを有効/無効にする/選択したオプションを選択します。JavaScript

コードスニペット1:(HTMLラジオボタン)

<div class="element-radio"> 
    <label class="title">Children</label> 
    <div class="column column2"> 
     <label> 
      <input type="radio" name="children" value="Yes" onChange="findselected()"/> 
      <span>Yes</span> 
     </label> 
    </div> 
    <span class="clearfix"></span> 

    <div class="column column2"> 
     <label> 
      <input type="radio" name="children" value="No" checked="checked" onChange="findselected()"/> 
      <span>No</span> 
     </label> 
    </div> 
    <span class="clearfix"></span> 
</div> 

<div class="element-number"> 
    <label class="title">No of children</label> 
    <div class="item-cont"> 
     <input class="large" type="text" min="0" max="100" name="no_children" placeholder="If YES, Number of Children?" value="<?php echo $no_children?>" /> 
     <span class="icon-place"></span> 
    </div> 
</div> 

コードスニペット2:(JavaScript関数)

<script type="text/javascript"> 
function findselected() { 
    if (document.form.children.value == 'No') { 
     document.form.no_children.disabled=true; 
//  return false; // not sure this line is needed 
    } else { 
     document.form.no_children.disabled=false; 
//  return false; // not sure this line is needed 
    } 
} 
</script> 

これは必須の方法では動作しません。同じことをするより良い方法はありますか?私はJavascriptをかなり新しくしているので、複雑なコードを実装することはできません。

答えて

2

は、次のコードを使用してスクリプトを更新します。

function findselected() { 
    var result = document.querySelector('input[name="children"]:checked').value; 
    if(result=="Yes"){ 

     document.getElementById("inputtext").setAttribute('disabled', true); 
    } 
    else{ 
     document.getElementById("inputtext").removeAttribute('disabled'); 
    } 
} 

そしてid="inputtext"としてあなたの入力コントロールにid属性を追加します。

<input id="inputtext" class="large" type="text" min="0" max="100" name="no_children" placeholder="If YES, Number of Children?" value="<?php echo $no_children?>" /> 
+0

Works!どうもありがとう! – Sahitya

+0

選択オプションhtmlタグのクエリセレクタを使用して結果変数を定義するにはどうすればよいですか? – Sahitya

+0

'document.querySelector( '#age option:checked')。value'を使用できます。ここで' age'は選択されたHTMLタグのidです。 – thisisbobbs

関連する問題