首页 > 解决方案 > 从 html 输入中获取值

问题描述

我正在使用 js 从表单中获取数据。我只想从变量中获取 <input type="text" name="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输入中获取值到我的变量中?

标签: javascriptjqueryhtml

解决方案


可能有很多方法。

您可以通过以下方式通过直接按名称或 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()

推荐阅读