Merge two forms with two radio button and one form - javascript

So I have this two forms. Each has its own action, separate fields and values, radio button and button. What I want to do is that I want to have two radio buttons and one button. What is the best solution.
<div class="span6">
<h2 class="headback" >انتخاب دروازه پرداخت</h2>
<div class="text-box" style="padding-bottom: 0px">
<form class="form-inline" method="post" id="PaymentForm" action="https://google.com" style="direction: rtl">
<input type="hidden" name="amount" value="{{payment.Amount}}"/>
<input type='hidden' name='paymentId' value='{{payment.InvoiceNumber}}' />
<input type='hidden' name='revertURL' value='http://test2.happycard.ir/payment/verify' />
<input type='hidden' name='customerId' value='{{payment.Id}}' />
<label class="radio">
<img src="/media/images/images/bank.jpg"/><br/>
<input type="radio" name="PaymentProvider" id="PaymentProvider" value="4" checked>
</label>
<ul style="text-align: right">
<li>
<input type="button" value="Proceed" ng-click="SetPrePayment();" class="btn btn-primary">
</li>
</ul>
</form >
<form class="form-inline" method="post" id="PaymentForm2" action="www.wikipedia.com" style="direction: rtl">
<input type="hidden" name="pin" value='5I8bpgGr034AmB38MPQ7'/>
<input type="hidden" name="Id" value="{{payment.Id}}"/>
<input type="hidden" name="OrderId" value="{{payment.OrderId}}"/>
<input type="hidden" name="amount" value="{{payment.Amount}}"/>
<input type='hidden' name='paymentId' value='{{payment.InvoiceNumber}}' />
<?php if(custom_config::$IPGtest==1){ ?>
<input type='hidden' name='revertURL' value="<?php echo custom_config::$Test2ParsianRevertUrlHappyBarg; ?>" />
<?php } elseif(custom_config::$IPGtest==2){ ?>
<input type='hidden' name='revertURL' value="<?php echo custom_config::$ParsianRevertUrlHappyBarg; ?>" />
<?php } ?>
<label class="radio">
<img src="/media/images/images/bank.jpg"/><br/>
<input type="radio" value="parsian" name="bankname" checked>
</label>
<ul style="text-align: right">
<li>
<input type="button" ng-click="SetPrePayment2();" value="Proceed" class="btn btn-primary">
</li>
</ul>
</form >
</div>
</div>
Spoiler alert, AngularJS is used in button's actions. I uploaded a photo to show you the output of my current code.
What I want to be like is:
This is the code for my SetPrePayment() function.
$scope.SetPrePayment=function(){
$http.post('/payment/happy_payment_register/',{ 'Amount':$scope.totalPrice,'Item':$scope.item.Id, 'Description':$scope.item.Title, 'Count':$scope.defaultQuantity })
.success(function(data, status, headers, config) {
if(data!='Fail')
{
$timeout(function() {
$scope.payment=data;
timer= $timeout(function(){
document.getElementById("PaymentForm").submit();
},10)
}, 0);
}
})
.error(function(data, status, headers, config) {
console.log(data)
});
};
and SetPrePayment2() is :
$scope.SetPrePayment=function(){
$http.post('/payment/happy_payment_register/',{ 'Amount':$scope.totalPrice,'Item':$scope.item.Id, 'Description':$scope.item.Title, 'OrderId':$scope.item.Id, 'Count':$scope.defaultQuantity })
.success(function(data, status, headers, config) {
if(data!='Fail')
{
$timeout(function() {
$scope.payment=data;
timer= $timeout(function(){
document.getElementById("PaymentForm2").submit();
},10)
}, 0);
}
})
.error(function(data, status, headers, config) {
console.log(data)
});
};

You can use jquery for solve this problem.
move your button, out of two forms and set an ID for that.
<button id="myButton">Submit</button>
now you can check radio buttons in jquery to submit own form.
jQuery sample code:
$( document ).ready( function() {
$( '#myButton' ).on( 'click', function() {
if ( $( '#radio_1' ).is(':checked') ) {
$( '#form_1' ).submit();
setPrePayment();
} else {
$( '#form_2' ).submit();
setPrePayment2();
}
});
});

I think there's no jQuery needed for this. You can use ng-if that shows the form based on the user selection expression.
If you need to load the template conditionally you could also use ng-include but it should be OK with ngIf.
I've added two controllers one for each form that's only needed if you have to do many things in the form or you want to have them separate.
But the same approach with ng-if will work with one form controller.
Please have a look at the demo below or in this jsfiddle.
angular.module('demoApp', [])
.controller('FormOneController', FormOneController)
.controller('FormTwoController', FormTwoController)
.controller('MainController', MainController);
function FormOneController($window) {
this.submit = function() {
$window.alert('hello from form 1');
}
}
function FormTwoController($window) {
this.submit = function() {
$window.alert('hello from form 2');
}
}
function MainController() {
var vm = this;
vm.hideForms = hideForms;
vm.forms = getFormObject();
vm.isFormActive = isFormActive;
vm.selectForm = selectForm;
vm.showForm = showForm;
activate();
function activate() {
vm.selectedForm = vm.forms[0];
}
function getFormObject() {
return [{
id: 1,
name: 'form1',
label: 'show form 1',
visible: false
}, {
id: 2,
name: 'form2',
label: 'show form 2',
visible: false
}];
}
function hideForms() {
angular.forEach(vm.forms, function(form) {
form.visible = false;
});
//console.log(vm.forms);
}
function isFormActive(id) {
return vm.selectedForm.id === id && vm.selectedForm.visible
}
function selectForm(form) {
hideForms();
vm.selectedForm = form;
}
function showForm() {
vm.selectedForm.visible = true;
//console.log(vm.selectedForm);
}
}
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="demoApp" ng-controller="MainController as mainCtrl">
<label ng-repeat="form in mainCtrl.forms">{{form.name}}
<input type="radio" name="formSelector" value="form" ng-click="mainCtrl.selectForm(form)" ng-checked="mainCtrl.selectedForm === form"></input></label>
<button ng-click="mainCtrl.showForm()">show form</button>
<form ng-if="mainCtrl.isFormActive(1)" ng-controller="FormOneController as formOneCtrl">
<button ng-click="formOneCtrl.submit()">form1 submit</button>
</form>
<form ng-if="mainCtrl.isFormActive(2)" ng-controller="FormTwoController as formTwoCtrl">
<button ng-click="formTwoCtrl.submit()">form2 submit</button>
</form>
</div>

Related

Validate fields using jquery

I'm creating a form that requires to enter some fields.
The basic required attribute won't work on me, so I would like to use jQuery.
Then when those fields were already filled, the submit button will be enabled.
here's my code:
$(function() {
$('#catalog_order').validate(
{
rules:{
schedule: {
required: true
}
},
messages:{
schedule: "Please indicate schedule",
}
});
$('#checkin input').on('keyup blur', function (e) { // fires on every keyup & blur
if ($('#checkin').valid()) {
$('#submit').attr('disabled', false);
}
else {
$('#submit').attr('disabled', true);
}
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery-validate/1.16.0/jquery.validate.js"></script>
<form role="form" id="checkin" name="checkin" method="post">
<label for="dedicatalog"> Dedication Text: </label> <input type="text" name="dedicatalog" id="dedicatalog" size="20" placeholder="Dedication" /> <!-- NOT REQUIRED, but still disable the CHECK IN NOW-->
<label for="schedule"> Date: </label> <input type="date" id="schedule" name="schedule" value="M-D-YY"/> <!-- REQUIRED -->
<label for="figurine_select"> Figurine/s: </label> <!-- NOT REQUIRED, but still disable the CHECK IN NOW-->
<select name="figurine_sel" id="figurine_select" />
<option selected value=" ">--Figurines--</option>
<option value="angel">Angel</option>
<option value="teletubies">Teletubies</option>
</select>
<input type="submit" id="submit" class="btn btn-default" value="Check In Now" disabled="disabled" />
</form>
Hope someone can help me out.
Thank you!!
This Fiddle Should work
Note that for every field you should specify all its option inside js object ( between brackets )
schedule: {
required: true
},
Below working snippet
jQuery.validator.addMethod("dateFormat", function(value, element) {
console.log(value,/^(0?[1-9]|1[0-2])\/(0?[1-9]|1[0-9]|2[0-9]|3[01])\/\d{2}$/.test(value));
return /^(0?[1-9]|1[0-2])\/(0?[1-9]|1[0-9]|2[0-9]|3[01])\/\d{2}$/.test(value);
}, "Invalid Date !");
$(function() {
$('#checkin').validate(
{
rules:{
schedule: {
required:true,
dateFormat: true,
}
},
messages:{
required:"Required Field !"
}
});
$('#checkin input').on('keyup blur', function (e) { // fires on every keyup & blur
if ($('#checkin').valid()) {
$('#submit').attr('disabled', false);
}
else {
$('#submit').attr('disabled', true);
}
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery-validate/1.16.0/jquery.validate.js"></script>
<form role="form" id="checkin" name="checkin" method="post">
<label for="dedicatalog"> Dedication Text: </label> <input type="text" name="dedicatalog" id="dedicatalog" size="20" placeholder="Dedication" />
<label for="schedule"> Date: </label> <input id="schedule" name="schedule" placeholder="M-D-YY"/>
<input type="submit" id="submit" class="btn btn-default" value="Check In Now" disabled />
</form>
This is how I validate that.
return false is just the same us disabling it
<form role="form" id="checkin" name="checkin" method="post">
<input id="dedicatalog"/>
<input id="date" type="date"/>
</form>
<script>
$('#checkin').on('submit', function() {
var dedicatalog = $.trim($('#dedicatalog').val());
var date = $.trim($('#date').val());
if(dedicatalog == '' || date == '') {
return false;
}
});
</script>
You can use the invalidHandler parameter to check for any invalid fields:
invalidHandler: function(event, validator) {
var errors = validator.numberOfInvalids();
if (errors) {
$('#button').hide();
} else {
$('#button').show();
}
}

Angular -multi step form

How I can set val1 to $_POST variable ? Because in step 2 val1 is null.
I try to use $scope, $rootScope, angular.copy() and .val().
This is my html code:
<html ng-app="myApp"><body>
<form action="url.php" method="POST" ng-controller="FormController as vmForm">
<div ng-switch="vmForm.step">
<div class="stepone" ng-switch-when="one">
<label for="val1">Val1</label>
<input type="text" name="val1" ng-model="val1">
<button type="button" ng-click="vmForm.stepTwo()"></button>
</div>
<div class="steptwo" ng-switch-when="two">
<label for="val2">Val2</label>
<input type="text" name="val2" ng-model="val2">
<input type="submit" value="Submit">
</body>
JS
<script>
angular.module('myApp', ['ngAnimate'])
.controller('FormController', FormController);
function FormController($scope) {
var vm = this;
vm.step = "one";
vm.stepTwo = stepTwo;
function stepTwo() {
vm.step = "two";
}
}</script>
$_POST is a PHP variable that's accessible on the server. It contains the payload or request body that's sent in a HTTP POST request as an associative array. It cannot be set directly using Javascript / AngularJS.
What you can do is construct your request data and make a $http POST request to your form action endpoint. Here's a working example based on the code you posted: http://plnkr.co/edit/C1FGvoDrmzYEFMCwymIG?p=preview
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.1/angular.min.js"></script>
<script src="script.js"></script>
</head>
<body ng-app="myApp">
<h1>Hello Plunker!</h1>
<form ng-submit="formSubmit()" ng-controller="FormController">
<p>Val1: {{val1}}</p>
<p>Val2: {{val2}}</p>
<div ng-switch="vm.step">
<div class="stepone" ng-switch-when="one">
<label for="val1">Val1</label>
<input type="text" name="val1" ng-model="$parent.val1">
<button type="button" ng-click="stepTwo()">Go to Step two</button>
</div>
<div class="steptwo" ng-switch-when="two">
<label for="val2">Val2</label>
<input type="text" name="val2" ng-model="$parent.val2">
<input type="submit" value="Submit">
</div>
</div>
</form>
</body>
</html>
script.js
var app = angular.module('myApp', []);
app.controller('FormController', ['$scope','$http',function ($scope,$http) {
$scope.vm = {
step : "one"
};
$scope.val1 = "";
$scope.val2 = "";
$scope.stepTwo = function () {
$scope.vm.step = "two";
}
$scope.formSubmit = function () {
console.log($scope.val1, $scope.val2);
var req = {
url : 'url.php',
method: 'POST',
data : {
val1 : $scope.val1,
val2 : $scope.val2
}
};
$http(req).then(function(response) {
console.log('success', response);
}, function(errorResponse){
console.log('error', errorResponse);
});
}
}]);
Just leave everything as is in your controller and tweak your HTML like this:
<form action="url.php" method="POST" ng-controller="FormController as vmForm">
<div ng-switch="vmForm.step">
<div class="stepone" ng-switch-when="one">
<label for="val1">Val1</label>
<input type="text" name="val1" ng-model="vmForm.val1">
<button type="button" ng-click="vmForm.stepTwo()">Goto Step 2</button>
</div>
<div class="steptwo" ng-switch-when="two">
<input type="hidden" name="val1" value="{{vmForm.val1}}">
<label for="val2">Val2</label>
<input type="text" name="val2" ng-model="val2">
<input type="submit" value="Submit">
</div>
</div>
</form>
The tweak to your code is simply raising the scope of "val1" to "vmForm.val1" so in Step 2 "vmForm.val1" can be assigned to a hidden input field for posting.
Here's the form fields being posted in the browsers debugger:
Here's a Plunker, http://plnkr.co/edit/3VaFMjZuH09A4dIr1afg?p=preview
Open your browsers debugger and view network traffic to see form fields being posted.

ui-grid: problems to access $scope

I have a problem with my ui-grid setup.
There is one ui-grid with an expandable row template loading a html file containing another ui-grid.
In this "subgrid" there is another expandable row template with another html-file containing 3 divs and a third ui-grid.
It works fine and shows all data needed.
In the most inner (is that a word?) expandable row (that with the 3 divs and the third grid) I want to use some functions to show and hide data with ng-show and some crud actions to edit the content of the third ("subsubgrid") ui-grid.
Since functions in the scope are not directly accessible I added an appScopeProvider and put the function in the subGridScope.
Now the function is accessed (I checked it with an alert).
In the function I set some boolean variables (e.g. $scope.showcreate = true), the divs contain ng-show directives (ng-show="showcreate") to hide or show the content of the div.
I debugged the function in the subGridScope and it sets the right values in $scope.showxyz, but the div is not hidden when set to false.
Do I need to re-render the page to "see" the change?
Do I need to change the ng-show directive?
Is there any good tutorial explaining this problem?
How would I access the "CRUD" actions? Would grid.appScope.function work even if the scope is kinda "stacked"?
If you need any more information, just ask, I will provide you with all information needed.
Here is the code:
app.js:
var alarmwesen = angular.module('alarmwesen', ['ui.grid', 'ui.grid.expandable']);
alarmwesen.controller('AlarmwesenCtrl', [
'$scope', '$http', '$log', '$templateCache', 'i18nService', '$interval', 'uiGridConstants', function ($scope, $http, $log, $templateCache, i18NService, $interval, uiGridConstants) {
$http.get('/api/action1)
.success(function (data) {
$scope.Beauftragter = data;
});
$scope.gridOptions = {
enableScrollbars : false,
expandableRowTemplate: 'expandableRowTemplate.html',
expandableRowHeight: 1400,
rowHeight: 36,
expandableRowScope: { subGridVariable: 'subGridScopeVariable' },
enableFiltering: true,
treeRowHeaderAlwaysVisible: false,
columnDefs: [
{ name: 'Trigraph',field:'ZeigeTrigraphen', width: '10%' },
{ name: 'Titel', field: 'Titel' },
],
onRegisterApi: function(gridApi) {
$scope.gridApi = gridApi;
gridApi.expandable.on.rowExpandedStateChanged($scope, function(row) {
if (row.isExpanded) {
row.entity.subGridOptions = {
appScopeProvider: $scope.subGridScope,
enableScrollbars: false,
expandableRowTemplate: 'expandableRowTemplate2.html',
expandableRowHeight: 700,
enableFiltering: false,
expandableRowScope: { subGridVariable: 'subsubGridScopeVariable' },
columnDefs: [
{ name: 'LfdAngabe', field:'LfdAngabe', width: '10%' },
{ name: 'Text', field: 'Text' }],
onRegisterApi:function(gridapi) {
this.subgridApi = gridapi;
gridapi.expandable.on.rowExpandedStateChanged($scope, function(row) {
if (row.isExpanded) {
row.entity.subsubGridOptions = {
appScopeProvider: $scope.subGridScope,
columnDefs: [
{ name: 'Durchführungsverantwortliche',width:'25%' }, { name: 'Auftrag' },
{ name: 'Aktionen', field: 'EinzelauftragId', width: '10%', cellTemplate: '<a id="Details" ng-click = "grid.appScope.BearbeiteAuftrag(row.entity.EinzelauftragId)" class="btn btn-success" )"><i class="glyphicon glyphicon-edit"</a><a id="Details" ng-click = "grid.appScope.LoescheAuftrag(row.entity.AuftragId)" class="btn btn-danger" )"><i class="glyphicon glyphicon-remove"</a>' }
]
};
$http.get('/api/action2')
.success(function(data) {
row.entity.subsubGridOptions.data = data;
});
}
});
}
};
$http.get('/api/action3?trigraph=' + row.entity.ZeigeTrigraphen)
.success(function(data) {
row.entity.subGridOptions.data = data;
});
}
});
}
};
$scope.subGridScope = {
NeuerAuftrag: function () {
$scope.showcreate = true;
$scope.showedit = false;
$scope.showdelete = false;
alert("Geht doch!");
}
};
$http.get('/api/AlarmwesenWebAPI/HoleAlle').then(function (resp) {
$scope.gridOptions.data = resp.data;
$log.info(resp);
});
}]);
html-files
<button class="btn btn-success" ng-click="grid.appScope.NeuerAuftrag()"><i class="glyphicon glyphicon-plus"></i> &#160 Neuen Auftrag erstellen</button>
<div class="well" ng-show="showcreate">
<div class="well-header">Einzelauftrag erstellen</div>
<form role="form" ng-submit="ErstelleEinzelauftrag()" ng-model="Einzelauftrag" name="einzelauftragcreate" id="einzelauftragcreate">
<fieldset>
<input type="text" id="createEinzelauftragsId" class="" ng-model="Einzelauftrag.EinzelauftragsId" />
<input type="text" id="createAlarmkalenderId" class="" ng-model="Einzelauftrag.AlarmkalenderId" />
<input type="text" id="createAlarmmassnahmeTrigraph" class="" ng-model="Einzelauftrag.AlarmmassnahmeTrigraph" />
<input type="text" id="createEinzelmassnahmeLfdAngabe" class="" ng-model="Einzelauftrag.EinzelmassnahmeLfdAngabe" />
<div class="form-group">
<label for="createBeauftragterId">Durchführungsverantwortlicher:</label>
<select name="editBeauftragterId" id="createBeauftragterId"
ng-options="Beauftragter.Bezeichnung for Beauftragter in $scope.Beauftragter track by $scope.Beauftragter.BeauftragterId"
ng-model="$scope.Beauftragter.BeauftragterId"></select>
</div>
<div class="form-group">
<label for="createAuftragstext">Auftrag:</label>
<textarea class="form-control" rows="10" id="createAuftragstext" ng-model="Einzelauftrag.Auftragstext"> </textarea>
</div>
<button type="submit" class="btn btn-default">Auftrag erstellen</button>
</fieldset>
</form>
</div>
<div class="well" ng-show="showedit">
<div class="well-header">Einzelauftrag ändern</div>
<form role="form" ng-submit="BearbeiteEinzelauftrag()" ng-model="Einzelauftrag" name="einzelauftragedit" id="einzelauftragedit">
<fieldset>
<input type="text" id="editEinzelauftragsId" class="" ng-model="Einzelauftrag.EinzelauftragsId" />
<input type="text" id="editAlarmkalenderId" class="" ng-model="Einzelauftrag.AlarmkalenderId" />
<input type="text" id="editAlarmmassnahmeTrigraph" class="" ng-model="Einzelauftrag.AlarmmassnahmeTrigraph" />
<input type="text" id="editEinzelmassnahmeLfdAngabe" class="" ng-model="Einzelauftrag.EinzelmassnahmeLfdAngabe" />
<div class="form-group">
<label for="editBeauftragterId">Durchführungsverantwortlicher:</label>
<select name="editBeauftragterId" id="editBeauftragterId"
ng-options="beauftragter.Bezeichnung for beauftragter in data.Beauftragter track by Beauftragter.BeauftragterId"
ng-model="data.beauftragter.BeauftragterId"></select>
</div>
<div class="form-group">
<label for="editAuftragstext">Auftrag:</label>
<textarea class="form-control" rows="10" id="editAuftragstext" ng-model="Einzelauftrag.Auftragstext"> </textarea>
</div>
<button type="submit" class="btn btn-default">Änderung speichern</button>
</fieldset>
</form>
</div>
<div class="well" ng-show="showdelete">
<div class="well-header">Einzelauftrag löschen</div>
<form role="form" ng-submit="LoescheEinzelauftrag()" ng-model="Einzelauftrag" name="einzelauftragdelete" id="einzelauftragdelete">
<fieldset>
<input type="text" id="deleteEinzelauftragsId" class="" ng-model="Einzelauftrag.EinzelauftragsId" />
<input type="text" id="deleteAlarmkalenderId" class="" ng-model="Einzelauftrag.AlarmkalenderId" />
<input type="text" id="deleteAlarmmassnahmeTrigraph" class="" ng-model="Einzelauftrag.AlarmmassnahmeTrigraph" />
<input type="text" id="deleteEinzelmassnahmeLfdAngabe" class="" ng-model="Einzelauftrag.EinzelmassnahmeLfdAngabe" />
<div class="form-group">
<label for="deleteBeauftragterId">Durchführungsverantwortlicher:</label>
<input type="text" class="form-control" id="deleteBeauftragterId" ng-model="Einzelauftrag.BeauftragterId">
</div>
<div class="form-group">
<label for="deleteAuftragstext">Auftrag:</label>
<textarea class="form-control" rows="10" id="deleteAuftragstext" ng-model="Einzelauftrag.Auftragstext"> </textarea>
</div>
<button type="submit" class="btn btn-default">Auftrag löschen</button>
</fieldset>
</form>
</div>
<div ui-grid="row.entity.subsubGridOptions" style="height: 700px;"></div>
I believe you want to execute the method 'BearbeiteAuftrag' from 3rd Grid while clicking the hyperlink on second column. For that you can try the following changes.
On the 3rd Grid definition (row.entity.subsubGridOptions=), replace the line "appScopeProvider: $scope.subGridScope," with "appScopeProvider: $scope,"
Add the following function just after the "$scope.gridOptions =...."
$scope.BearbeiteAuftrag = function (einzelauftragId){
alert(einzelauftragId);
//Add code for the logic here with the parameter einzelauftragId
};

Multiple submit inputs, do something based on which one was clicked

I have hit a road block. I have 3 different buttons submit, delete and cancel inside a form. Depending on which one was hit, it should get the inputs name or id. My current code for the delete button is this.
if ($("input[value=delete]").click()) {
myApp.alert($(this).attr("name"));
myApp.confirm('Are you sure?', 'Delete Staff', function () {
check_url(url, "delete");
});
return false;
}
Here is the check_url() function, if it will help:
function check_url(recieve_url, type) {
if (recieve_url == undefined || recieve_url == null) {
alert("recieve_url is not set!");
}
$.ajax({
url : recieve_url,
type : 'POST',
dataType : 'json',
data : "type="+type,
success : function (result) {
//alert(result['bg'] + result['message'] + result['caption'])
myApp.alert(result['message'], result['title']);
if (result['redirect'] != null || result['redirect'] != undefined){
window.location = "<?php echo $this->url;?>"+result['redirect'];
}
//notify_response(result['message'], result['bg'], result['caption']);
},
error : function (xhr, ajaxOptions, thrownError) {
myApp.alert(xhr.responseText);
myApp.alert(xhr.status);
myApp.alert(thrownError);
}
})
}
I have tried an else if and use "input[value=submit]", but the other submit buttons will use this delete one instead. Is there something I'm currently missing?
Edit
<form onsubmit="return submit_edit(this.action);" method="post" action="<?php echo $this->url."Staff/EditSubmit/".$value['id']; ?>">
<div class="content-block-title"><?php echo $value['first_name'].' '.$value['last_name']?></div>
<div class="list-block inset">
<ul>
<li>
<div class="item-content">
<div class="item-inner">
<div class="item-title label">Phone Number</div>
<div class="item-input">
<input type="tel" value="<?php echo $value['phone_number']?>">
</div>
</div>
</div>
</li>
<li>
<div class="item-content">
<div class="item-inner">
<div class="item-title label">Address</div>
<div class="item-input">
<input type="text" value="<?php echo $value['address']?>">
</div>
</div>
</div>
</li>
<li>
<label class="label-checkbox item-content">
<!-- Checked by default -->
<?php if($value['admin'] == 1): ?>
<input type="checkbox" name="admin_check" value="true" checked="checked">
<?php else: ?>
<input type="checkbox" name="admin_check" value="false">
<?php endif ?>
<div class="item-media">
<i class="icon icon-form-checkbox"></i>
</div>
<div class="item-inner">
<div class="item-title">Admin</div>
</div>
</label>
</li>
<li>
<label class="label-checkbox item-content">
<!-- Checked by default -->
<?php if($value['staff'] == 1): ?>
<input type="checkbox" name="staff_check" value="true" checked="checked">
<?php else: ?>
<input type="checkbox" name="staff_check" value="false">
<?php endif ?>
<div class="item-media">
<i class="icon icon-form-checkbox"></i>
</div>
<div class="item-inner">
<div class="item-title">Staff</div>
</div>
</label>
</li>
<li>
<label class="label-checkbox item-content">
<!-- Checked by default -->
<?php if($value['disabled'] == 1): ?>
<input type="checkbox" name="disabled_check" value="true" checked="checked">
<?php else: ?>
<input type="checkbox" name="disabled_check" value="false">
<?php endif ?>
<div class="item-media">
<i class="icon icon-form-checkbox"></i>
</div>
<div class="item-inner">
<div class="item-title">Disabled</div>
</div>
</label>
</li>
<li>
<label class="label-checkbox item-content">
<!-- Checked by default -->
<?php if($value['active'] == 1): ?>
<input type="checkbox" name="active_check" value="true" checked="checked">
<?php else: ?>
<input type="checkbox" name="active_check" value="false">
<?php endif ?>
<div class="item-media">
<i class="icon icon-form-checkbox"></i>
</div>
<div class="item-inner">
<div class="item-title">Active</div>
</div>
</label>
</li>
</ul>
</div>
<div class="list-block inset">
<div class="row">
<div class="col-33">
<input id="submit" type="submit" name="submit" value="Submit" class="button button-big button-fill color-green">
</div>
<div class="col-33">
<input id="delete" type="submit" name="delete" value="Delete" class="button button-big button-fill color-red">
</div>
<div class="col-33">
<input id="cancel" type="submit" name="cancel" value="Cancel" class="button button-big button-fill color-blue">
</div>
</div>
</div>
</form>
And the following function:
function submit_edit(url) {
if ($("input[value=delete]").click()) {
myApp.confirm('Are you sure?', 'Delete Staff', function () {
check_url(url, "delete");
});
return false;
}
}
I forgot to include the function name at the beginning.
If you want to point all the buttons to a common place, but change something slightly depending on which one has been clicked, you do it like this:
$(function () {
// A single click event handler to all the submit buttons.
$('input[type=submit]').on('click', function (event) {
// Prevent the default behavior for the form submit.
event.preventDefault();
// The value of the clicked one.
var buttonValue = $(this).attr('value');
// Carry on with your code...
if (buttonValue == 'delete') {
myApp.confirm('Are you sure?', 'Delete Staff', function () {
check_url(url, "delete");
});
}
else if (buttonValue == 'submit') {
}
else {
}
});
});
UPDATE
After chatting in the comments, I believe that's what you're after actually:
Add this to your form:
<!-- This field will hold which submit button has been clicked -->
<input type="hidden" name="clicked" id="clicked" value="" />
And change your script:
function submit_edit(url) {
// Check which submit button has been clicked
// by getting the hidden input value.
var value = $('#clicked').val();
if (value == 'delete') {
myApp.confirm('Are you sure?', 'Delete Staff', function () {
check_url(url, "delete");
});
}
else if (buttonValue == 'submit') {
}
else {
}
}
$(function () {
// A single click event handler to all the submit buttons.
$('input[type=submit]').on('click', function () {
// The value of the clicked one.
var buttonValue = $(this).attr('value');
// Store the value in the hidden field.
$('#clicked').val(buttonValue);
});
});
you should do something like this i guess:
$("input[value=delete]").click(function(){
myApp.alert($(this).attr("name"));
myApp.confirm('Are you sure?', 'Delete Staff', function () {
check_url(url, "delete");
});
return false;
});
Why don't you bind different function calls to different input tags. Like:
<input type="submit" value="Submit" onclick="javascript:SubmitClicked(parameters)">
And for a delete button
<input type="submit" value="Delete" onclick="javascript:DeleteClicked(parameters)">
You need to handle the click-event using an event handler instead of a conditional-statement, like so:
$("input[value=delete]").click(function() {
myApp.alert($(this).attr("name"));
myApp.confirm('Are you sure?', 'Delete Staff', function () {
check_url(url, "delete");
});
return false;
});
...because if ($("input[value=delete]").click()) will always return true.
The reason: you're effectively raising a click()-event instead of checking for an existing condition. But... you still get a response that causes the condition check to return true and that's why this bit of code always runs no matter what button you click :)
You could also grab clicks on all buttons using this:
$("input").click(function() {
// Check for value of $(this).attr("value") and act accordingly
if ($(this).attr("value") == "delete")
{
// Do delete-stuff
}
else if ($(this).attr("value") == "submit")
{
// Do other stuff
}
});
Firstly, you usually don't want to have multiple submit buttons on a form (as you're experiencing, which one triggers the submit can be problematic). Instead, opt for one submit button and two other buttons. In addition to this, I would remove the onclick attribute from your form (it is unnecessary and if you target the click events of the buttons themselves it is redundant as well).
You should treat submit as what happens after you've done any pre-processing so binding to click events, then conditionally raising the submit is better than always submitting but conditionally stopping the submit.
That being said, you can bind to the click event of the buttons and the submit using code like the following:
What you need is to use JQuery's event argument to help you identify the source, like so:
<div id="actions">
<form>
<input type="submit" id="first-button" value="Submit" />
<br />
<input type="button" id="second-button" value="Delete" />
<br />
<input type="button" id="third-button" value="Cancel" />
</form>
</div>
<script type="text/javascript">
$(function () {
//Setup the click for all of the buttons (these could be hyperlinks or any other element as well).
$("#actions").find("input[type='submit'], input[type='button']").click(function (e) {
//Do some conditional stuff based on the element that triggered the event
var sender = $(e.currentTarget);
switch (sender.val()) {
case "Delete":
var shouldDelete = confirm("Are you sure you want to delete?");
break;
case "Submit":
alert("Submit clicked.");
$("#actions").find("form").submit();
break;
case "Cancel":
alert("Cancelled.");
break;
default:
alert("Unknown clicked.");
break;
} // end switch
e.preventDefault();
});
});
</script>
Here is a fiddle: http://jsfiddle.net/xDaevax/rhLdxjzj/
JQuery's event argument e has lots of useful information about which element triggered the event. See the JQuery documentation here: http://api.jquery.com/on/

Form is not checked by if statement

I have two forms with id formA and comments and I want to submit them via AJAX. But the if and else here doesn't check the form. I always get alert hello3.
JS:
function submitformbyajax() {
var currentForm = $(this);
if (currentForm.attr("id") == 'formA') {
$.ajax({
type: 'post',
url: 'commentformhandler.php',
data: $("form").serialize(),
success: function() {
$("#refresh").load("commentform.php #refresh");
}
});
} else if (currentForm.attr("id") == 'comments') {}
alert("hello3");
return false;
}
the function is called by
<div>
<form name="formA" id="formA" action="" method="" onsubmit="return submitformbyajax();">
<textarea name="comment" id="commentform" style="width:90%; height:45px;"></textarea>
<input type="submit" name="submit" value="submit" id="submitbtn" />
<input type="hidden" name="onid" value="2" id="submitbtn"/>
</form>
</div>
here is the full demo page ....
<?php
?>
<html>
<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.1/jquery.min.js"> </script>
<script>
function submitformbyajax (){
var currentForm = $(this);
if (currentForm.attr("id") == 'formA' ) {
$.ajax({type: 'post',
url: 'commentformhandler.php',
data: $("form").serialize(),
success: function(){
$("#refresh").load("commentform.php #refresh");
alert ("hello1");
}
} );
}
else if (currentForm.attr("id") == 'comments') {
alert("hello2");
}
alert ("hello3");
return false;
}
</script>
<title>
comment forms..
</title>
</head>
<body>
<div>
<form name="formA" id="formA" action="" method="" onsubmit="return submitformbyajax();">
<textarea name="comment" id="commentform" style="width:90%; height:45px;"></textarea>
<input type="submit" name="submit" value="submit" id="submitbtn" />
<input type="hidden" name="onid" value="2" id="submitbtn"/>
</form>
</div>
<div id="refresh">
<?php
include_once('databaseconnection.php');
$selectdata=mysql_query("select * from `fetwork_view` ");
while($selectedinarray=mysql_fetch_array($selectdata)){ ?>
<table>
<tr>
<td>
<?=$selectedinarray['view']?>
</td>
</tr>
<tr>
<td>
<form name="comment" id="comments" action="" method="">
<textarea name="comment" id="commentform" style="width:70%; height:25px;"></textarea>
<input type="submit" name="submit" value="submit" id="submitbtn" />
<input type="hidden" name="onid" value="2" id="submitbtn"/>
</form>
</td>
</tr>
</table>
<?php } ?>
</div>
</body>
</html>
Your alert(...) statement is executed regardless of condition tested by if. It is executed right after that if.
Note that ajax will not redirect the "flow" of the code. Browser will just "launch" the AJAX request and continue. Then, after a response from server is received - AJAX callback function will be executed.
Update:
To "pass" your form to submitformbyajax function add this as an argument:
<form name="formA" id="formA" onsubmit="submitformbyajax(this);">
JS:
function submitformbyajax(your_form) {
var currentForm = $(your_form);
I think you should use
$("form#formA").submit(function(){
alert(1);
});

Categories

Resources