我想在输入文本中插入值
时获取输入文本值当我点击<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>
按钮时,jquery会附加到booklist ul tag
html代码
val()
我决定使用alert()
方法并使用(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);
}
});
})();
js代码
val()
但是jquery无法获得文本值
value=""
方法仅在标记内联中获取<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="wrap_content">
<ImageView
android:layout_width="match_parent"
android:layout_height="wrap_content"></ImageView>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginLeft="10dp"
android:orientation="vertical">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
</LinearLayout>
</RelativeLayout>
..但它是无用的值
我想得到客户的宝贵文字,请有人帮助我
答案 0 :(得分:1)
问题是您在页面加载时检查输入的值,但在用户单击按钮时则不会。
因此,解决方案是在用户点击按钮时进行检查。
(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>
答案 1 :(得分:1)
在点击事件中获取输入值,如下所示:
(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);
}
});
})();
答案 2 :(得分:1)
这是因为您在触发事件之前定义了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);
}
});
})();