I have a MySQL database table which has a unique ID identifier for each line:
id text cat
4 abc 1
233 bbb 2
45 efa 1
Using PHP, I show an HTML table where you can see the TEXT and CAT fields. Each row of the table is shown using a "while" loop. As you can see, I also store the IDs in the array $val
.
<?php
....
$val = array();
while($objResult = mysql_fetch_array($objQuery)){
$val[] = $objResult["id"];
?>
<table>
<tr>
<td><?php echo $objResult["text"];?></td>
<td><?php echo '<a href="#" id="open">'.$objResult["cat"].'</a>';</td>
<tr>
<?php
}
?>
</table>
Now comes the tricky part. Using JQuery, I would like to be able to click on the CAT cells in the html table and open a dialog window where I can change the value of CAT. Here is the form:
<form action="modcat.php" method="POST" id="modcat">
<table>
<tr>
<td>
<select id="cat">
<option value="a">a</option>
<option value="b">b</option>
<option value="c">c</option>
</select>
<input type="hidden" name="val" value="<?php
for ($i = 0; $i < 1000; $i++) {
echo $val[$i];
}
?>">
</td>
</tr>
</table>
</form>
<script>
$(document).ready(function () {
$("a#open").click(function () {
$('#finestra').dialog("open");
return false;
});
$('#finestra').dialog({
modal: true,
autoOpen: false,
buttons: [{
text: "modifica",
click: function () {
submitform();
$(this).dialog("close");
}
}, {
text: "annulla",
click: function () {
$(this).dialog("close");
}
}]
});
function submitform() {
$('#modcat').submit();
}
});
</script>
As you can see, I am trying to send to the form the corresponding value of ID (through a hidden input). As it turns out, I put together all the IDs of all the table in the array $val
. How can I send to the form just the one which is chosen?
You can add the id to the html someplace, retrieve it in the click function, and add it to the form before submitting.
Here, i am adding the id as a data attribute, i also changed the id on the a element to a class, since your rendered html will contain multiple a elements, and ids should be unique
while($objResult = mysql_fetch_array($objQuery)):?>
<table>
<tr>
<td><?= $objResult['text'];?></td>
<td>
<a href="#" class="open" data-id="<?=$objResult['id'];?>">
<?=$objResult['cat'];?>
</a>
</td>
<tr>
</table>
<?php endwhile;
For the form, dont prepopulate the hidden field, just give it an id so its easy to target in js:
<form action="modcat.php" method="POST" id="modcat">
<table>
<tr>
<td>
<select id="cat">
<option value="a">a</option>
<option value="b">b</option>
<option value="c">c</option>
</select>
<input type="hidden" name="val" id="hidden-id">
</td>
</tr>
</table>
</form>
Then in your js update the value from the data attribute:
$(document).ready(function () {
$("a.open").click(function () {
var clickedLink = $(this); //get clicked link
var id = clickedLink.data('id'); //extract id from data attribute
$('#hidden-id').val(id); //update hidden field value with id
$('#finestra').dialog("open");
return false;
});
...