[英]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.