there's a php scripts which create multiple <p>text</p>
elements due to user's query. I'd like to create an option that every time user clicks on a certain element , the text in this elements will appear in a text box. The intuitive way to do such task is:
<p class="c1"> textA...</p>
<p class="c2"> textB...</p>
<p class="c3"> textC...</p>
<p class="c4"> textD...</p>
and the jQuery code will be :
$("p.c1").click(function(){ code... }
$("p.c2").click(function(){ code... }
etc ...
Is there any elegant method of implementing this functionality ?
Any suggestion will be helpful,
Thanks in advance
you can assign multiple classes to HTML elements. You can change your PHP script to output mutliple classes. i.e.
<p class="c1 clickable"> textA...</p>
<p class="c2 clickable"> textB...</p>
<p class="c3 clickable"> textC...</p>
<p class="c4 clickable"> textD...</p>
Then you can use the click function.
$("p.clickable").click(function () {
$('#yourtextbox').val($(this).text());
});
Event delegation.
$('body').on('click', 'p[class^=c]', function(evt) {
var clickedPara = $(this);
});
There, I filter on paragraphs whose class
attribute starts with c
. This is just demonstrative but is ultimately likely not very watertight. You should give your elements a common class. If this class was, say, 'clickablePara', you could instead use
$('body').on('click', 'p.clickablePara', function(evt) {
Event delegation means you bind one event and evaluate the trigger element when it fires, rather than binding lots of events to each possible element. If this is new to you, it's worth looking into. If you happen to be in the UK, the upcoming edition of .NET Magazine has an article by me discussing it.
It does'nt say anything about dynamic elements inserted with ajax, so I'm guessing the elements are created serverside before the page is outputted and that delegation is'nt neccessary ?
$("p[class^='c']").on('click', function() {
$("#textboxID").val(this.innerHTML);
});