简体   繁体   中英

How to Get the value of the checked radio button in a group using type attribute?

I am trying to add focus to a text area using jQuery.

 $("input[type='checkbox']").click(function(){ $("#mycbxs input[type ='checkbox']").val(""); var radioButtonsChecked = $("input[value='']:checked"); radioButtonsChecked = $("#mycbxs:checked"); if(radioButtonsChecked == "B") { $("#BAcbx").focus(); } if(radioButtonsChecked == "M") { $("#MAcbx").focus(); } if(radioButtonsChecked == "P") { $("#PHDcbx").focus(); } }); 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <div id="mycbxs"> <br><strong>&nbsp;</strong> <br><input type="checkbox" id="BAcbx" value="B"> BA <br><input type="checkbox" id="MAcbx" value="M"> MA <br><input type="checkbox" id="PHDcbx" value="P"> PHD </div> <div id="myinputs"> <br><strong>Discipline</strong> <br><input type="text" id="BAText" size="30"> <br><input type="text" id="MAText" size="30"> <br><input type="text" id="PHDText" size="30"> </div> 

Any ideas why it is not adding focus on the selected text areas? This is difficult since the HTML does not have a "Name" attribute (this is on purpose).

Thank you for help.

您需要使用radioButtonsChecked.val() == "B"代替radioButtonsChecked == "B"

  $("input[type='checkbox']").click(function(){
   var radioButtonsChecked= $(this).val();
   if(radioButtonsChecked == "B") { $("#BAcbx").focus(); } 
   if(radioButtonsChecked == "M") { $("#MAcbx").focus(); } 
   if(radioButtonsChecked == "P") { $("#PHDcbx").focus(); }
  })

However in this case i suggest radio button so there is no multiple selection

Here you go with a solution

 $('input[type="checkbox"]').on('change', function(){ if($(this).is(':checked')){ $('#' + $(this).attr('text-id')).focus(); } }); 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <div id="mycbxs"> <br><strong>&nbsp;</strong> <br><input type="checkbox" id="BAcbx" text-id="BAText" value="B"> BA <br><input type="checkbox" id="MAcbx" text-id="MAText" value="M"> MA <br><input type="checkbox" id="PHDcbx" text-id="PHDText" value="P"> PHD </div> <div id="myinputs"> <br><strong>Discipline</strong> <br><input type="text" id="BAText" size="30"> <br><input type="text" id="MAText" size="30"> <br><input type="text" id="PHDText" size="30"> </div> 

I've used one extra attribute text-id in checkbox to keep the input textbox id

Hope this will help you.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM