Hi. I have one drop down menu and one textfield. The drop down menu will display the book's id and book's name that retrieve from the database while the textfield will automatically display the book's name based on the user selection from the drop down menu. I try to use the javascript function to do this but since the value for the option is book's id so the textfield is displayed the book's id but not the book's name. What should I do so that the textfield will display the book's name? Below are parts of the code.

<?php  $sql = "SELECT * FROM store ORDER BY book_id"; 
       $result = mysql_query($sql); 
?>
<select name="book_id" id="book_id" class="font" onChange="updateText();"><option value=""></option> 
<?php while($row = mysql_fetch_array($result))
      { ?> 
	<option value="<?php echo $row['book_id']; ?>" class="font"><?php echo $row['book_id']; ?>&nbsp;&nbsp;<?php echo $row['book_name']; ?></option>
<?php }?>
</select>
<input type="text" name="book_name" id="book_name" class="font" readonly="readonly">

javascript code:

<script type="text/javascript">
function updateText()
{	
   document.getElementById("book_name").value = document.getElementById("book_id").value;
}
</script>

Thanks in advance.

Hi,

Replace your javascript function with this below function.

function updateText()
{	
  	var dd = document.getElementById("book_id");
	var ddtext = dd.options[dd.selectedIndex].text;
	var sp_ddtext = ddtext.replace(/[^ a-zA-Z]+/g,'');
	document.getElementById("book_name").value = sp_ddtext;
}

Thanks a lot, paulraji. The code is really work for me and solve my problem. Thanks.

Hi. If my book_id is in alphanumeric it will also read the alphabet. For example, if the book_id is 001FT then when display the name, it will display as FTSnow White. So how to make sure that it just display the book_name as Snow White? Thanks in advance.

Hi,

Check out this below function.

function updateText()
{	
  	var dd = document.getElementById("book_id");
	var ddtext = dd.options[dd.selectedIndex].text;
	var sp_ddtext = ddtext.replace(/(\w+)\s\s+/g,'');  // replaces the first part (book_id)
	document.getElementById("book_name").value = sp_ddtext;
}

Thanks a lot, paulraji. The code solved my problem. Thanks.

This is in interesting . What if I also want on selection of the book name, the book ISDN and publishers to show on the ISDN and publishers text field.
Thanks all
Emeka

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.