0


I want to ask how i can get value of input ONLY ON SUBMIT in Javascript from HTML form when i have many forms with same name on one page.

It's looking like this:

First printed HTML form:

<div id="addCommentContainer3">
<form class="add-comment-form" id="addCommentForm3" method="post" action="">
<input type="hidden" value="3" name="comentonpost" id="comentonpost"/>
<textarea class="commentinput" name="body" id="body" cols="20" rows="5"></textarea>
<input type="submit" id="submit" value="Submit" />
</form>
</div>

Second printed:

<div id="addCommentContainer2">
<form class="add-comment-form" id="addCommentForm2" method="post" action="">
<input type="hidden" value="2" name="comentonpost" id="comentonpost"/>
<textarea class="commentinput" name="body" id="body" cols="20" rows="5"></textarea>
<input type="submit" id="submit" value="Submit" />
</form>
</div>

And like this there are many more .

I must take the value of comentonpost because i need it in my Javascript so when i post comment it wil appear before addCommentContainer of the submited form.
And there is the whole Javascript:

$(document).ready(function(){

var name_element = document.getElementById('comentonpost');
var x = name_element.value;

/* The following code is executed once the DOM is loaded */

/* This flag will prevent multiple comment submits: */
var working = false;

/* Listening for the submit event of the form: */
$('#addCommentForm'+x).submit(function(e){

    e.preventDefault();
    if(working) return false;

    working = true;
    $('#submit').val('Working..');
    $('span.error').remove();

    /* Sending the form fileds to submit.php: */
    $.post('comment.submit.php',$(this).serialize(),function(msg){

        working = false;
        $('#submit').val('Submit');


            /* 
            /   If the insert was successful, add the comment
            /   below the last one on the page with a slideDown effect
            /*/

            $(msg.html).hide().insertBefore('#addCommentContainer'+x).slideDown();


    },'json');

});

  });

And in this way when i press the Submit button it's working only for the first form printed in the page.


My question is how i can fix this? How i can make it get the comentonpost value only of the submited form not the first printed, is there any better way this script may work?

Thanks in advance!

11
  • 2
    The inputs and textareas have the same id, which is invalid (and the id selector will only get the first one). You have already done it correctly for the addCommentContainerN and addCommentFormN, so you should be able to fix it yourself :-) Commented Jun 2, 2013 at 22:43
  • what is the var x in your selector? what is that supposed to do? Isn't it supposed to differentiate the forms from each other? Commented Jun 2, 2013 at 22:43
  • 2
    looks to me like you are only listening to the submit event on one form. Commented Jun 2, 2013 at 22:44
  • @AustinAllover that looks to me too. seems like he had forgotten about the x var. Commented Jun 2, 2013 at 22:46
  • Yes @MiroMarkarian this is the purpose of var x. Commented Jun 2, 2013 at 22:48

4 Answers 4

2

This will do what you need:

$(document).ready(function(){
    /* Watch OnSubmit for all forms */
    $('form').submit(function(e){
        e.preventDefault();

        /* Show the 'commentonpost' for the submitted form */
        alert($(this).children('#comentonpost').val());
    });
});

This works, but you should keep in mind that your document is not valid because you have elements that have the same IDs. IDs must be unique within a document for it to be valid.

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

2 Comments

What do you mean how my IDS must look like ?
IDs must be unique within a document, read section 7.5.2 in this document: w3.org/TR/html401/struct/global.html I am not suggesting you go and change all your IDs. I am just pointing out that you have an invalid document (you can search the web for why this is a bad idea). You have to decide what is more important to you: getting it done or have a valid document.
0

You may only need to change this part:

$(document).ready(function(){
  /* The following code is executed once the DOM is loaded */

  /* This flag will prevent multiple comment submits: */
  var working = false;

  /* Listening for the submit event on all the forms: */
  $('form[id^=addCommentForm]').on('submit', (function(e) {
    var submitted_form = $(this);
    //etc...

4 Comments

And there will be no problem if the form names are different like addCommentForm3 or addCommentForm2 it will work?
It will work, it means forms with id starting with addCommentForm, although Hugo Paz (@hugo-paz) refactoring is way better.
Yes but it should add comment on just one not all which starts with addCommentForm.
You do have a handle to the one form that was submitted in var submitted_form = $(this);
0

when you use jquery to select an ID, it will return 0 or one elements that match, and it will match the first one it finds. from http://api.jquery.com/id-selector/

Calling jQuery() (or $()) with an id selector as its argument will return a jQuery object containing a collection of either zero or one DOM element.

whenever you use $("#submit") its parsing through the DOM and finding the first instance of <input type="submit" id="submit" value="Submit" /> and returning that element. what you really want to do in your to scope your search down. you know you want the input from the form that was submitted, so you should try

$(this).find("#submit")

this will start at the form element, and search only elements contained inside the form for the first element with an ID of submit.

update

didnt realize your event was only tied to the first form, this whole things needs some work.

you've got a generic form template, and when you've got multiple forms like this, you really shouldnt be giving them all the same ID. instead, start binding event handlers to classes, and use the dom to store whether a form is 'working' or not as well

http://jsfiddle.net/neKdz/3/

17 Comments

I don't get it... where i must put this $(this).find("#submit") ?
IDs must be unique document-wide, a scoped search doesn't make much sense (though it works). Please suggest to use classes instead.
How my Javascript will look @Bergi to work with class? What i must change ?
@ViolinaMilanova: Remove the invalid ids, and change your '#submit' selectors to something like '#addCommentForm'+x+' input[type="submit"]'
@ragnarok56 In your jsfiddle the java script is not showing. I mean this is not there $(msg.html).hide().insertBefore('#addCommentContainer'+x).slideDown(); How this this must be? Thanks a lot man!
|
0

I would suggest something like this

$(document).ready(function(){
    $(".add-comment-form").submit(function(e){
        var x = $(this).find("#comentonpost").eq(0).val();
        // now you have number x of submitted form and you can do the rest
    }); 
});

Edit:

To prevent page reloading because of form submission, add onSubmit="return false;" on form elements, e.g.:

<form class="add-comment-form" id="addCommentForm3" method="post" action="" onSubmit="return false;" >

But because of this we have to follow another approach using click event:

$(document).ready(function(){
    $("#submit").click(function(e){
        var x = $(this).parent(".add-comment-form").eq(0).find("#comentonpost").eq(0).val();
        // now you have number x of submitted form and you can do the rest
    }); 
});

Combination of click event and cancelling submit event should work. But just for the record (you should already know this, but I can imagine you might have a reason for doing it) using same id on multiple html elements is not a good strategy.

1 Comment

It's not working. When i press submit it's just refreshin the page but nothing.

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.