tags:

views:

38

answers:

4

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

A: 

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.

Jørn Schou-Rode
this is not very friendly. if he wants to use an extra inputfield. working with selectors seems better to me
michel
Sure, but considering the markup there is *nothing* to select on, apart from a duplicated `id` attribute.
Jørn Schou-Rode
A: 

this should work

$(document).ready(function(){
$(".lala").submit(function(){
      alert($("#textv").val());
      return false;
});
}
michel
I think you might have misread the question. How do you ensure that the selector finds the right `#textv` when there are two such elements in the DOM?
Jørn Schou-Rode
+1  A: 
$(function(){
    $("form.lala").submit(function(){
        alert($(this).find(":text:last").val());
    });
});
Shein Alexey
yup, this works, I just tried it at: http://jsbin.com/oguna3/edit
rohancragg
A: 

Hey Joel,

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());
    });
});
ilovewebdev