Reputation: 741
I've searched through the site for this but am coming up empty handed. Here is what I am trying to do:
See the image below for a visual representation of what I mean:
I know that I am going to need JavaScript for this solution, but my JS skills are not so hot (and I think I am having a momentary lapse of brain power today)!
Here's the code that I have so far (don't worry about the outdated PHP):
<select name="item" id="item">
<?php
while($row = mysql_fetch_array($result)) {
$item_id = $row['item_id'];
$item_category = $row['item_category'];
$item_title = $row['item_title'];
$item_price = $row['item_price'];
$item_description = $row['item_description'];
echo "<option value=\"".$item_id."\">".$item_title."</option>";
}
?>
</select>
<script>
function update_txt() {
price = document.getElementById('item').selectedIndex.value;
document.getElementById('item_details').value = price;
document.getElementById('item_price').value = price;
}
</script>
<input id="item_details" type="text" class="validate">
<input id="item_price" type="text" class="validate" value="$">
Any help is greatly appreciated! Let me know if you need any clarification. :)
Upvotes: 3
Views: 3531
Reputation: 479
You can use a combination of PHP, AJAX and JavaScript (or jQuery).
The general idea is as follows:
There's a good tutorial here which shows how it fits together: http://www.tizag.com/ajaxTutorial/ajax-mysql-database.php. I would use prepared statements instead of the SQL queries shown in this example though.
Upvotes: 1
Reputation: 64695
I would json encode the row and store it as a data-attribute on the option, then read the attribute on the selects change event:
<select name="item" id="item">
<?php
while($row = mysql_fetch_array($result)) {
$item_id = $row['item_id'];
$item_title = $row['item_title'];
echo "<option value=\"".$item_id."\" data-json='" . json_encode($row) . "'>".$item_title."</option>";
}
?>
</select>
<input id="item_details" type="text" class="validate">
<input id="item_price" type="text" class="validate" value="$">
<script>
$('#item').on('change', function() {
var selected = $(this).find('option[value="' + $(this).val() + '"]').data('json');
$('#item_details').val(selected.item_description);
$('#item_price').val(selected.item_price);
});
</script>
Upvotes: 4