[英]get value from html input
我正在使用js从表单中获取数据。 我只想将<input type="text" name="postid">
的postid
放入postid
变量中。
这是我的代码。 我在需要值的地方添加了评论。 ( var postid= ? //Here
)。
$('#comment_form_sub').on('submit', function(event){ event.preventDefault(); var form_data = $(this).serialize(); //var postid= ? //Here console.log(form_data); });
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <form class="comment-form inline-items" method="POST" id="comment_form_sub"> <input type="text" name="postid" id="postid" value="23"> <input type="text" name="comment_content" id="comment_content" class="form-control input-sm" placeholder="Press enter to post comment"> <input type="submit" style="display: none;" /> </form>
如何从postid
输入中获取值到变量中?
可能有很多方法。
您可以通过以下方式通过选择元素的名称或ID直接选择它。
var postid = $("input[name=postid]").val() Or
var postid = $("input[id=postid]").val() Or
var postid = $('#postid').val();
如果要通过此关键字获取,请使用以下任何一种方法。
var postid = $(this).children("#postid").val() Or
var postid = $(this).children("input[name=postid]").val() Or
var postid = $(this).children("input[id=postid]").val() Or
var postid = $(this).find("#postid").val() Or
var postid = $(this).find("input[name=postid]").val() Or
var postid = $(this).find("input[id=postid]").val()
如果我正确理解了这个问题,我认为您只想使用$('#postid').val()
来获取postid输入的值。 因此,整个行应如下所示: var postid = $('#postid').val();
您不需要jQuery。
这是获取该值的两种方法,一种是使用jQuery(可接受的答案),另一种是使用标准方法document.getElementById
和Element.addEventListener
:
// The jQuery way: $('#comment_form_sub').on('submit', function(event) { event.preventDefault(); const postId = $('#postid').val(); console.log(postId); }); // You don't need jQuery: document.getElementById('comment_form_sub').addEventListener('submit', (event) => { event.preventDefault(); const postId = document.getElementById('postid').value; console.log(postId); });
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <form class="comment-form inline-items" method="POST" id="comment_form_sub"> <input type="text" name="postid" id="postid" value="23"> <input type="text" name="comment_content" id="comment_content" class="form-control input-sm" placeholder="Press enter to post comment"> <input type="submit" style="display: none;" /> </form>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.