javascript - Retrieve data from MySQL according to the item_ID selected from the select box -


i have populated mysql database, database has 2 columns (item_id, item_title), , html page has select box, item_ids stored, , below have input box, want following: when user selects item_id select box, should go database , find out item_title belongs item_id. using php, don't know how carry such task. thank in advance.

nb: okay populating select box available item_ids. thing not sure how implement retrieve item_title dynamically item_id changes, , display inside input box.

<select name='item_id'> <option>1</option> <option>2</option> <option>3</option> <option>4</option> </select>  <input name='item_title' value='should change item_id changes' /> 

let's generate select element dinamically php:

<?php      while($row = mysql_fetch_assoc($some_query)) {         echo "<option>" + $row["id"] + "</option>";     }  ?> 

right? why not add title in same query , generate select it?

echo "<option data-title='" + $row["title"] + "'>" + $row["id"] + "</option>"; 

nice, select looks like:

<select name='item_id'>     <option data-title="title 1">1</option>     <option data-title="title 2">2</option>     <option data-title="title 3">3</option>     <option data-title="title 4">4</option> </select> 

now bind change event select this:

$("#item_id").on("change", function(e) {     var selectedoption = $("option:selected", this);     $("#item_title").val($(selectedoption).data("title")); }); 

don't forget add id="item_title" title field.

so, approach won't need request , query database in order title adding in same query use create select(with inner/left join if table, think). thus, increase application performance.

update:

the event binding should stay on ready event of document, this:

$(document).ready(function() {     $("#item_id").on("change", function(e) {         var selectedoption = $("option:selected", this);         $("#item_title").val($(selectedoption).data("title"));     }); }); 

and more columns add them data- prefix option element attributes:

<option data-title="" data-other-property=""></option> 

and on... access use same method:

$(selectedoption).data("title"); $(selectedoption).data("other-property"); 

considering selectedoption stands option element.

some references worth reading:


Comments

Popular posts from this blog

php - SPIP: From Tag directly to an article -

jquery - isAjaxRequest always return false -

ruby on rails - In a controller spec, how to find a specific tag in the generated view? -