Reputation:
I'm a beginner with Jquery and I have this little problem that I don't know how to fix. I've tried to debug with JSFiddle but I had no success so here my problem :
I have two div elements, in the first div I have several textboxes and in the second div I have my button. I would like that when I click on the button, a particular textbox in the first div become empty.
Okay, the whole picture is that I don't know the textbox name in advance (a list is fetch and ASP.NET MVC automatically names my input fields), so the only thing I know is that I want to empty the first textbox whose name property value finishes with "input1" (its beginning being auto-generated). I also know that the textbox I'm interested in is the one that immediately precedes my button. I hope I was clear.
Here is my Fiddle which is not working : http://jsfiddle.net/XvTNh/1/
Any help would be appreciate !
HTML:
<div class="myClass1">
<input name="fdsgginput1" type="text" value="Salé sucré"/>
<input name="gfsginput2" type="text" value="Macarons"/>
</div>
<div class="myClass2fdsff">
<input type="submit" name="envoyer" />
JS:
$("div[class^='myClass2']").on('click','input[name="envoyer"]',function(){
$(this).closest('input[name$="input1"]').val('');
});
Upvotes: 0
Views: 464
Reputation: 1103
Try this:
<script>
$(document).ready(function(){
$('.myClass2fdsff input[type=submit]').click(function(){
$('.myClass1 input:first').val(''); // Empty first textbox
$('.myClass1 input[name*=input1]').val(''); //Empty input with input1 in name
});
});
</script>
Upvotes: 0
Reputation: 1898
Try this
$("body").find('input[name$="input1"]').first().val('');
Upvotes: 0
Reputation: 237905
You're basically attempting to navigate around the DOM. closest
does not go hunting for other elements that may be nearby in the HTML. Rather it goes up the DOM tree, looking at ancestor elements, and looks to see if any element matches the selector you pass.
Since the element you want is not an ancestor element, it will not be found. You actually need to add a common ancestor element (in reality your HTML probably already contains one) and then combine closest
and find
to find the element:
$("div[class^='myClass2']").on('click', 'input[name="envoyer"]', function () {
$(this).closest('.container').find('input[name$="input1"]').val('');
});
Upvotes: 1