On form submit determine which submit button action is clicked - backbone.js

How can I get the 'Submit button action' when a form is submitted? For example;
<form data-action="foo">
<button type="submit" name="action" value="update">Update</button>
<button type="submit" name="action" value="cancel">Cancel</button>
</form>
In my Backbone View I am trying to figure which button was clicked:
, events: {
'submit form[data-action="foo"]': 'editSubscription'
}
, editSubscription: function(e)
{
e.preventDefault();
// How can I determine the submit action is 'update' or 'cancel'
// Save the model, ie, implicitly do a POST with action UPDATE or CANCEL
this.model.save({action: 'update' /*or 'cancel'*/}, ...);
}

By getting value of submit button.
$(document).on("click", ":submit", function(e){
alert($(this).val());
});

You can get the button value on click event, use prevent default to stop form submit
var el = document.querySelectorAll('button');
el.forEach(item => {
item.addEventListener('click', function(e){
e.preventDefault();
console.log(e.target.value);
})
})
<form data-action="foo">
<button type="submit" name="action" value="update">Update</button>
<button type="submit" name="action" value="cancel">Cancel</button>
</form>

Here is how you can get notification. Just add id attribute to element and get it from currentTarget.
var eventType = '';
$("button").on("click",function(e){
alert($(e.currentTarget).attr('id')+' clicked');
eventType = $(e.currentTarget).attr('id');
//this.model.save({action: eventType}, ...);
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form data-action="foo">
<button type="submit" id="update" name="action" value="update">Update</button>
<button type="submit" id="cancel" name="action" value="cancel">Cancel</button>
</form>

You can achieve that in Vanilla JS in the following way:
document.querySelectorAll('button[type=submit]').forEach(function(btn){
btn.addEventListener('click', function(e){
console.log('You have clicked the button:', this.value);
e.preventDefault();
})
});
<form data-action="foo">
<button type="submit" name="action" value="update">Update</button>
<button type="submit" name="action" value="cancel">Cancel</button>
</form>
OR: If you prefer jQuery:
$('button[type=submit]').on('click', function(e){
console.log('You have clicked the button:', this.value);
e.preventDefault();
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form data-action="foo">
<button type="submit" id="update" name="action" value="update">Update</button>
<button type="submit" id="cancel" name="action" value="cancel">Cancel</button>
</form>

The simplest way is by using event.target you can get the value of button and put the condition on that
// you can determine by e.target.value that action is 'update' or 'cancel'
if(e.target.value=='update'){
// Save the model, ie, implicitly do a POST with action UPDATE
this.model.save({action: 'update'}, ...);
}
if(e.target.value=='cancel'){
// Save the model, ie, implicitly do a POST with action CANCEL
this.model.save({action: 'cancel'}, ...);
}
Your updated code:
, events: {
'submit form[data-action="foo"]': 'editSubscription'
}
, editSubscription: function(e)
{
e.preventDefault();
// you can determine by e.target.value that action is 'update' or 'cancel'
if(e.target.value=='update'){
// Save the model, ie, implicitly do a POST with action UPDATE
this.model.save({action: 'update'}, ...);
}
if(e.target.value=='cancel'){
// Save the model, ie, implicitly do a POST with action CANCEL
this.model.save({action: 'cancel'}, ...);
}
}

Related

AngularJS disable double click

I have a problem with a button which contacts server on click. If you do a double click (or any number of clicks for that matter) you will call the server that number of times.
<div class="modal-footer">
<button type="button" class="btn btn-default" data-dismiss="modal">{{ 'ADMIN.CONTENT.DELIVERIES.BODY.CLOSE' | translate }}</button>
<a class="btn btn-danger" ng-click="vm.markDelivered()" ng-dblclick="return" ng-disabled="flag">{{ 'MANAGER.CONTENT.DELIVERIES.BODY.DELETE_PANEL.CONFIRM' | translate }}</a>
</div>
I have tried with ng-disabled but for some reason it doesn't work, as it is saying that that element is not allowed there. I tried changing a to button, but that seems the same. ng-dblclick="return" does nothing also.
Even I had the same issue,And solved using this approach.
<div class="col-sm-4 form-group pull-right">
<input type="submit" name="Submit" class="btn btn-primary"
value="Submit" data-ng-disabled="myForm.$invalid"
ng-click="myForm.$invalid=true;vm.markDelivered()" />
</div>
So on first click myForm.$invalid=true will be set and button will be disabled. SO you will not have multiple calls to your server side code.
So with Bootstrap buttons you won't be able to use ng-disabled. You would have to do it this way:
<div class="btn btn-default" ng-class="{'disabled': idDisabled}" ng-click="doSomething()">I'm a button!</div>
where you are setting the class disabled on the button. But this does not disable the action itself. So when the button is pressed you would need to check that isDisabled variable and if it is true just return and don't do the intended action.
So for example:
doSomething() {
if (isDisabled) {
return
} else {
// do your server call
// when call is finished set isDisabled = false
}
}
I see a couple of issues here.
First, change the anchor tag to a button.
Second, you seem to be using 'controller as' syntax. So, you are probably setting your flag in the vm. But, in your html, you are looking for the flag in the $scope. Change ng-disabled="flag" to ng-disabled="vm.flag"
Your final button line would look like this:
<button class="btn btn-danger" ng-click="vm.markDelivered()" ng-dblclick="return" ng-disabled="vm.flag">{{ 'MANAGER.CONTENT.DELIVERIES.BODY.DELETE_PANEL.CONFIRM' | translate }}</button>
Adding a working plunker here demonstrating ng-disabled
What about using a simple behaviour directive?
function oneTimeCallDirective($timeout) {
var httpCallMock = (cb = () => 'ok') => $timeout(cb, 5000);
return function oneTimeCallPostLink(iScope, iElement) {
let busy = false;
return iElement
.on('click dblclick', function(event) {
if(busy) {
return event.preventDefault();
}
busy = true;
console.info('Well, Calling.');
return httpCallMock()
.then(() => {
console.log('You Can Start Calling Again');
})
.finally(() => {
busy = false;
})
;
})
;
};
}
angular
.module('test', [])
.directive('oneTimeCall', oneTimeCallDirective)
;
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<section ng-app="test">
<button one-time-call>Click Here</button>
</section>

AngularJS form validations with submit and reset buttons

I have a simple form where I have applied AngularJS validation on a input box containing number value. On submit, it works fine but when I click on Reset button, it gives the input box validation error message. Looks like it is calling ng-submit after ng-click of Reset button. I have tried resetting the value of input field in ng-click, removed type='Reset' and also used $setPristine() on the form. But nothing helps. Below is the code.
<form name="myForm" novalidate ng-submit="submitFilter()">
Enter Age:
<div>
<input name="age" ng-class="{errorinput: submitted && myForm.age.$invalid }" class="form-control" ng-pattern="/^[0-9]+$/" placeholder="Age" type="text" ng-model="age" required>
</div>
<span class="error" ng-style="{color:'red'}" ng-show="submitted && myForm.age.$invalid">Please enter a valid Age</span>
<button type="submit">
Submit
</button>
<button ng-click="reset(myForm)">
Reset
</button>
</form>
Controller:
var original = $scope.age;
$scope.submitFilter = function () {
if ($scope.filterForm.$valid) {
} else {
$scope.submitted = true;
}
};
$scope.reset = function (myForm) {
$scope.age = angular.copy(original);
$scope.myForm.$setPristine();
};
Kindly help in getting rid of this error.
Thanks in Advance.
Setting the reset button's type as 'button' should work. Following code works perfectly on my machine.
// Code goes here
app.controller('mainController', function($scope) {
$scope.age = 123;
var original = $scope.age;
$scope.submitFilter = function () {
$scope.submitted = true;
};
$scope.reset = function (myForm) {
$scope.age = angular.copy(original);
$scope.myForm.$setPristine();
};
});
<form name="myForm" novalidate ng-submit="submitFilter()">
Enter Age:
<div>
<input name="age" ng-class="{errorinput: submitted && myForm.age.$invalid }" class="form-control" ng-pattern="/^[0-9]+$/" placeholder="Age" type="text" ng-model="age" required>
</div>
<span class="error" ng-style="{color:'red'}" ng-show="submitted && myForm.age.$invalid">Please enter a valid Age</span>
<button type="submit">
Submit
</button>
<button type="button" ng-click="reset(myForm)">
Reset
</button>
</form>

Submit event doesn't work when specifying with class

I have a view which has the "el" set to the form id. I have two buttons in the form, one for submit and one for clear. I cannot figure out how to set an event for each button. For example when I set the events as follows they will not work:
Form Template:
<form id="addTask" action="">
<input type="text" placeholder="Your new task"/>
<input type="submit" id="submit" value="Add Task"/>
<input type="submit" id="clear" value="Clear" />
</form>
Form View:
App.Views.AddTask = Backbone.View.extend({
el: '#addTask',
events: {
'submit .edit': 'submit',
'submit .clear': 'clear'
},
submit: function(e) {
e.preventDefault();
var newTaskTitle = $(e.currentTarget).find('input[type=text]').val();
var task = new App.Models.Task({ title: newTaskTitle });
this.collection.add(task);
},
clear: function() {
// do some stuff
}
});
When I use the below syntax for the "click" event in another view it works.
events: {
'click .delete': 'destroy',
'click .edit': 'edit'
},
I have Googled and cannot find an answer. Funny thing is I found a tutorial where this syntax is used with a submit event:
http://dailyjs.com/2013/01/31/backbone-tutorial-10/
Any assistance is appreciated. Thanks.
The submit event is triggered on the form itself, in your case your "el", not the clicked button.
events: {
'submit': 'onSubmit'
}
Would work, but you wouldn't be able to know which button has been clicked.
If you have to submit button, I guess the correct way to do it would be to have two forms.
Let me know if that helps!
Edit:
If you don't want to change your form:
Form Template:
<form id="addTask" action="">
<input type="text" placeholder="Your new task"/>
<input type="submit" id="submit" value="Add Task"/>
<input type="submit" id="clear" value="Clear" />
</form>
Form View:
App.Views.AddTask = Backbone.View.extend({
el: '#addTask',
events: {
'submit': 'submit',
'click #clear': 'clear'
},
submit: function(e) {
e.preventDefault();
var newTaskTitle = $(e.currentTarget).find('input[type=text]').val();
var task = new App.Models.Task({ title: newTaskTitle });
this.collection.add(task);
},
clear: function() {
// do some stuff
}
});

How To save users feed data in database in my custom form in WordPress?

I have created a custom form in my project and also create mail functionality for it. Now i want to save all the data post by users in database how do i achieve it?
Here is my Form:
<form id="formMy">
<input name="txtFirstName" type="text" required placeholder="Name" id="txtFirstName">
<input name="PopupContact_email" type="email" required placeholder="E-Mail Address" id="requestemail">
<input name="txtOrganisationName" type="text" required placeholder="Company/ Institute Name" id="requestcompany">
<input type="hidden" name="hiddenform">
<button class="btn btn-primary btn-lg bbtn" data-toggle="modal" data-target="#myModal" style="display:none;">
Launch demo modal
</button>
<button type="button" class="btn btn-inverse" style="vertical-align:top;" name="submit" onClick="ajaxFormSubmit2();">Request a Demo</button>
</form>
And this is my ajax code:
<script>
function ajaxFormSubmit2(){
var txtFirstName = jQuery('#txtFirstName').val();
var requestemail = jQuery('#requestemail').val();
var requestcompany = jQuery('#requestcompany').val();
var atpos=requestemail.indexOf("#");
var dotpos=requestemail.lastIndexOf(".");
if(txtFirstName=="" || requestemail=="" || requestcompany==""){
jQuery('.alertred').show();
jQuery(".alertred").delay(10000).hide(0);
jQuery('.alertred').html('<strong>Error!</strong> Please Fill out all the fields.');
return false;
}
else if (atpos<1 || dotpos<atpos+2 || dotpos+2>=requestemail.length)
{
jQuery('.alertred').show();
return false;
}
else
{
jQuery.post("<?php echo get_bloginfo('template_directory').'/mail2.php'; ?>",{txtFirstName:txtFirstName,requestemail:requestemail,requestcompany:requestcompany},function(r){
if(r=="success"){
jQuery('.success').show();
}
});
}
}
</script>
You can get all the form data using formId_specifier.serialize() method. And you get this in your php file like this one example for you.
JS Code::
$(document).on('submit', 'form#form_id',function(){
$.post(
MyAjax.ajax_url,{
action: AJAX_FILE_URL,
data: me.serialize()
}, function(response){
// Handle after getting response
}
);
});
In php code you can get form date using this code:
parsestr($_POST['data'], $form_data); // now all form data is assign to $form_data

Why click event in backbone not working?

//I am using template in view
App.Backbone.UserView = Backbone.View.extend({
tagName: 'li',
className: 'pp-entry group',
template :_.template('<img src="i/pp-pic-8.png" class="pp-pic" alt="" />),
templatedetails:_.template('`<div style="display:none"><div id="pp-details-<%=username%>" class="pp-details"><div class="cta clear"><input type="button" name="" value="Add to my Wallet" class="mar-right-10 addtowallet" /><input type="button" class="mar-right-10 addtogib" name="" value="Add to gib as link" /><input type="button" name="" value="Close" onclick="$.fancybox.close()" /></div></div><.div>'`)
//Here is the click event defined
events:{
"click .addtowallet":"addlinktowallet",
"click .addtogib":"addasgiblink"
},
//Render contents
render: function() {
$(this.el).html(this.template(this.model.toJSON()));
$(this.el).attr('id', 'pp-'+this.model.get('username')); //This is used to set the id for the "li" tag
$('#pp-'+this.model.get('username')).append(this.templatedetails(this.model.toJSON())); //appending to the template
},
//But when i am defining the function the click event does not get triggered
addasgiblink: function(){
alert("gib button clicked");
},
addlinktowallet: function(){
alert("wallet button clicked");
}
});
The question is when i click on the pic as rendered from template a fancybox popup opens where templatedetails is rendered but when i click on the buttons in the popup it does not get triggered. Why the click function is not working?
The HTML that is generated after rendering is
<li id="pp-bikram" class="pp-entry group">
<img class="pp-pic" alt="" src="i/pp-pic-8.png">
<div style="display:none">
<div id="pp-details-bikram" class="pp-details">
<div class="cta clear">
<input class="mar-right-10 addtowallet" type="button" value="Add to my Wallet" name="">
<input class="mar-right-10 addtogib" type="button" value="Add to gib as link" name="">
<input type="button" onclick="$.fancybox.close()" value="Close" name="">
</div>
</div>
</div>
</li>
Till this point everything is working fine but i am not getting why the click event is not not working. Please suggest me some solution.
This cannot work because fancybox is not opening your content directly but its "clonning" it into its own container $('#fancybox-content').
Nice solution i think is possible by rebinding this container as Backbone.View.$el so you'll have Backbone.events{} working uppon that:
window.FancyboxView = Backbone.View.extend({
events: {
click: 'handleClick'
},
initialize:function () {
this.$trigger = this.$el.find('a.trigger');
this.$trigger.fancybox({
onComplete:$.proxy(function () {
this.setElement($('#fancybox-content')[0]);
}, this)
});
},
handleClick:function (e) {
e.preventDefault();
console.log('woala!')
}
});
In your code while executing this line
$('#pp-'+this.model.get('username'))
that element wont be available in the dom. So what you have to do is
$(this.el).append(this.templatedetails({// Your json}))
As per my observation both this.el and $('#pp-'+this.model.get('username')) are the same the li tag. So refer it as $(this.el). Please let me know if it works
Please update the code as below.
events:{
"click .addtowallet":"addlinktowallet",
"click .addtogib":"addasgiblink"
"click .fancybox":"fancyBoxClose"
},
fancyBoxClose : function(){
$.fancybox.close()
}
templatedetails:_.template('`<div style="display:none"><div id="pp-details-<%=username%>" class="pp-details"><div class="cta clear"><input type="button" name="" value="Add to my Wallet" class="mar-right-10 addtowallet" /><input type="button" class="mar-right-10 addtogib" name="" value="Add to gib as link" /><input type="button" name="" value="Close" class="fancybox" /></div></div><.div>'`)

Resources