简体   繁体   English

如何从jQuery中获取html表单的输入值?

[英]How to get input value from html form in jQuery?


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. 我想问一下,当我在一个页面上有许多同名的表单时,我是如何从HTML表单中获取Javascript中的SUBMIT输入值。

It's looking like this: 它看起来像这样:

First printed HTML form: 第一个打印的HTML表单:

<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. 我必须考虑comentonpost的价值,因为我需要在我的Javascript中,所以当我发表评论时,它会出现在提交addCommentContainer之前。
And there is the whole Javascript: 并且有整个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? 我怎么能让它只获得comentonpost形式的comentonpost值而不是第一次打印,这个脚本有什么更好的方法可以工作吗?

Thanks in advance! 提前致谢!

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. 这有效,但您应该记住,您的文档无效,因为您的元素具有相同的ID。 IDs must be unique within a document for it to be valid. ID必须在文档中是唯一的才能有效。

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. 当你使用jquery选择一个ID时,它将返回0或一个匹配的元素,它将匹配它找到的第一个元素。 from http://api.jquery.com/id-selector/ 来自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. 使用id选择器作为参数调用jQuery()(或$())将返回包含零个或一个DOM元素集合的jQuery对象。

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. 每当你使用$(“#submit”)它通过DOM解析并找到<input type="submit" id="submit" value="Submit" />的第一个实例并返回该元素。 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. 这将从表单元素开始,并仅搜索表单中包含ID为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. 你有一个通用的表单模板,当你有这样的多个表单时,你真的不应该给它们所有相同的ID。 instead, start binding event handlers to classes, and use the dom to store whether a form is 'working' or not as well 相反,开始将事件处理程序绑定到类,并使用dom来存储表单是否“正常”

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

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...

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;" 要防止因表单提交而导致页面重新加载,请添加onSubmit =“return false;” on form elements, eg: 在表单元素上,例如:

<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. 但只是为了记录(你应该已经知道这一点,但我可以想象你可能有理由这样做)在多个html元素上使用相同的id并不是一个好策略。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM