Reputation: 9778
I use the following javascript function,
function get_check_value(formId,checkboxId,TxtboxId)
{
alert(formId);
var c_value = "";
for (var i=0; i < document.formId.checkboxId.length; i++)
{
if (document.formId.checkboxId[i].checked)
{
c_value = c_value + document.formId.checkboxId[i].value + "\n";
}
}
alert(c_value);
document.getElementById(TxtboxId).value= c_value;
// alert(c_value.value);
}
and my php page has this,
<form name="orderform" id="orderform">
<input type="text" name="chId" id="chId" >
<table align="center" border="0">
<tr>
<td>Country</td>
</tr>
<? foreach($country as $row){ ?>
<tr>
<td><?= $row['dbCountry']; ?></td>
<td><input type="checkbox" name="CountrycheckId" id="CountrycheckId" value="<?= $row['dbCountryId']; ?> " onClick="get_check_value('orderform','CountrycheckId','chId')"></td>
<? } ?>
</tr>
</table>
</form>
I am getting formname,checkboxid,textid in alerts inside the javascript function... But
the problem is with the line
for (var i=0; i < document.formId.checkboxId.length; i++)
Webdeveloper toolbar shows this error
document.formId is undefined
Upvotes: 0
Views: 609
Reputation: 187020
I think you are having multiple elements with the same id inside the document. This isn't valid. Ids are unique and cannot be assigned to multiple elements. You can use name for this and get those elements using
document.getElementsByName("name");
var checkBoxes = document.getElementsByName('CountrycheckId');
var c_value = new Array();
for (var i=0; i < checkBoxes.length; i++)
{
if (checkBoxes[i].checked)
{
c_value.push(checkBoxes[i].value);
}
}
// join the array using any delimiter like
c_value.join(',');
If you can use a framework like jQuery it would be much more simple
$("input:checkbox[name='CountrycheckId']:checked").each(function(){
c_value.push(this.value); //or
c_value.push($(this).val());
});
Upvotes: 0
Reputation: 17977
var selects = document.getElementsByName('CountrycheckId');
for (var i=0; i < selects.length; i++)
{
if (selects[i].checked)
{
c_value = c_value + selects[i].value + "\n";
}
}
Upvotes: 4
Reputation: 30723
You need to access the form via getElementById(formId), see below:
function get_check_value(formId,checkboxId,TxtboxId)
{
alert(formId);
var c_value = "";
for (var i=0; i < document.getElementById(formId).checkboxId.length; i++)
{
if (document.formId.checkboxId[i].checked)
{
c_value = c_value + document.formId.checkboxId[i].value + "\n";
}
}
alert(c_value);
document.getElementById(TxtboxId).value= c_value;
// alert(c_value.value);
}
When you write document.formId Javascript will look for a property of document whose name is (literally) "formId" when you use document.getElementById(formId) Javascript will look for an HTML element whose id is whatever the variable formId is holding.
Upvotes: 0