JQuery with Forms
I have the following HTML:
<form class="lala">
<input type="text" id="textv" value="Text 1" size="5">
<input type="submit" value="Go!"></form>
<form class="lala"><input type="text" id="textv" value="Text 2" size="5"><input type="submit" value="Go!"></form>
Now I have开发者_运维知识库 the following JQuery:
$(document).ready(function(){
$(".lala").submit(function() {
alert($("#textv").val());
});
Of course this is not working (I know I shouldn't use duplicate IDs) , but how can I show an alert of the text value where the corresponding submit button was clicked?
Thanks, Joel
$(function(){
$("form.lala").submit(function(){
alert($(this).find(":text:last").val());
});
});
this should work
$(document).ready(function(){
$(".lala").submit(function(){
alert($("#textv").val());
return false;
});
}
You are almost there in the first place. Just give ur selector a context of the submitted form. Note the addition of ",this":
$(function() {
$('.lala').submit(function() {
alert($('#textv',this).val());
});
});
You should be able to access the <input type="text">
which is placed just before the <input type="submit">
in the markup, using the prev()
function:
I misread your original jQuery snippet, and thought you where handling the click
event on the button, rather than the submit
event on the form. Your problem should be solvable by using the overload of the jQuery
function, that takes a context
parameter:
$(document).ready(function(){
$(".lala").submit(function() {
alert($("#textv", this).prev().val());
});
});
This assumes that the browser does indeed build the object model with two elements having the same ID. If this does not work, try changing the selector in the line 3 to input[type=text]
Also, your code sample is missing a set of });
in the end, but I guess this is just a copy/paste mistake made when posting the question.
精彩评论