Reputation: 25
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!
Upvotes: 2
Views: 1141
Reputation: 10995
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
.
Upvotes: 3
Reputation: 6527
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>
Upvotes: 0
Reputation: 6907
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);
});
Upvotes: 0