Simple Form validation failing Backbone
- by Corey Buchillon
Im not exactly adept at coding so Im probably missing something, but my view here is failing to refuse submission when one or both of the fields are empty. I have a feeling something isnt connected right to my template for the row and the view of the form
Form = Backbone.View.extend({ //form vie
el: '.item-form',
initialize: function(){
},
events: {
'click #additem': 'addModel'
},
addModel: function(itemName, price){
// simple validation before adding to collection
if (itemName !="" && price !="" ){
var item = new Item({
itemName: this.$("#item").val(),
price: this.$("#price").val()});
items.add(item);
$("#message").html("Please wait; the task is being added.");
item.save(null, {success:
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('');
this.$("#price").val('');
} else {
alert('Please fill in both fields');
}
}
});
and HTML
<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>