我想在输入文本中插入值时获取输入文本值
当我点击 ADD IN BOOK LIST
按钮时,jquery 将附加在 booklist ul 标签中
html代码
<form action="" method="POST">
{% csrf_token %}
<p>POST TITLE</p>
<input type="text" name="title" placeholder="Insert title" required>
<p>INSERT BOOK NAME</p>
//user will input value this text box
<input type="text" name="bookname" placeholder="book name">
<input type='button' name="addlist" value="ADD IN BOOK LIST">
<ul class="booklist">
</ul>
<input type="submit" id='button'>//create post button
</form>
我决定使用 val()
方法并使用 alert()
进行测试
js代码
(function(){
//get ADD IN BOOK LIST button
//get bookname tagname
var addlist_button = $('input[name=addlist]');
var book_name = $('input[name=bookname]').val();
addlist_button.on('click', function(event){
if((book_name == "")||(book_name == null)){
alert('fail');
}
else{
alert(book_name);
}
});
})();
但是jquery无法获取文本值
val()
方法只是在标签内联中获取value=""
..但它是无用的值
我想得到客户的宝贵文本,请有人帮助我
最佳答案
问题是您在页面加载时检查输入的值,而不是在用户单击按钮时检查。
所以解决方案是在用户点击按钮时检查它。
(function(){
//get ADD IN BOOK LIST button
//get bookname tagname
var addlist_button = $('input[name=addlist]');
addlist_button.on('click', function(event){
var book_name = $('input[name=bookname]').val();
if((book_name == "")||(book_name == null)){
alert('fail');
}
else{
alert(book_name);
}
});
})();
<form action="" method="POST">
<script src="https://code.jquery.com/jquery-3.0.0.js"></script>
<p>POST TITLE</p>
<input type="text" name="title" placeholder="Insert title" required>
<p>INSERT BOOK NAME</p>
//user will input value this text box
<input type="text" name="bookname" placeholder="book name">
<input type='button' name="addlist" value="ADD IN BOOK LIST">
<ul class="booklist">
</ul>
<input type="submit" id='button'>//create post button
</form>
关于javascript - 如何在jquery中获取输入文本值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38888958/