...

View Full Version : Select Radiobox on Text Field Input



SteveSensei
09-25-2009, 10:46 PM
I have an existing form with radio buttons and a text input field:

<input type="radio" name="recurringEnd" value="yes"> End after <input type="text" name="numberOccurrences" size="1"> occurrences

<input type="radio" name="recurringEnd" value="date"> End on <input type="text" name="endDate" size="8">

My client now wants it setup so that if the text field is filled in, the radiobox is automatically selected.

Any help on this would be greatly appreciated as I am not a JS programmer.

jolly_nikki
09-25-2009, 11:19 PM
<html>
<body>
<html>
<head>
<script>
function selectRadioButton(obj){
if(obj.value != ""){
obj.previousSibling.previousSibling.setAttribute("checked", true);
}else{
obj.previousSibling.previousSibling.removeAttribute("checked");
}
}
</script>
</head>
<body>
<input type="radio" name="recurringEnd" value="yes"> End after
<input type="text" name="numberOccurrences" size="1" onKeyup = "selectRadioButton(this)"> occurrences
<input type="radio" name="recurringEnd" value="date"> End on
<input type="text" name="endDate" size="8" onKeyup = "selectRadioButton(this)">
</body>
</html>
</body>
</html>

Old Pedant
09-25-2009, 11:31 PM
The thing wrong with using onkeyup, that everybody misses, is that anybody who copy/pastes into the form field using a mouse alone will not trigger it.

I'd just use onchange or onblur.

The button won't change state until the cursor leaves the text box, but it will work even with a mouse copy.

Nikki's code also assumes that the radio button immediately precedes the text field.

I'd keep it dirt simple:


<input type="radio" name="recurringEnd" value="yes"> End after
<input type="radio" name="recurringEnd" value="date"> End on
... maybe lots of html ...
<input type="text" name="numberOccurrences" size="1" onchange="selectRB(this,'recurringEnd','yes')"> occurrences
<input type="text" name="endDate" size="8" onchange="selectRB(this,'recurringEnd','yes')">
...
Then the code:

selectRB(txt, rbname, val)
{
var rbgroup = txt.form.elements[rbname];
for ( var r = 0; r < rbgroup.length; ++r )
{
var rb = rbgroup[r];
if (rb.value == val)
{
rb.checked = txt.replace(/\s/g,"").length > 1;
return;
}
}
}

Needs more code if it's possible there is only one radio button of the given name (which means it should maybe be a check box, but...).

SteveSensei
09-26-2009, 12:47 AM
Many thanks jolly_nikki. Works great!



EZ Archive Ads Plugin for vBulletin Copyright 2006 Computer Help Forum