0

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 

2 Answers 2

2
$('form').submit(function() {

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

    return false;

});
Sign up to request clarification or add additional context in comments.

Comments

2

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.