UmarAbbasKhan UmarAbbasKhan - 2 months ago 7
HTML Question

how to pass value to javascript through clicking <li> element

I have the following Unordered List which has been dynamically populated from database through JQuery .ajax, with a few list items which are names of the products.

<ul id="here">
<li>Product 1</li>
<li>Product 1</li>
<li>Product 1</li>
<li>Product 1</li>
<li>Product 1</li>
</ul>


I can hover over these through mouse events in css with the following code

li:hover {background: #ccc; cursor: pointer;}


The javascript code for populating the
<li>
is as follows:

var pr= [Product1, Product2, Product3, Product4, Product5];
for (var option in pr){
var newLi = document.createElement("li");
newLi.innerHTML=pr[option];
$("#here").append(newLi);}


But I want to pass the Product Name inside of the
<li>
element to another input element through Javascript or JQuery when that
<li>
element is clicked. How can I do this?

Answer

Since I see you are using jQuery, you can bind the ul's "click" event like so:

$("#here").on("click", "li", function(evt) {
   $("#your_Input_Id").val(evt.target.innerHTML);
});

Example at jsfiddle: https://jsfiddle.net/bkbtert9/

Comments