[英]how to get input text value in jquery
我想在输入文本中插入值时获取输入文本值
当我点击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>
在click事件中获取输入值如下:
(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);
}
});
})();
这是因为您在事件被触发之前已经定义了book_name
,并且在那时它等于“”。
(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);
}
});
})();
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.