Reputation:
I'm new to JQuery and I have some troubles to solve this problem. I have to generate input fields from a dynamic List (using ASP.NET MVC4), the point is that I don't know the size of the List in advance.
I generate input boxes like this :
<ul>
@for(int i=0;i< Model.listeVisites.Count;i++)
{
<li><input id="input-visite+@i" type="text" value="@Model.listeVisites[i]" /></li>
}
</ul>
And I would like to create a button for each input so that when it is clicked, the input field is hidden with .hide(), and the field is set to the empty string. However I can't figure out two things :
1) With Jquery I don't really know how I can link a function to an event. In "normal" javascript I would have added an Onclick attribute to the input fields, but how can I achieve it with Jquery ?
2) What is the simplest and the more conventional way to achieve my goal, considering the dynamic and unpredictible nature of my id names.
Thank you !
Upvotes: 1
Views: 84
Reputation: 337560
First of all, add a class
or id
to your ul
so it can be easily identified. Then try this:
$('#myUl li input').each(function() {
$(this).after($('<button />', { text: 'Hide' }));
});
$('#myUl').on('click', 'button', function() {
$(this).prev('input').hide();
});
Upvotes: 2