Tell me more ×
Stack Overflow is a question and answer site for professional and enthusiast programmers. It's 100% free, no registration required.

I have created a page with two forms. Each form has a text box and a submit button. When either form is fired, I want the (same) submit function to be fired. The function must then be able to tell which form was fired, getting the entered text as well as an ID.

It works for the first form, but not for the second form. When I click the second Submit button, it correctly gets the id="1", but it reads the input from the first text box. In general I'm having a hard time navigating targets: sometimes it's only the first of the elements that causes the firing and sometimes it's all.

      <div> 
      <p>First form</p> 
      </div> 
      <div class = 'add_video_form' id = "3"> 
      <form  method="post" action="dummy/"> 
          <input type="text" id="url"> 
          <input type="submit" value = "Add video"> 
         </form> 
       </div>          
      <div> 
      <p>Second form</p> 
     </div> 
        <div class = 'add_video_form' id = "1"> 
      <form  method="post" action="dummy/"> 
          <input type="text" id="url"> 
          <input type="submit" value = "Add video"> 
            </form> 
  </div>       

The script is:

$(document).ready(function(){

  $("form").submit(function() {

   var v_new_url = $("input#url").val(); 

   var v_cat_id =  $(event.target).parents(".add_video_form").attr("id");


   alert(v_new_url);
   alert(v_cat_id);

   return false;

});   
     });     //end of $(document).ready 
share|improve this question

2 Answers

up vote 0 down vote accepted
$('form').submit(function() {

    var input_value = $(this).find('input:text').val();
    var id = $(this).parent().attr('id');

    return false;

});
share|improve this answer
Great, that works! – dkgirl Jan 2 '11 at 15:24

You have some issues with your IDs.

The main answer to your question is to use this to refer to the <form> that received the event:

var v_new_url = $(this).find("input#url").val();

The trouble is that an ID can not start with a number in HTML4.

<div class = 'add_video_form' id = "3"> <!-- invalid ID in HTML4 -->

and you can not have duplicate IDs on the same page.

 <!-- first form -->
<input type="text" id="url"> <!-- duplicate ID -->

 <!-- second form -->
<input type="text" id="url"> <!-- duplicate ID -->

It would be better if url was a class:

 <!-- first form -->
<input type="text" class="url"> 

 <!-- second form -->
<input type="text" class="url"> 

Then select by the class:

var v_new_url = $(this).find("input.url").val();
share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.