Sunday, 2 June 2013

How to get input value from html form in Javascript?

How to get input value from html form in Javascript?


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!

No comments:

Post a Comment