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

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/

Related

Removing parent div containing many divs and spans and sections in it using javascript ajax

I have a comment div. so in this div, i have some other divs and spans to show edit and delete buttons, comment text, time, user name, profile pic and footer section for like or dislike.
Here is full code
while($fetch = mysql_fetch_array($rest)) {
<div class="container1" id="container1">
<div class="div-image">
<img src="images.jpg" />
</div>
<div class="div-right">
<div class="div-right-top">
<div class="div-user-name">
<span class="text-user-name">
UserName
</span>
</div>
<div class="div-time">
<span class="time-text">
comment-time
</span>
</div>
<?php if (isset($_SESSION['userid'])) { ?>
<form action="" method="post">
<input type="hidden" name="commentingid" value="FETCHVALUE" />
<div class="div-myoptions">
<span class="time-text div-option-div">
<?php if($userid !== $loggedid) { ?>
<button class="mycomoptions" type="submit" name="favorite">Fav</button>
<button class="mycomoptions" type="submit" name="flag">Report</button>
</form>
<?php } else { ?>
<button class="edit" type="button">Edit</button>
<button class="delete" data-emp-id="<?php echo $comentid ?>">X</button>
<?php } ?>
</span>
</div>
<?php } ?>
</div>
<div class="div-right-mid comment-text">
<?php echo $fetch['usercom'] ?>
</div>
<section class="right-bottom small">
<div class="div-like">
<span class="text-bottom">
Up
</span>
</div>
<div class="div-dislike">
<span class="text-bottom">
Down
</span>
</div>
<div class="div-reply">
<span class="text-bottom">
reply
</span>
</div>
<div id="editcoment" class="collapse">
<p>
<form action="" method="post" name="updatecom" onSubmit="return validateForm();">
<input type="text" />
<button type="submit" name="updatecom">Submit</button></p</form>
</p>
</div>
</section>
</div>
</div>
All I want to do is to delete the container1 div when i click on Delete button
Delete button is working, comment is deleted from database but its not been deleted from the page right after confirmation dialogue done with ajax. so when i refresh the page, comment is deleted. but why is it not working with ajax. is it just because i have spans and sections in the parent div?
here its javascript code
$(document).ready(function(){
$('.mycomoptions').click(function(e){
e.preventDefault();
var delete = $(this).attr('data-emp-id');
var container1 = $(this).parent("#container1 div");
bootbox.dialog({
message: "Delete Comment??",
title: "Sure Delete?",
buttons: {
success: {
label: "No",
className: "btn",
callback: function() {
$('.bootbox').modal('hide');
}
},
danger: {
label: "Yes",
className: "btn-danger",
callback: function() {
$.ajax({
type: 'POST',
url: '<?php echo $_SERVER['PHP_SELF'];?>',
data: 'delete='+delete
})
.done(function(){
container1.remove();
})
}
}
}
});
});
});
When i use simple divs then it works fine, but with this template of divs, its not removing container div on confirming Yes from confirmation dialogue. Need Help to understand how to make container variable to select parent div including all internal divs
You're using var container1 = $(this).parent("#container1 div"); but you have no element with an id of container1. Do you mean to be using $(this).parent(".container1 div")?

submit a form and prevent from refreshing it

i'm working on a email sending function on a project. here when i fill the form and after sending it the web site page getting refresh and showing white background page. i need to prevent that from the refreshing and submit the form. here i'l attach the codes and can someone tell me the answer for this question.
HTML code for form
<form class="form-vertical" onsubmit="return sendEmail();" id="tell_a_friend_form" method="post" action="index.php?route=product/product/tellaFriendEmail" enctype="multipart/form-data">
<div class="form-group ">
<label class="control-label ">Your Name <span >* </span> </label><br>
<div class="form-group-default">
<input type="text" id="senders_name" name="sender_name" value="" class="form-control input-lg required" >
</div>
</div>
<div id="notify2" class="">
<div id="notification-text2" class="xs-m-t-10 fs-12"></div>
<!--<button type="button" class ="close" id="noti-hide">×</button>-->
</div>
<div class="form-group ">
<label class="control-label ">Your Email <span >* </span> </label><br>
<div class="form-group-default">
<input type="text" id="sender_email_ID" name="sender_email" value="" class="form-control input-lg" >
</div>
</div>
<div id="notify1" class="">
<div id="notification-text1" class="xs-m-t-10 fs-12"></div>
<!--<button type="button" class ="close" id="noti-hide">×</button>-->
</div>
<div class="form-group ">
<label class="control-label">Your Friends' Email <span >* </span></label>
<p class="lineStyle">Enter one or more email addresses, separated by a comma.</p>
<div class="form-group-default">
<input type="text" value="" id="receiver_email" class="form-control required" name="receivers_email" >
</div>
</div>
<div id="notify" class="">
<div id="notification-text" class="xs-m-t-10 fs-12"></div>
<!--<button type="button" class ="close" id="noti-hide">×</button>-->
</div>
<div >
<label domainsclass="control-label ">Add a personal message below (Optional) <br></label>
<div class="form-group-default">
<textarea type="text" id="tell_a_friend_message" name="tell_a_friend_message" class="form-control" rows="10" col="100" style=" width: 330px; height: 100px;"></textarea>
</div>
</div>
<div id="notify3" class="">
<div id="notification-text3" class="xs-m-t-10 fs-12"></div>
<!--<button type="button" class ="close" id="noti-hide">×</button>-->
</div>
<input type="hidden" name="product_url" id="product_url_field" value="">
<div class="p-t-15 p-b-20 pull-right">
<button id="send_mail_button" class="btn btn-rounded btn-rounded-fl-gold text-uppercase" name="submit" onclick="return sendEmail();" >Send</button>
<button id="cancel_email_form" class="btn btn-rounded btn-rounded-gold text-uppercase btn-margin-left" data-dismiss="modal" aria-hidden="true" >Cancel</button>
</div>
javascript code:
<script>
function sendEmail() {
document.getElementById('product_url_field').value = window.location.href
var emailpattern = /^\w+([\.-]?\w+)*#\w+([\.-]?\w+)*(\.\w{2,3})+$/;
var receivers_email = $("#receiver_email").val();
var sender_email = $("#sender_email_ID").val();
var sender_name = $("#senders_name").val();
var email_pathname = window.location.pathname;
var product_url = window.location.href;
if (receivers_email == '') {
$('#notify').removeClass().addClass("alert-danger");
$('#notification-text').empty().html("Invalid e-mail or fill the email address correctly");
$('#notification-text').show();
setTimeout(function() {
$('#notification-text').fadeOut('slow');
}, 10000);
return false;
}
else {
!emailpattern.test(receivers_email);
}
if(sender_name == ''){
$('#notify2').removeClass().addClass("alert-danger");
$('#notification-text2').empty().html("please fill the name");
$('#notification-text2').show();
setTimeout(function() {
$('#notification-text2').fadeOut('slow');
}, 10000);
return false;
}
if (sender_email == '') {
$('#notify1').removeClass().addClass("alert-danger");
$('#notification-text1').empty().html("Invalid e-mail or fill the email address correctly");
$('#notification-text1').show();
setTimeout(function() {
$('#notification-text1').fadeOut('slow');
}, 10000);
return false;
}
else {
!emailpattern.test(sender_email);
}
$('#notify3').removeClass().addClass("alert-success");
$('#sender_email').val('');
$('#notification-text3').empty().html("Email has sent successfully");
$('#notification-text3').show();
setTimeout(function() {
$('#notification-text3').fadeOut('slow');
}, 10000);
return true;
}
</script>
Controller php class:
public function tellaFriendEmail(){
if (isset($_POST['submit'])) {
$receiver_email = $_POST['receivers_email'];
$name = $_POST['sender_name'];
$email = $_POST['sender_email'];
$message = $_POST['tell_a_friend_message'];
$products_url = $_POST['product_url'];
$mail = new Mail();
$mail->protocol = $this->config->get('config_mail_protocol');
$mail->parameter = $this->config->get('config_mail_parameter');
$mail->smtp_hostname = $this->config->get('config_mail_smtp_hostname');
$mail->smtp_username = $this->config->get('config_mail_smtp_username');
$mail->smtp_password = html_entity_decode($this->config->get('config_mail_smtp_password'), ENT_QUOTES, 'UTF-8');
$mail->smtp_port = $this->config->get('config_mail_smtp_port');
$mail->smtp_timeout = $this->config->get('config_mail_smtp_timeout');
$mail->setTo($receiver_email);
$mail->setFrom($this->config->get('config_email'));
$mail->setSender("Waltersbay");
$mail->setSubject($name.' '.'wants you to checkout this product from waltersbay.com');
if ($message !=''){
$mail->setHtml('Hi Dear,<br/> please checkout the following product that'.' '.$name.' '.'wanted you to see.'.' '.'we hope that you will like it !!!!<br/>'.$products_url.'<br/>'.'<br/> Here is a little message from your friend:<br/>'.$message.'<br/>'.'<br/> Thank you, <br/> ');
}
else{
$mail->setHtml('Hi Dear,<br/> please checkout the following product that'.' '.$name.' '.'wanted you to see.'.' '.'we hope that you will like it !!!!<br/>'.$products_url.'<br/>'/*.'<br/> Here is a little message from your friend:<br/>'.$message.'<br/>'*/.'<br/> Thank you, <br/> ');
}
$mail->send();
}
else{
header('location : tella_friend.tpl');
}
}
}
Put a hidden input in your form. before submitting in your js, fill it with a new key according to time.
in your php file check if key is duplicate or not? or even if its filled?
Because js fill this input after clicking the submit button, every time you submit your form you have a new key! If you refresh the form, you're gonna send the previous value again.
For your problem then best practice recommended is to use jquery ajax requests.
Firstly if you pretend to use "submit" element then do following,
$(".form-vertical").submit(function(e) {
e.preventDefault();
//send ajax with your form data. Ample examples on SO already.
$.ajax(.....);
});
Other option we would recommend is to avoid using 'submit' behavior at first place for requirement you have.
1. Use button elements instead of submit element.
2. Attach click event on button. i.e. in your case 'send'.
3. On click, send ajax as described above. This will avoid doing things like onsubmit="return sendEmail();" you had to do.
4. Also following is not required as well,
$(".form-vertical").submit(function(e) {
e.preventDefault();
as it will be done as follows,
$("button#buttonId").click(function(e) {
// your ajax call.....
}

Merge two forms with two radio button and one form

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>

Press Enter and the button function to be called

I have a page login, with label of user and pass. I want to know, how I do to when I press Enter in textbox to the button function to be called.
Login.js
$(document).ready(function () {
$("#btnOK").on("click", function () {
var UserName = $("#txt_user").val();
var Password = $("#txt_pass").val();
.
.
.
});
Login.cshtml
form action="#Url.Action("Default")" method="post">
<div id="boxLogin">
<br />
<label id="lbl_login">Login</label>
<div id="log">
<img src="../../img/images.jpg" alt=""/>
</div>
<div class="boxUser">
<label id="lbl_user">User: </label>
<input id="txt_user" type="text" value="" name="UserName">
</div>
<div class="boxPass">
<label id="lbl_pass">Pass: </label>
<input id="txt_pass" type="password" name="Password">
</div>
<div id="btns">
<input type="button" ID="btnOK" class="btn" value="Confirm" />
<input type="button" ID="btnCancel" class="btn" value="Cancel" />
</div>
</div>
</form>
You can submit it using below code:
$('#txt_usuario').on('keyup', function(e) {
var code = (e.keyCode ? e.keyCode : e.which);
if (code == 13) {
$( "#form" ).submit();
}
});
where form - is your form id.
$("#txt_senha").keyup(function(event){
if(event.keyCode == 13){
$("#btnOK").click();
}
});
Simple method is to change the btnOK element to a submit button (type="submit"), and change the javascript to run on the onsubmit event of the form.

field empty error for pop-up form

Can I have yout help pleas there,I make a validation field for a popup form :
function prepareEventHandlers() {
document.getElementById("contact").onsubmit = function () {
if (document.getElementById("message").value == '') {
document.getElementById("errorMessage").innerHTML = 'the field should not be empty!';
return false;
}
else {
document.getElementById("errorMessage").innerHTML = '';
return true;
}
};
}
window.onload = function () {
prepareEventHandlers();
}
then the html code :
<div id="form-content" class="modal hide fade in" style="display: none;">
<div class="modal-body">
<form class="contact" name="contact" >
<label class="label" for="message">Enter a Message</label><br>
<textarea id="message" name="message" class="input-xlarge"></textarea>
<p><span id="errorMessage"></span></p>
</form>
</div>
<div class="modal-footer">
<input class="btn btn-success" type="submit" value="Send!" id="btnsubmit">
No!
</div>
and I got this error :
TypeError: document.getElementById(...) is null document.getElementById("contact").onsubmit = function () {
Any Idea?
Edit:
OK I add id="contact" to my form so the error is gone but now the popup form is displyaed but when I try to click send with empty or not empty value nothing is happened...
just close </form> after <input class="btn btn-success" type="submit" value="Send!" id="btnsubmit">
and change html form id to contact

Categories

Resources