Submit form via Enter key and Submit button both - javascript

Hi I have form and following things are bothering me:
1. Form does not submit on pressing enter.
2. When i press enter in input field then Search Now button needs to be pressed
twice to search places.
Form is displayed as below:
<form method="POST" id="mylocform" action="">
<h3 class="animated slideInLeft delay-2">
<input type="text" placeholder="Start Typing Your Location" id="geocomplete"
style="color:black;width:100%;padding:5px;height:45px;border-radius:5px"
autocomplete="off" class="chkmeloc" onblur="checkmylocform()"/></h3>
<input type="submit" class="btn btn-default btn-lg animated fadeInUpBig delay-3"
style="color: black;background-color: #FFF;border-color: #FFF;"
value="Search Now!"/>
</form>
Validation goes like below:
$(document).ready(function(){
$("form#mylocform").submit(function(event) {
event.preventDefault();
validate();
});
});
function checkmylocform(){
var checkOdlen = $(".chkmeloc").val().length;
if(checkOdlen==0){
$(".chkmeloc").css("border-color","#F05F68");
$(".chkmeloc").focus();
$(".chkmelocmess").html('<button type="submit" class="btn btn-default
btn-lg" style="background: #FFF;color:red">
<i class="fa fa-warning text-red"></i>
Select Your Location</button>');
return false;
}
else{
$(".chkmeloc").css("border-color","#0C9");
$(".chkmelocmess").html('<input type="submit" class="btn btn-default
btn-lg" style="color: black;background-color: #FFF;border-color: #FFF;"
value="Search Now!"/>');
return true;
}
}
function validate(){
$.each($('form :input'),function(){
$(this).blur().change();
});
if(!checkmylocform()){
return false;
}
else{
submitform();
}
}
Submit Form has code to submit form via ajax as below. Please help me to get out of this situation.

$("Your selector").keypress(function (e) {
var key = e.which;
if(key == 13) // the enter key code
{
$(input[type = submit]).click();
return false;
}
});

look at this site:
http://tjvantoll.com/2013/01/01/enter-should-submit-forms-stop-messing-with-that/
the site says that enter key is automaticly a submit in al browser

Try This
File index.html :
<form class="form-inline" action="" method="POST">
<input type="password" name="token" placeholder="Enter Facebook access token..." class="subscribe-email">
<button type="submit" class="btn">Start!</button>
</form>
<div class="success-message"></div>
<div class="error-message"></div>
File script.js :
$('.get_token form').submit(function(e) {
e.preventDefault();
var postdata = $('.get_token form').serialize();
$.ajax({
type: 'POST',
url: 'assets/submit_token.php',
data: postdata,
dataType: 'json',
success: function(json) {
if(json.valid == 0) {
$('.success-message').hide();
$('.error-message').hide();
$('.error-message').html(json.message);
$('.error-message').fadeIn();
}
else {
$('.error-message').hide();
$('.success-message').hide();
$('.get_token form').hide();
$('.success-message').html(json.message);
$('.success-message').fadeIn();
}
}
});
});

Related

How to get the button to work on keyboard Enter?

I'm trying to get the button to work without clicking on it.
I tried but with using 'Submit' and 'button', neither works unless user clicks the button.
<input id="txtDusNumber" class="form-control form-control-sm" type="text" />
<input type="submit" name="submit" class="btn " value="Search" id="enter-btn" onclick="ShowCard()" />
<input type="button" class="btn " value="Search" onclick="ShowCard()" />
<script>
function ShowCard() {
var dusNumberVal = $('#txtDusNumber').val();
if (dusNumberVal) {
$.ajax({
url: "#Url.Action("display","Card")",
data: { number: dusNumberVal },
type: 'GET',
success: function (result) {
$('#results').html(result);
},
error: function () {
alert("error...");
}
});
} else {
alert('Please enter Number.');
}
}
</script>
Try this:
$(document).keypress(function(e) {
if(e.which == 13) {
ShowCard();
}
});
function ShowCard(){
...
}
What it does is when the page is loaded, once you press enter, the ShowCard function gets executed.
Wrap <button type="submit"> in <form> tag

How to do Multiple Proccess in One JavaScript

I want to processes three command.
check if input empty or not, if empty the proccess stop, if not continue to command 2 and 3.
insert input data to database.
show and hide between 2 div.
Here what I try
function SubmitFormData() {
if ($.trim($('#url').val()) == '') {
alert('Input can not be left blank');
return false;
}
var url = $("#url").val();
$.post("shorten.php", {
url: url
},
function(data) {
$('#result_div').html(data);
$('#short_form')[0].reset();
});
$("#result_div").hide();
$("#submit").show();
$('#submit').click(function() {
$("#result_div").slideToggle();
$("#short_div").slideToggle();
});
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form class="col-12" id="short_form" name="short_form" method="post">
<div class="input-group" id="short_div">
<input type="text" class="form-control" id="url" name="url" placeholder="Your Long URL" required>
<div class="input-group-append">
<button type="button" id="submit" name="submit" class="btn btn-default" onclick="SubmitFormData();"><i class="fa fa-search" aria-hidden="true" style="font-size: 25px;"></i>Submit</button>
</div>
</div>
<div class="input-group" id="result_div">
</div>
</form>
A/C to the description given by you :-
You are on right track just try like the code given, it should work for you -
$(document).ready(function(){
$('#result_div').hide();
$('#submit').on('click', function(){
var inputVal = $.trim($("#url").val());
if(inputVal != ''){
$.post('shorten.php', {url: inputVal}, function(response){
$('#result_div').html(response).show();
$('#short_form')[0].reset();
});
$("#result_div").slideToggle();
$("#short_div").slideToggle();
}else{
alert('Please insert valid input')
}
});
});

Submitting two forms separately in one page with separate thankyou message

I've a page which have two different forms:
Form 1:
<form id="info-form" method="POST" action="">
<label for="name">What is your Name? </label>
<input required type="text" name="name" placeholder="Enter your full name here." />
<label for="email">What is your email ID? </label>
<input required type="email" name="email" placeholder="your.name#email.com" />
<label for="mobile-number">What is your 10-Digit Mobile Number? </label>
<input required type="text" name="mobile-number" maxlength="10" placeholder="Enter num." />
<label for="posting-place">What is your current place of residence? </label>
<input type="text" name="place" placeholder="Enter your current residing place here." />
<button type="submit" class="btn btn-lg btn-success">
  Submit
</button>
<button type="reset" class="btn btn-lg btn-warning">
Reset
</button>
</form>
Form 2:
<form id="contact-form" method="POST" action="">
<label for="name">What is your Name? </label>
<input type="text" name="name" placeholder="Enter your full name here." />
<label for="email">What is your email ID? </label>
<input type="email" name="email" placeholder="your email" />
<label for="message"> Your Message: </label>
<textarea id="message" name="message" rows="5" placeholder="Type in your message here"></textarea>
<button id="submit_button" type="submit" class="btn btn-lg btn-success">
Send
</button>
<button id="reset_button" type="reset" class="btn btn-lg btn-warning">
Reset
</button>
</form>
I then have these below thank you messages after the closing form tag of both the above two forms
Thank you message after submitting Form 1:
<div style="display:none;" id="thankyou_form">
<p><em>Thank You</em> for submitting!</p>
</div>
Thank you message after submitting Form 2:
<div style="display:none;" id="thankyou_contact">
<p><em>Thank You</em> for contacting! We will get back to you soon!</p>
</div>
I then have two script for displaying the thank you message on the same page after the form is submitted.
<script type="text/javascript">
$(function ()
{
$('form').submit(function (e)
{
e.preventDefault();
$.ajax(
{
url: this.action,
type: this.method,
data: $(this).serialize(),
success: function (response)
{
console.log(response);
if(response.result == 'success')
{
// this is for the second form. For the 1st form ID is changed to thankyou_form
document.getElementById("thankyou_contact").style.display = "inline";
}
else
{
// this is for the second form. For the 1st form ID is changed to thankyou_form
document.getElementById("thankyou_contact").style.display = "none";
}
}
});
});
});
</script>
But when I submit the second form the thankyou message is also displayed is the first form. Also, the form is submitted twice.
Can you please inform me how to identify both the javascript separately? Or, Can I combine both the script into one but both submit buttons working independently of each other?
It would be very much helpful and also enlightening for me if you can point out my mistake.
P.S. I'm a beginner.
Edit1: The javascript code was modified (but currently non-working) as per suggestion from David. The new code is:
<script type="text/javascript">
$(function ()
{
$('form').submit(function (e)
{
if(e.target === 'form#info-form')
{
e.preventDefault();
$.ajax(
{
url: this.action,
type: this.method,
data: $(this).serialize(),
success: function (response)
{
console.log(response);
if(response.result == 'success')
{
document.getElementById("thankyou_info").style.display = "inline";
}
else
{
document.getElementById("thankyou_info").style.display = "none";
document.getElementById("sorry_info").style.display = "inline";
}
}
});
}
if(e.target === 'form#contact-form')
{
e.preventDefault();
$.ajax(
{
url: this.action,
type: this.method,
data: $(this).serialize(),
success: function (response)
{
console.log(response);
if(response.result == 'success')
{
document.getElementById("thankyou_contact").style.display = "inline";
}
else
{
document.getElementById("thankyou_contact").style.display = "none";
document.getElementById("sorry_contact").style.display = "inline";
}
}
});
}
});
});
</script>
Use event.target to determine which form is getting submitted, You need to refine your code as,
if(response.result == 'success')
{
// Determine if the submission came from "Info Form" or "Contact Form"
if(e.target === 'form#info-form')
{
document.getElementById("thankyou_form").style.display = "inline";
}
else
{
document.getElementById("thankyou_contact").style.display = "inline";
}
}
else
{
// this is for the second form. For the 1st form ID is changed to thankyou_form
document.getElementById("thankyou_form").style.display = "none";
document.getElementById("thankyou_contact").style.display = "none";
}

Form submission works with html but not javascript at the same time

I want to achieve that the user can search on the website and then filter his search results by clicking on a link (which triggers javascript) so he gets people instead of articles. In terms of database and PHP it works, but when I try to submit this code:
<form id="searchform" class="navbar-form" role="search" method="post" action="/search">
{{ csrf_field() }}
<div class="input-group">
<input type="text" class="form-control" style="width: 300px;" placeholder="Search" name="searchterm" id="srch-term" value="<?php if(isset($searchterm)) { echo $searchterm; } ?>">
<div class="input-group-btn">
<button class="btn btn-default" type="submit"><i class="glyphicon glyphicon-search"></i></button>
</div>
</div>
</form>
... with this code:
function submit() {
document.getElementById("searchform").submit();
}
this is what I use to communicate with my database initially, the url leads to a PHP function that returns the users. (works)
The following code only gets submitted with HTML button, but not with the link which will submit the form through javascript.
$("#searchform").submit(function(e){
e.preventDefault();
var form = $(this);
$.ajax({
type: "POST",
url : "/search/people",
data : form.serialize(),
dataType : "json",
success : function(data){
if(data.length > 0) {
console.log(data);
} else {
console.log('Nothing in the DB');
}
}
}, "json");
});
I get no results in the console when I press the link, BUT with the search bar button (html) I get something in the console.
So what I want to do is with the second link in this code:
<div class="list-group">
sounds
<a id="people" onclick="submit()" href="#" class="list-group-item">people</a>
requests
</div>
I will submit the javascript that part is not working.
Any suggestions on what I can try?
Here's a working example of your code:
https://jsfiddle.net/jonva/x99nxz0h/1/
It seems perfectly fine.
<form id="searchform" class="navbar-form" role="search" method="post" action="/echo/json">
abc
<div class="input-group">
<input type="text" class="form-control" style="width: 300px;" placeholder="Search" name="searchterm" id="srch-term" value="">
<div class="input-group-btn">
<button class="btn btn-default" type="submit">Search</button>
</div>
</div>
</form>
$("#searchform").submit(function(e) {
e.preventDefault();
var form = $(this);
$.ajax({
type: "POST",
url: "/echo/json",
data: form.serialize(),
dataType: "json",
success: function(data) {
if (data.length > 0) {
console.log(data);
} else {
console.log('Nothing in the DB');
}
}
}, "json");
});

Automatic Login

I'm trying to automatically login a user. The JavaScript code below here actually does that but only when I remove the 'login/submit' div (), and then stops working when I include the 'div'. I can't remove this 'div' as that is my submit button. I don't know how to get around this problem, any help will be appreciated.
HTML;
<body>
<form name="EventConfirmRedirection" class="Form" method="post" action="index.php" id="myForm" data-ajax="false">
<div class="user_login3"><input style="text-transform:lowercase" type="text" name="username" id="username" placeholder="username"></div>
<div class="user_login3"><input type="password" name="password" id="password" placeholder="password"></div>
<div style="margin-left:5%; width:45%; font-size:5px;">
<input data-theme="c" type="checkbox" id="rememberMe" name="rememberMe"/>
<label for="rememberMe"><span style="font-size:12px">remember me</span></label>
</div>
<div style="margin-left:5%; color:#FF0000; font-weight:bold" id="error"></div>
<div class="login"><input type="submit" value="LOGIN" name="submit" data-theme="e" id="submit"></div>
</form>
</body>
JAVASCRIPT;
$(document).ready(function() {
"use strict";
if (window.localStorage.checkBoxValidation && window.localStorage.checkBoxValidation !== '') {
$('#rememberMe').attr('checked', 'checked');
$('#username').val(window.localStorage.userName);
$('#password').val(window.localStorage.passWord);
document.EventConfirmRedirection.submit();
} else {
$('#rememberMe').removeAttr('checked');
$('#username').val('');
$('#password').val('');
}
$('#rememberMe').click(function() {
if ($('#rememberMe').is(':checked')) {
// save username and password
window.localStorage.userName = $('#username').val();
window.localStorage.passWord = $('#password').val();
window.localStorage.checkBoxValidation = $('#rememberMe').val();
} else {
window.localStorage.userName = '';
window.localStorage.passWord = '';
window.localStorage.checkBoxValidation = '';
}
});
});
AJAX
$(document).ready(function() {
"use strict";
$("#submit").click( function(e) {
e.preventDefault();
if( $("#username").val() === "" || $("#password").val() === "" )
{
$("div#error").html("Both username and password are required");
} else {
$.post( $("#myForm").attr("action"),
$("#myForm :input").serializeArray(),
function(data) {
$("div#error").html(data);
});
$("#myForm").submit( function() {
return false;
});
}
});
});
"submit is not a function" means that you named your submit button or some other element submit. Rename the button to btnSubmit and your call will magically work. Any of the form element name and id should not be submit, otherwise form.submit will refer to that element rather than submit function.
When you name the button submit, you override the submit() function on the form.
So changing the div/submit like this will work for you
<div class="login"><input type="submit" value="LOGIN" name="btnSubmit" data-theme="e" id="btnSubmit"></div>
And if you don't want to change the button name then you might call the submit function natively aswell, which looks a bit dirty..
document.EventConfirmRedirection.prototype.submit.call(document.EventConfirmRedirection);
//or
document.EventConfirmRedirection.prototype.submit.call($('#myForm')[0]);

Categories

Resources