June 25, 2012
PHP Populate Text box from Select – Array fields
Question by user1479891
I need to populate the relevant text box with the results of a Select drop down.
My Javascript so far is
<script language="JavaScript">
var mytextbox = document.getElementById('error');
var mydropdown = document.getElementById('errormsg_id');
mydropdown.onchange = function(){
mytextbox.value = this.value;
}
</script>
My select box and text boxes are built as arrays from a query so there is nultiple of them.
I need to be able to populate the corresponding text box with the results from the Select next to it.
Any ideas?
Thanks
<td width="1%">
<select style="width:100%" name="errormsg_id[]" id="errormsg_id[]">
<?php do { ?>
<option value="<?php echo $row_rserrormsg['errormsg_id']?>"
<?php if ($row_rsdates['errormsg_id'] == $row_rserrormsg['errormsg_id']) { echo("selected='selected'"); } ; ?> >
<?php echo $row_rserrormsg['error_message']?></option>
<?php } while ($row_rserrormsg = mysql_fetch_assoc($rserrormsg)); ?>
<?php mysql_data_seek($rserrormsg, 0);
$row_rserrormsg = mysql_fetch_assoc($rserrormsg);?>
</select>
</td>
<TD align="center" class="adminuser">
<input style="width:96%;text-align:left;" autocomplete="on" title="Enter Error Message" type="text" name="error[]" id="error[]" value="<?php echo $row_rsdates['error_message']; ?>" maxlength="100"/>
</TD>
Answer by Starx
You need to think of way to uniquely identify your corresponding set of elements. The most convenient way I would suggest would be to use the primary key value of the data row.
And example would be like
while($row = mysqli_fetch_assoc($result)) {
$id = $row['id']; //A primary key field
echo '<input type="text" name="text'.$id.'" id="text'.$id.'" />';
echo '<select name="select'.$id.'" id="select'.$id.'" />...</select>";
}
Next, call a function from the select menu, so that only the relevant text box is updated. Update the above select portion to read something similar to this.
echo '<select name="select'.$id.'" id="select'.$id.'" onchange="updateBox('text'.$id.'', this.value)" />...</select>";
Now, create a very simple simple function to update the text box.
function updateBox(element, value) {
el = document.getElementById(element);
el.value = value;
}