如何解决console.log 在我的输入字段中给出 undefined
脚本:
$(document).ready(function (){
$(document).on('click','.add_category',function(e){
e.preventDefault();
var data = {
'category_name': $('.category_name').val(),'category_description': $('.category_description').val(),}
console.log(data);
});
});
形式:
<h4 class="text-center font-weight-bold">Add New Category</h4>
<div class="form-group">
<input type="text" class="form-control form-group w-100" placeholder="Category Name" class="category_name">
</div>
<div class="form-group">
<textarea class="form-control w-100" placeholder="Category Description" class="category_description" cols="50" rows="10"></textarea>
</div>
需要建议,即使输入类型和脚本的 var 数据中的变量相同,我添加内容的输入字段事件也会返回 undefined
我也尝试将 class="category_name" 更改为 name="category_name"
我错过了什么?
解决方法
您的 HTML 标签包含两个 class
属性:
<input type="text" class="form-control form-group w-100" placeholder="Category Name" class="category_name">
^^^ here ^^^ and here
浏览器忽略了第二个,所以你的 jQuery 选择器返回空集。
您应该将类属性组合成一个字符串:
<input type="text" class="form-control form-group w-100 category_name" placeholder="Category Name">
,
不能重复声明类。
你在哪里<input type="text" class="form-control form-group w-100" placeholder="Category Name" class="category_name">
相反,您需要一起声明所有类,如下所示:
<input type="text" class="category_name form-control form-group w-100" placeholder="Category Name" >
document.getElementById('submit').onclick=function(e){
e.preventDefault();
var data = {
'category_name': document.getElementsByClassName('category_name')[0].value,'category_description': document.getElementsByClassName('category_description')[0].value,}
console.log(data);
};
<h4 class="text-center font-weight-bold">Add New Category</h4>
<div class="form-group">
<input type="text" class="form-control form-group w-100 category_name" placeholder="Category Name" value="">
</div>
<div class="form-group">
<textarea class="form-control w-100 category_description" placeholder="Category Description" cols="50" rows="10" value=""></textarea>
</div>
<button id="submit"> Save</button>
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。