...

View Full Version : Changing PHP form array values using JavaScript



bauhsoj
03-09-2005, 05:21 AM
Say I have the following PHP code:

<form name="value_list" method="POST" action="value_lister.php">
<?php
foreach ($somevar as $k=>$v) {
?>
<tr>
<td>
<input name="form_var[<?=$k ?>][name]" type="text" size="40" value="<?=$v['name'] ?>" />
</td>
<td>
<input name="form_var[<?=$k ?>][number]" type="text" size="8" value="<?=$v['number'] ?>" />
</td>
<td>
<select name="form_var[<?=$k ?>][type]">
<option value="static" onClick="document.value_list.form_var[<?=$k ?>][number].disabled=false"<?=($v['type']=='static'?' selected':'') ?>>Static</option>
<option value="dynamic" onClick="document.value_list.form_var[<?=$k ?>][number].value='';document.value_list.form_var[<?=$k ?>][number].disabled=true"<?=($v['type']=='dynamic'?' selected':'') ?>>Dynamic</option>
</select>
</td>
</tr>
<?php
}
?>
</form>

How would I get the JavaScript embedded in the options of <select name="form_var[<?=$k ?>][type]"> to function correctly, disabling or enabling the specific form_var[<?=$k ?>][number] field? The above does not seem to work as-is.

I figure this has probably been asked before but I couldn't find a correct solution to what I was looking for...unless I have misread some other posts. I am not so great with JavaScript, unfortunately. :rolleyes:

Thanks in advance for any help!

glenngv
03-09-2005, 06:37 AM
It does not work because <option> tags don't have onclick event. You should use onchange event in <select> tag.

glenngv
03-09-2005, 06:47 AM
I think this is what you want.

<head>
<script type="text/javascript">
function enableDisableField(oSel, index){
var oFld = oSel.form.elements["form_var[" + index + "][number]"];
if (oSel.selectedIndex == 0){ //Static
oFld.disabled = false;
}
else { //Dynamic
oFld.value = "";
oFld.disabled = true;
}
}
</script>
</head>
<body>
<form name="value_list" method="POST" action="value_lister.php">
<?php
foreach ($somevar as $k=>$v) {
?>
<tr>
<td>
<input name="form_var[<?=$k ?>][name]" type="text" size="40" value="<?=$v['name'] ?>" />
</td>
<td>
<input name="form_var[<?=$k ?>][number]" type="text" size="8" value="<?=$v['number'] ?>" />
</td>
<td>
<select name="form_var[<?=$k ?>][type]" onchange="enableDisableField(this, <?=$k ?>)">
<option value="static"<?=($v['type']=='static'?' selected':'') ?>>Static</option>
<option value="dynamic"<?=($v['type']=='dynamic'?' selected':'') ?>>Dynamic</option>
</select>
</td>
</tr>
<?php
}
?>
</form>

bauhsoj
03-09-2005, 08:31 PM
Thanks! That looks like what I need. I will try it and see if it works for me. :thumbsup:

bauhsoj
04-28-2005, 06:21 PM
Thanks, this worked for me. Took some time before I had chance to go back and try this again.



EZ Archive Ads Plugin for vBulletin Copyright 2006 Computer Help Forum