简体   繁体   中英

How can a radio button get checked by filling in a text field?

I have a HTML form, with radio buttons and a text field for some of them. When filling in a textfield, I want the corresponding radio button to be checked.

I suppose it's possible with Javascript. Can anyone help me out?

Thanks!

Here is how you can do it without jquery. This will also uncheck the radio button if the input is blank.

 var inputs = document.querySelectorAll('input[type="text"]'); for (var i = 0; i < inputs.length; i++) { var input = inputs[i]; input.addEventListener('input', function() { if (this.value == "") { this.nextElementSibling.checked = false; } else { this.nextElementSibling.checked = true; } }); } 
 <input type="text"> <input type="radio"> <input type="text"> <input type="radio"> 

If you have the radio buttons before the text fields, just change nextElementSibling to previousElementSibling .

Explanation

document.querySelectorAll('input[type="text"]') will return an array of DOM elements that represent each of your input text fields.

Then, a for loop is used to loop through each text field.

For each text field, an event listener is added that will call the function that is defined whenever the user changes the input in the text field. Don't use on change here, because that would only trigger the event when focus leaves the text field (in other words, when the user clicks outside the text field).

In the event listener, we can reference the current text field with this .

We can get a reference to the radio button that is next to the current text field using this.nextElementSibling . Attempting to use this.nextSibling will not work, as it will find a node that contains the actual text in your input field.

The if statement checks if the current text field is blank. If it is blank it will set the checked attribute of the corresponding radio button to false , but if it is not blank, it will set checked to true .

not sure if you have jquery on the page but with jQuery you could use

$('#idOfTextbox').on('input propertychange paste', function() {
    $('#idOfCheckbox').attr('checked', true);
});

You can use .on('input' ...

Please check out the snippet.

 $('.container').on('input' , 'input[type=text]',function(e){ var that = $(this); that.prev().prop({'checked':that.val().length>0}); }); 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <div class=container> <div><input type=radio /><input type=text></div> <div><input type=radio /><input type=text></div> <div><input type=radio /><input type=text></div> <div><input type=radio /><input type=text></div> <div><input type=radio /><input type=text></div> </div> 

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