好的,我正在搞乱代码,以帮助我更好地理解javascript,而且我一直在玩骨干。我可能会错过它,但我的验证在这里工作正常。我要么得到一个"你必须填写这两个字段,或者即使字段为空,它也只是提交。
addModel的功能是向我的父视图添加一行并将其全部保存在一个导致我出现问题的函数中
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
答案 0 :(得分:1)
验证应该比较输入值而不仅仅是id。
if(!_.isEmpty(this.$("#item").val()) && !_.isEmpty(this.$("#price").val())){