I am trying to do a form submit with backbone.js, and when I click submit, it refreshes form. I have added my js code here. Is there any source from where i can get some detailed example with backbone js and have proper explained backbone js. I am new to backbone js and trying to learn it.
$(document).ready(function () {
Models.morderfaq = Backbone.Model.extend({
action: "ae-morder_faq-sync",
defaults: {
}
});
Collections.morderfaqs = Backbone.Collection.extend({
model: morderfaq,
el: '#save_faq_form',
action: 'ae-fetch-morder_faq',
initialize: function () {
}
});
Views.morderfaq_view = Backbone.View.extend({
el: '#save_faq_form',
events: {
"submit #save_faq_form": "syncChange"
},
initialize: function (options) {
_.bindAll(this, 'syncChange');
this.model = new morderfaq();
},
syncChange: function (event) {
event.preventDefault();
var self = this;
console.log('clicked');
self.$el.find('input,textarea,select').each(function () {
self.model.set($(this).attr('name'), $(this).val());
});
}
});
new Views.morderfaq_view();
});
Html code
<form class="post et-form" id="save_faq_form" novalidate="novalidate">
<div class="form-group clearfix">
<div class="input-group">
<label for="" class="input-label">1. send me
</label>
<textarea name="morder_faq_491" class="input-item input-full" id="morder_faq_491" value="" placeholder="Enter Text...">
</textarea>
</div>
</div>
<div class="form-group">
<button class="btn-save btn-submit" type="submit">SEND</button>
<input type="hidden" class="input-item save_faq_nonce" name="_wpnonce" value="fd75e383ec">
</div>
</form>
Related
Having an issue hiding/disabling the submit button with it also submitting the form. I have tried adding: onclick="this.value='Submitting, Please Wait.'; this.disabled='disabled';" into the input submit field which will disable the button but wont submit the form. I have tried placing this into the javascript portion also and it not working. I have tried things like this also:
$("#SignInButton").one('click', function (event) {
event.preventDefault();
$(this).prop('disabled', true);
});
I am at a loss because a lot of examples I am looking at are for html.beginform and this old form was set up with Ajax.BeginForm. Any insight on how to either just hide the button or disable the button with the code below would be much help!!
<div id="LoginModal" style="display:none;padding:1rem;max-width:580px;">
#using (Ajax.BeginForm("Login", "Accounts",
new AjaxOptions
{
HttpMethod = "POST",
OnSuccess = "OnSuccess",
OnFailure = "OnSuccess"
}))
{
<div>
Other Form Data
<div>
#Html.Hidden("ItemID", Model.ItemID)
<input type="submit" id="SignInButton" data-loading-text="Signing in" class="button success" value="Sign In" />
</div>
</div>
}
<script type="text/javascript">
var ready;
ready = function () {
$(".fancybox").fancybox({
'content': $('#LoginModal'),
'onStart': function () { $("#LoginModal").css("display", "block"); },
'onClosed': function () { $("#LoginModal").css("display", "none"); }
});
};
$(document).ready(ready);
$(document).on('page:load', ready);
</script>
EDIT!!!!!
<div id="LoginModal" style="display:none;padding:1rem;max-width:580px;">
#using (Ajax.BeginForm("Login", "Accounts", new AjaxOptions { HttpMethod = "POST", OnSuccess = "OnSuccess", OnFailure = "OnSuccess" }))
{
<h1>Sign In</h1>
var displayLocalLogin = "";
#Html.AntiForgeryToken()
#Html.ValidationSummary(false, "", new { #class = "text-error" })
#Html.Sitecore().FormHandler()
<div class="">
<div class="row">
<div class="internal">
<div class="medium-12 columns">
</div>
<div class="medium-12 border-top columns">
<div class="form-group">
<label for="UserName">UserName <span class="required">*</span></label>
#Html.TextBoxFor(m => m.UserName)
#Html.ValidationMessageFor(m => m.UserName)
</div>
</div>
<div class="medium-12 columns">
<div class="form-group">
<label for="Password">Password <span class="required">*</span></label>
#Html.PasswordFor(m => m.Password)
#Html.ValidationMessageFor(m => m.Password)
</div>
</div>
<div class="medium-12 columns" style="padding-bottom: 10px;">
<div class="form-group">
</div>
</div>
<div class="medium-5 columns left">
<div class="form-group">
<div>
<div>
#Html.Hidden("ItemID", Model.ItemID)
<input type="submit" id="SignInButton" data-loading-text="Signing in" class="button success" value="Sign In">
</div>
</div>
</div>
</div>
</div>
#if (string.Equals(System.Configuration.ConfigurationManager.AppSettings["EnableSalesForceLogin"], "true", StringComparison.InvariantCultureIgnoreCase))
{
displayLocalLogin = "displaynone";
#Html.Partial("/salesforceloginpartial.cshtml")
}
</div>
</div>
}
<script type="text/javascript">
$("#SignInButton").one('click', function (event) {
$(this).prop('disabled', 'disabled');
});
//function OnSuccess(data) {
// alert(data);
// $('#LoginModal').parent.html(data).css("display", "block");
// $("#LoginModal").css("display", "block");
//}
var ready;
ready = function () {
$(".fancybox").fancybox({
'content': $('#LoginModal'),
'onStart': function () { $("#LoginModal").css("display", "block"); },
'onClosed': function () { $("#LoginModal").css("display", "none"); }
});
};
$(document).ready(ready);
$(document).on('page:load', ready);
</script>
You can disable the button in the next event loop excecution by using setTimeout(func, 0):
$("#SignInButton").one('click', function (event) {
setTimeout(function() {
event.preventDefault();
$(this).prop('disabled', true);
}, 0);
});
This will block the button right after the user click, but it will pass the first click.
I think you should set the attribute disabled to "disabled" instead
$(this).prop('disabled', 'disabled');
You can probably try to make use of ajaxStart and ajaxStop methods from jquery.
http://api.jquery.com/ajaxStart/
http://api.jquery.com/ajaxStop/
May be something like, in ajaxStart disable the button.
You need to submit the form after disabling button.
Give to your form an id:
#using (Ajax.BeginForm("Login",
"Accounts",
new AjaxOptions { HttpMethod = "POST", OnSuccess = "OnSuccess", OnFailure = "OnSuccess" },
new { id = "formId"}))
and then submit it by javascript:
$("#SignInButton").one('click', function (event) {
event.preventDefault();
$(this).prop('disabled', true); //disable button
$("#formId").submit(); //submit the form
});
I seem to be overlooking something simple here but it has me stumped.
Why does nothing happen when i hit the submit button?
<section ng-controller="SavingsController as savingsCTRL">
<form name="createSavingForm" class="form-horizontal" novalidate>
<fieldset>
<!-- Title Box Start-->
<div class="form-group new-deal-form" show-errors>
<label for="title">Title</label>
<input name="title" type="text" ng-model="savingsCTRL.title" id="title" class="form-control" placeholder="Title" required>
<div class="sub-label">Enter the Title of the Deal.</div>
<div ng-messages="savingForm.savingsCTRL.title.$error" role="alert">
<p class="help-block error-text" ng-message="required">Saving title is required.</p>
</div>
</div>
<!-- Title Box End-->
<!--Submit Button Start-->
<div class="form-group buttons-cancel-submit">
<button class="btn btn-default " ng-click="savingsCTRL.cancel()">Cancel</button>
<input type="submit" class="btn btn-success " ng-click="savingsCTRL.create(); submitForm(createSavingForm.$valid)" >
</div>
</fieldset>
</form>
</div>
</div>
</section>
for simplicity i took most of the forms out but what else is wrong?
Savings Controller Function
// Create new Saving
$scope.create = function () {
$scope.error = null;
alert("create");
// Create new Saving object
var saving = new Savings({
title: this.title,
details: this.details,
retailer: this.retailer,
price: this.price,
link: this.link,
image: $scope.user.imageURL,
urlimage: this.urlimage,
tags: this.tags
//startdate: this.startdate,
//enddate: this.enddate
});
// Redirect after save
saving.$save(function (response) {
$location.path('savings/' + response._id);
// Clear form fields
$scope.title = '';
$scope.details = '';
$scope.retailer = '';
$scope.price = '';
$scope.link = '';
$scope.image = '';
$scope.urlimage = '';
$scope.tags = '';
}, function (errorResponse) {
$scope.error = errorResponse.data.message;
});
};
Main issue is, you are mixing controller as syntax with $scope.
According to documentation, we should use this instead of $scope.
... binds methods and properties directly onto the controller using this: ng-controller = "SettingsController1 as settings"
Than, submitForm is not a predefined method, it should be defined in controller first
this.submitForm = function(isValid){
console.log('Submitting form: ' + isValid)
}
In addition to that, bind that to form with ng-submit= "savingsCTRL.submitForm(createSavingForm.$valid)"
See Plunker, with working code. (I took ng-click="savingsCTRL.create()", since we don't have all parts of your application)
Bind the form submit event to ng-submit.
Example: ng-submit="submitForm(createSavingForm.$valid)"
I have a OutputsFormView which should have a save and cancel handler for click events on the buttons. When the save button is clicked it should collect all values from the child views and send it to the controller which then persists it.
outputs.js
App.OutputsCreateRoute = Ember.Route.extend({
model: function() {
return App.Output.createRecord();
},
renderTemplate: function() {
return this.render('outputs/form', {
controller: 'outputsCreate'
});
}
});
App.OutputsCreateController = Ember.Controller.extend({
save: function(model) {
// outputs empty values for title, receiver, value
console.log(model);
}
});
App.OutputsFormView = Ember.View.extend({
tagName: 'form',
classNames: ['form', 'form-horizontal'],
save: function(e) {
this.get('controller').send('save', {
title: this.get('title'),
receiver: this.get('receiver'),
value: this.get('value')
});
},
cancel: function(e) {
console.log('canceling');
}
});
template
<script type="text/x-handlebars" data-template-name="outputs/form">
{{#view App.OutputsFormView}}
<legend class="text-right">create a new output</legend>
<fieldset>
<div class="control-group">
<label class="control-label" for="title">Title</label>
<div class="controls">
{{view Ember.TextField valueBinding="view.title" placeholder="Lovely Afternoon Pizza"}}
</div>
</div>
<div class="control-group">
<label class="control-label" for="receiver">Receiver</label>
<div class="controls">
{{view Ember.TextField valueBinding="view.receiver" placeholder="The Goverment"}}
</div>
</div>
<div class="control-group">
<label class="control-label" for="value">Receiver</label>
<div class="controls">
{{view App.ValueView valueBinding="view.value"}}
</div>
</div>
<div class="control-group pull-right">
<div class="controls">
<button type="button" {{action "save"}} class="btn">save</button>
<button type="button" {{action "cancel"}} class="btn btn-red">cancel</button>
</div>
</div>
</fieldset>
{{/view}}
</script>
For some reason I cannot get the values of the child form views and unfortunately I have no idea what I have forgotten...
Bodo
The solution is that each a valueBinding is available in the controller:
App.OutputsCreateController = Ember.Controller.extend({
save: function(model) {
var output = this.get('model');
output.set('title', this.get('title'));
output.set('receiver', this.get('receiver'));
output.set('value', this.get('value'));
output.save();
}
});
This is better than resolving the values out of the view directly. But if you want to do this you can give your view a name:
{{view viewName="blabla"}}
and then access it through the parent view with:
this.get('blabla');
However I think the value binding method should be preferred
I'm trying to create a page where I can see list of my items, and edit them when clicked (on a separate page).
But when I browse trough different items (models), and then try to edit one item, every other item that I have loaded edits too.
My view:
App.Views.Items.Types.Type = Backbone.View.extend({
template: '#template_itemtypeview',
el: '#content',
initialize: function() {
$('.manage_items_header').show();
this.render();
},
render: function() {
var self = this;
var itemtypes = new App.Collections.ItemTypes();
itemtypes.fetch({
success: function() {
var template = _.template($(self.template).html());
$(self.el).html(template({
model: self.model.toJSON(),
itemtypes: itemtypes.models
}));
}
});
return this;
},
events: {
"change": "change",
"click .save": "save",
"click .delete": "delete",
},
change: function(event) {
// Remove any existing alert message
App.Utils.hideAlert();
// Apply the change to the model
var target = event.target;
var change = {};
if (target.type == 'checkbox') {
change[target.name] = target.checked;
} else {
change[target.name] = target.value;
}
this.model.set(change);
},
save: function() {
var self = this;
this.model.save(null, {
success: function(model) {
self.render();
App.app.navigate('items/types/' + model.id, false);
App.Utils.showAlert('Success!', 'Item type saved successfully', 'alert-success');
},
error: function() {
App.Utils.showAlert('Error', 'An error occurred while trying to delete this item type', 'alert-error');
}
});
},
delete: function() {
var self = this;
this.model.destroy({
success: function() {
App.app.navigate('items/types/new', true);
alert('Item type deleted successfully');
//window.history.back();
}
});
return false;
} });
Relavent part of route:
itemTypeAdd: function(){
App.Views.HeaderView.selectMenuItem('manage_items');
new App.Views.Items.Types.Type({
model: new App.Models.ItemType()
});
},
itemTypeShow: function(id){
App.Views.HeaderView.selectMenuItem('manage_items');
var itemtype = new App.Models.ItemType({id: id});
itemtype.fetch({success: function(){
new App.Views.Items.Types.Type({
model: itemtype
});
}});
},
HTML:
<form class="form-horizontal span5">
<fieldset>
<legend>Item Type Details</legend>
<br/>
<div class="control-group">
<label for="collectionID" class="control-label">ID:</label>
<div class="controls">
<input id="collectionID" name="id" type="text" value="<%= model.id === null ? '' : model.id %>" class="span3"
disabled/>
</div>
</div>
<div class="control-group">
<label for="name" class="control-label">Name:</label>
<div class="controls">
<input type="text" id="name" name="name" value="<%= model.name %>"/>
<span class="help-inline"></span>
</div>
</div>
<div class="control-group">
<label for="name" class="control-label">Has places?:</label>
<div class="controls">
<input type="checkbox" name="has_place"<% if(model.has_place) { %> checked="checked"<% } %>>
<span class="help-inline"></span>
</div>
</div>
</fieldset>
<div class="form-actions">
Save
Delete
</div>
</form>
<div class="span2">
<legend>Item Types + New</legend>
<ul id="itemtypes_list">
<%
_.each(itemtypes,function(item,key,list){
%>
<li><%= item.attributes.name %></li>
<%
});
%>
</ul>
</div>
I am having some issues getting started with using underscore js and backbone js together. I am able to display just plain html with backbone but i am not able to get the templates to display.
Template:
<script type="text/template" id="edit-user-template">
<form class="edit-user-form">
<legend>Create User</legend>
<label>First Name</label>
<input type="text" name="firstname" />
<label>Last Name</label>
<input type="text" name="lastname" />
<label>Age</label>
<input type="text" name="age" />
<hr />
<button type="submit" class="btn">Create a User</button>
</form>
</script>
View:
var EditUser = Backbone.View.extend({
el: '.page',
template: _.template($('#edit-user-template').html),
render: function() {
this.$el.html(this.template({}));
return this;
}
});
Route:
var Router = Backbone.Router.extend({
routes:{
'':'home',
'new':'editUser'
}
});
var userList = new UserList();
var editUser = new EditUser();
var router = new Router();
router.on('route:home', function(){
userList.render();
});
router.on('route:editUser', function(){
editUser.render();
});
Backbone.history.start();
When i try to load the page in the browser i get the error:
Uncaught TypeError: Object function (e){return b.access(this,function(e){var n=this[0]||{},r=0,i=this.length;if(e===t)return 1===n.nodeType?n.innerHTML.replace(gt,""):t;if(!("string"!=typeof e||Tt.test(e)||!b.support.htmlSerialize&&mt.test(e)||!b.support.leadingWhitespace&&yt.test(e)||At[(bt.exec(e)||["",""])[1].toLowerCase()])){e=e.replace(vt,"<$1></$2>");try{for(;i>r;r++)n=this[r]||{},1===n.nodeType&&(b.cleanData(Ot(n,!1)),n.innerHTML=e);n=0}catch(o){}}n&&this.empty().append(e)},null,e,arguments.length)} has no method 'replace' underscore-min.js:1
Any idea what is causing this?
jQuery.html() is a method, so instead of this:
template: _.template($('#edit-user-template').html)
You need
template: _.template($('#edit-user-template').html())