Auto Select radio button when focus input text field

 At run time we need auto select radio button when one of the input fields focus like textfield, textarea, file, selection option like all fields selected. The jQuery or ajax are best suitable to work with this.

Auto focus radio button

Now i am explain with jQuery code auto selected when focus one of the field

Html code for Auto Select radio button, when focus text field


<fieldset>
<legend>Select Text Field or choose file button</legend>
<input type="radio" name="mr" value="1" checked>
<input type="file" name="dataFile" id="fileChooser"> <br/>
<input type="radio" name="mr" value="2"> Direct Enter full path of image
<input type="text" id="target" name="dataFile">
</fieldset>

jQuery code for Auto Select radio button, when focus text field


<script src="https://code.jquery.com/jquery-1.3.2.min.js"></script>
<script>
$("#target").focus(function(){
$('input:radio[name=mr]')[1].checked = true;
});
$("#fileChooser").focus(function(){
$('input:radio[name=mr]')[0].checked = true;
});
</script>

The above Jquery code use immediate after of html code.

The radio button is 0-based, so the First radio button option = ‘0’,  second radio button option ='1' like that.

Another type option use as

$('input:radio[name=sex]:nth(1)').attr('checked',true);

Complete example code Auto Select radio button, when focus text field


<html>

 <head>

  <title>Auto Selection input radio button when focus input text filed jQuery code</title>

  <script src="https://code.jquery.com/jquery-1.3.2.min.js"></script>

 </head>

 <body>
 
<h1>Auto Selection input radio button when focus input text filed </h1>
 
<form action=" ">

 <fieldset>

  <legend>Select Text Field or choose file button</legend>

  <input type="radio" name="mr" value="1" checked>

  <input type="file" name="dataFile" id="fileChooser"> <br/>
  
<input type="radio" name="mr" value="2">
  Direct Enter full path of image

  <input type="text" id="target" name="dataFile">
 
</fieldset>
 <script>
 
$("#target").focus(function(){

   $('input:radio[name=mr]')[1].checked = true;
 
});

   $("#fileChooser").focus(function(){
   
$('input:radio[name=mr]')[0].checked = true;

  });
 
</script>

</form>

</body>

</html>

Output of above code

Auto Selection input radio button when focus input text filed

Select Text Field or choose file button
Direct Enter full path of image

0 Comments:

Post a Comment