Javascript Function for PHP Looped Elements
Hi all,
I've got a script that I found on these forums that gives a text-box to a set of radio options. It's essentially an 'other___' box.
It works great, however, my php contains a loop where the strip of radio options would appear multiple times on one page. Not knowing too much javascript, I was hoping someone could help me generalize this JS so it can exist in multiple instances on the page.
JS
Code:
function displayTextBox()
{
var objElement = document.getElementById('otherTextBox');
otherTextBox.style.display = 'block';
otherTextBox.style.visibility = 'visible';
}
function hideTextBox()
{
var objElement = document.getElementById('otherTextBox');
otherTextBox.style.display = 'none';
otherTextBox.style.visibility = 'hidden';
}
function validate()
{
var arrElements = document.getElementsByName('choice');
var objElement;
var boolContinue = false;
var objOtherText;
for(var i=0, _length=arrElements.length; i<_length; i++)
{
objElement = arrElements[i];
if(objElement.checked)
{
if(objElement.id == 'choice5')
{
objOtherText = document.getElementById('othertext');
if(strTrim(objOtherText.value).length>0)
{
boolContinue = true;
break;
}
}
else
{
boolContinue = true;
break;
}
}
}
if(boolContinue)
{
alert('Continue, user completed the information.')
}
else
{
alert('Ask user to complete the data.')
}
}
/**
* Removes all white space characters from the string.
*
* @param: {String} String to trim.
*
* @return {String} Trimed string.
*/
function strTrim(strTrim)
{
return strTrim.replace(/^\s+|\s+$/g, '');
}
The HTML that is being looped in PHP
HTML Code:
<form name='' class='form' action='js/submit.php' method='post'>
<label for='choice1'>Keep:</label>
<input type='radio' name='dec[]' id='choice1' value='keep' onclick='hideTextBox()'>
<label for='choice2'>Donate:</label>
<input type='radio' name='dec[]' id='choice2' value='donate' onclick='hideTextBox()'>
<label for='choice3'>Sell:</label>
<input type='radio' name='dec[]' id='choice3' value='sell' onclick='hideTextBox()'>
<label for='choice4'>Trash:</label>
<input type='radio' name='dec[]' id='choice4' value='trash' onclick='hideTextBox()'>
<label for='choice5'>Give To:</label>
<input type='radio' name='dec[]' id='choice5' value="" onclick='displayTextBox()' />
<div id='otherTextBox' style='display:none;visibility:hidden;'>
<textarea id='othertext' cols='15' rows='1' style='resize:none;' name='dec[]'></textarea>
</div>
<input type='hidden' name='id' value='<?= $row['Id'] ?>' /><br />
<input type='submit' value='Submit' onclick='validate()'>
</form>