I have the following code to check a checkbox as soon as the user types something in the textbox. This works fine for a single text box.
function activateCheckbox() {
if (document.myForm.box1.checked == false) {
document.myForm.box1.checked = true;
}
}
<tr>
<td><input type="text" id="mySearch1" name="mySearch1" size="40" onkeypress="activateCheckbox()"/></td>
<td><input type="checkBox" id="box1" name="box1"/></td>
</tr>
However suppose there are more than one text boxes with a checkbox against each one and I want that only the corresponding checkbox should be checked. I modified the above code as shown below by passing a parameter to the function but it’s not working, because “document.myForm.id.checked” doesn’t work as it accepts the checkbox name instead of “id”. Please suggest if there are better alternatives or how do I modify my code to make it working?
function activateCheckbox(id) {
if (document.myForm.id.checked == false) {
document.myForm.id.checked = true;
}
}
<tr>
<td><input type="text" id="mySearch1" name="mySearch1" size="40" onkeypress="activateCheckbox('box1')"/></td>
<td><input type="checkBox" id="box1" name="box1"/></td>
</tr>
<tr>
<td><input type="text" id="mySearch2" name="mySearch2" size="40" onkeypress="activateCheckbox('box2')"/></td>
<td><input type="checkBox" id="box2" name="box2"/></td>
</tr>
<tr>
<td><input type="text" id="mySearch3" name="mySearch3" size="40" onkeypress="activateCheckbox('box3')"/></td>
<td><input type="checkBox" id="box3" name="box3"/></td>
</tr>
You have a couple of options. You can do:
…or personally, I think this is a bit more clear:
The first approach works because in JavaScript
obj.somePropertymeans the same semantically asobj["someProperty"]. So if you have a variable that stores the name of the property you want to access, you can always doobj[name]to access the property.The second approach is just finding the checkbox in the DOM by its
id. It seems cleaner to me, since you are setting theidof each checkbox anyways and since you called your variable “id”.Also note that your
ifstatement is superfluous. Thecheckedattribute will only ever betrueorfalse(you can subvert this by storing other things there, but that’s a completely separate topic). So setting it totruewhenever it isfalseis logically equivalent to always setting it to true, and you can implement your handler function with a single line, like: