Reputation: 41
I am currently working on a solution for an application that is written in PHP, but needs a JS solution for a preview link and I am stuck with binding onclick-events on the links. The HTML is given and may not be changed. (so no adding of classes and stuff, even though that would be easier)
My initial thought was to just get each of the li and perform a callable that sets the event and defines the rules for what happens, when the link is clicked.
I am unsure what is the best possible solution to get the values of the two Inputs, belonging to the preview link, as while I was running the code mentioned above on what ever link I clicked, the last item was logged.
So basically this is 2 questions in one: 1. how to properly bind the click events. 2. how to best acces the inputs belonging to the link
var items = $('div.foobar').find('li');
items.each(function() {
this = $(this);
url = lo_this.find('a').attr('href');
this.find('a').click(function(event) {
event.preventDefault();
console.log(this)
/** here is the point, where I got stuck **/
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="foobar">
<li>
<a href="somelinkwithID">Link</a>
<div class="justaname">
<input type="text" name="somenamewith[ID][foo]" value="">
<input type="text" name="somenamewith[ID][bar]" maxlength="50" value="">
</div>
</li>
<li>
<a href="somelinkwithOTHERID">Link</a>
<div class="justaname">
<input type="text" name="somenamewith[OTHERID][foo]" value="">
<input type="text" name="somenamewith[OTHERID][bar]" maxlength="50" value="">
</div>
</li>
</div>
Upvotes: 0
Views: 48
Reputation: 177684
You mean this?
Other code is needed if you want to use the ID of the link to access the named links
$('div.foobar li a').on("click",function(e) {
e.preventDefault();
$(this).closest("li").find("input").each(function() {
console.log(this.name,this.value)
})
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="foobar">
<li>
<a href="somelinkwithID">Link</a>
<div class="justaname">
<input type="text" name="somenamewith[ID][foo]" value="">
<input type="text" name="somenamewith[ID][bar]" maxlength="50" value="">
</div>
</li>
<li>
<a href="somelinkwithOTHERID">Link</a>
<div class="justaname">
<input type="text" name="somenamewith[OTHERID][foo]" value="">
<input type="text" name="somenamewith[OTHERID][bar]" maxlength="50" value="">
</div>
</li>
</div>
Upvotes: 1
Reputation: 124
You can do this to bind click events to your links and then do whatever with the input elements contained by the div after the clicked link:
$('.foobar li a').on('click',function(event){
event.preventDefault();
$(this).next().find('input').each(function(){
//Whatever you want to do for each input
});
});
Upvotes: 0