this is a really basic jQuery question, but i’m not sure how to do this:
<input type=text class=city />
<ul class="cityList">
<li><a href="#">Test 1</a></li>
<li><a href="#">Test 2</a></li>
<li><a href="#">Test 3</a></li>
</ul>
What I want to do is to just get the Text (Test 1, 2 etc) of any clicked li a and put into the textbox
The following will do what you want.
How it Works
$('.cityList a')returns an array of elements, bound with jQuery, that match the selector. In this case, all the links within any elements with a class of cityList..click(...)adds an event to all items called upon, which is the previous array.function(){}is an anonymous function. When called,thisis the element that has been clicked on. (Remember, this function represents the event we’re binding.)$('input.city')finds the textbox with the given class, but it could be multiple boxes. To prevent that, give it an ID in the HTML and change the selector to “#myID”..val(...)sets the value of the textbox to the first parameter.$(this).text()will return the text of the link, which will be set as the textbox’s value (represented by the above code-ellipsis).e.preventDefault();stops the browser from visiting the link that was just clicked. (However, this method will cancel any default behavior for any event.)