Reputation: 123
How would I go about setting 3 separate input tags to disable at once? After the user enters a time I would like to disable the input fields, then enable them when the time runs out. I know how to add the logic, I'm just having a hard time adding "disabled" to all of them at once.
<div id="inputFields">
<h3>Enter Time</h3>
<input id="hours" type="text" value="" name="hours" placeholder="Hours" maxlength="2"> <span>:</span>
<input id="minutes" type="text" value="" name="min" placeholder="Minutes" maxlength="2"> <span>:</span>
<input id="seconds" type="text" value="" name="seconds" placeholder="Seconds" maxlength="2">
</div>
Would I have to loop through them? Or could I access them as children of #inputFields? Or neither? Any suggestions would be appreciated...Thanks.
Upvotes: 1
Views: 909
Reputation: 225
Instead of packing your input
elements into a div
, you could properly make them child elements of a form
element.
This would have the advantage, that there is already a collection of form
elements in HTML, that you can easily access in JavaScript using document.forms[ ]
or just forms[ ]
, and their children with forms[ ].elements[ ]
.
The forms as well as their chilren can either be called by their index or their name
attribute, as like
var firstInput = forms['myInputForm'].elements[0];
for example, so that you then could loop through this selection and perform any changes you want.
EDIT
Given the fact, your input
elements do have a name
attribute anyway, you could write it like this
['hours', 'min', 'seconds'].forEach(function (name) {
document.forms['inputFields'].elements[name].setAttribute('disabled', true);
});
in your script and <form name="inputFields">
instead of your div
in HTML.
For containing input
elements, the form
element suits better than the div
element, and, as mentioned before, you wouldn't have to search the whole DOM for your input
elements, as there is already a HTML Collection that you can access using JavaScript the way described above.
Upvotes: 0
Reputation: 20756
If you're using jQuery:
$('#inputFields > input').prop('disabled', true);
Which sets the attribute for every input
that is a direct descendant of #inputFields
.
Another option:
$('#hours,#minutes,#seconds').prop('disabled', true);
Or if using pure Javascript:
['hours', 'minutes', 'seconds'].forEach(function (elemId) {
document.getElementById(elemId).setAttribute('disabled', true);
});
Should work nice too. This is as close to "all of them at once" that you can get.
Upvotes: 3
Reputation: 559
Here is a way to loop through them, you can do whatever you want with them.
$('#inputFields').children('input').each(function () {
alert(this.value);
});
e.g
$(this).prop('disabled', true);
Upvotes: 0