2016-11-25 5 views
1

jQueryで新しくなったので、ラジオボックスの値を自動的に変更しようとしていました。しかし、それは私が計画した通りには行かない。jqueryを使用してラジオで選択する

たとえば: 選択肢のオプションからMrs.またはMs.を選択すると、値のある女性のラジオのプロパティがtrueになるはずです。

<html> 
 

 
<head> 
 
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script> 
 
    <script> 
 
    $('[name="title"]').change(function() { 
 
     if ($(this).val() == "Ms." || $(this).val() == "Mrs.") { 
 
     $("#female").prop("checked", true); 
 
     } else if ($(this).val() == "Mr.") { 
 
     $("#male").prop("checked", true); 
 
     } 
 
    }); 
 
    </script> 
 
</head> 
 

 
<body> 
 
    <select name="title"> 
 
    <option value="" disabled selected>Choose your option</option> 
 
    <option value="Mr.">Mr.</option> 
 
    <option value="Mrs.">Mrs.</option> 
 
    <option value="Ms.">Ms.</option> 
 
    </select> 
 
    <label>Title</label> 
 

 
    <p><b>Gender</b> 
 
    <br/> 
 
    </p> 
 
    <input type="radio" name="gender" id="male"> 
 
    <label for="male">Male</label> 
 
    <input type="radio" name="gender" id="female"> 
 
    <label for="female">Female</label> 
 
</body> 
 

 
<html>

+2

でコードをラップします。https: //learn.jquery.com/using-jquery-core/document-ready/それが動作するはずです。 – sinisake

+0

@nevermindありがとうございました。 –

答えて

0

あなたのコードは正しいように見えます。 document.readyを使ってみるか、本文の最後に読み込んでみてください。

<html> 
 

 
<head> 
 
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script> 
 
    <script> 
 
    $(document).ready(function() { 
 
     $('[name="title"]').change(function() { 
 
      if ($(this).val() == "Ms." || $(this).val() == "Mrs.") { 
 
      $("#female").prop("checked", true); 
 
      } else if ($(this).val() == "Mr.") { 
 
      $("#male").prop("checked", true); 
 
      } 
 
     }); 
 
    }); 
 
    </script> 
 
</head> 
 

 
<body> 
 
    <select name="title"> 
 
    <option value="" disabled selected>Choose your option</option> 
 
    <option value="Mr.">Mr.</option> 
 
    <option value="Mrs.">Mrs.</option> 
 
    <option value="Ms.">Ms.</option> 
 
    </select> 
 
    <label>Title</label> 
 

 
    <p><b>Gender</b> 
 
    <br/> 
 
    </p> 
 
    <input type="radio" name="gender" id="male"> 
 
    <label for="male">Male</label> 
 
    <input type="radio" name="gender" id="female"> 
 
    <label for="female">Female</label> 
 
</body> 
 

 
<html>

0

あなたはdocument.readyラインを逃しています。

Using this page as a reference(jQueryを使ってラジオボタンをターゲットにする方法の説明である)、これは私はそれが私のテスト環境で動作させるために、あなたのコードを使用する方法である:

$(document).ready(initializePage); 
function initializePage(){ 
    $('[name="title"]').change(function() { 
     if ($(this).val() == "Ms." || $(this).val() == "Mrs.") { 
     $('input:radio[name=gender]')[1].checked = true; 
     } else if ($(this).val() == "Mr.") { 
     $('input:radio[name=gender]')[0].checked = true; 
     } 
    }); 
} 
関連する問題