gpt4 book ai didi

javascript - 主干 View 中的验证错误

转载 作者:行者123 更新时间:2023-12-03 12:31:10 24 4
gpt4 key购买 nike

好吧,我正在乱搞代码来帮助我更好地理解 javascript,并且我一直在玩主干。我可能错过了它,但我在这里的验证工作不正常。我要么收到“您必须填写两个字段,要么即使字段为空它也会提交。

addModel 的功能是向我的父 View 添加一行并将其全部保存在一个函数中,这导致了我的问题

Form = Backbone.View.extend({ //form view
el: '.item-form',
initialize: function(){
},
events: {
'click #additem': 'addModel' // clicking on the add item button launches the addmodel function
},
addModel: function(){ // when the addmodel function fires it takes
var item = new Item({
"itemName": this.$("#item").val(),//value of form input placed into row template cell
"price": this.$("#price").val()});

// simple validation before adding to collection
if(!_.isEmpty("#item") && !_.isEmpty("#price")){
var items = new Items();
items.add(item);
$("#message").html("Please wait; the task is being added.");
item.save(null, {success:
//use the mongo id as the Item models id
function (item, response,options) {
item.id= item.attributes._id.$id;
item.attributes.id = item.attributes._id.$id;
new ItemsView({collection: items});
$("#message").html("");
}
});
this.$("#item").val('');//all this does is empty the field
this.$("#price").val('');//all this does is empty the field
} else {
alert('Please fill in both fields');
}
}
});

这是引用的html

<body>
<table class="itemTable">
<thead>
<tr>
<th>Item</th>
<th>Price</th>
<th></th>
</tr>
</thead>
<tbody class="tableBody">
<script type="text/template" id="table-row">
<td><%= itemName %></td> <td><%= price %></td> <td> <button class="complete">Complete</button> <button class="remove">Remove</button></td>
</script>

</tbody>
</table>

<form class="item-form">
<input type="text" name="item" id="item" placeholder="Item"/> <!-- goes to itemName in the template for the body -->
<input type="text" name="price" id="price" placeholder="Price" /><!--goes to price in the template for the body -->
<button type="button" id="additem">Add</button>
</form>
<div id="message"></div

最佳答案

验证应该比较输入的值,而不仅仅是 ID。

if(!_.isEmpty(this.$("#item").val()) && !_.isEmpty(this.$("#price").val())){

关于javascript - 主干 View 中的验证错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23924136/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com