Use Javascript when pressing enter - javascript

I want to call a function when I press enter in the input field. The problem is, that it just reloads the page at the moment, and doesn't call the JavaScript. The JavaScript works without any problems, when I'm pressin the button. Now I want to have the same result, when I press enter.
This is my form
<form onSubmit="changeView()">
<input type="text" value="London" name="region" id="region">
<input type="button" onClick="changeView()" name="mySubmit" value="Search" >
</form>
I also tried to put this into the text field onKeydown="Javascript: if (event.keyCode==13) changeView();
But it didn't really help.
This is my JavaScript function
function changeView(){
var region = document.getElementById('region').value;
$.ajax({
type: 'GET',
url: 'webservice.php',
data: {region: region},
success: function(response, textStatus, XMLHttpRequest) {
alert("SUCCESS");
map.panTo(new L.LatLng(response[0].lat,response[0].lon));
}
});
return false;
}

HTML:
<form action="webservice.php" method="post">
<input type="text" value="London" name="region" id="region">
<input type="submit" name="mySubmit" value="Search" >
</form>
Javascript:
$('#region').on('keydown', function(e) {
if (e.which === 13) {
$(this).parent('form').submit();
}
});
$('.form').on('submit', function(e) {
var self = $(this);
$.ajax({
type: self.attr('method') ,
url: self.attr('action'),
data: {region: $('#region').val()},
success: function(response, textStatus, XMLHttpRequest) {
alert("SUCCESS");
map.panTo(new L.LatLng(response[0].lat,response[0].lon));
}
});
e.PreventDefault();
return false;
});

it looks like you're using jQuery, have you thought about just biding an event to the text box
something like this
$(document).ready(function(){ // binds when the document has finished loading
$("#region").on('keypress', function(e){
if (e.which === 13){ // enter key
changeView();
}
});
});

Related

Ajax in django form

My Ajax request works correctly when I use change and the input is checkbox, but my Ajax request does not work when use input type submit !!
I want my type in the input submit and when I do this the Ajax request will not work and the page will reload.
$(document).on('change','.filter-form',function(event){
event.preventDefault();
$.ajax({
type:'GET',
url:'filter/',
data : $(this).serialize(),
dataType: 'json',
success: function (data) {
$('#product-main').html(data['form']);
},
error: function (data) {
alert("error" + data);
}
});
});
my form :
<form action="" class="filter-form">
<input type="submit" name="price" value="new">
<input type="submit" name="discount" value="discount">
<input type="submit" name="old" value="old">
</form>
I don't think submit buttons trigger the change event, so you'll have to listen for something else, also .serialize() do not give you the name/value pair of submit buttons.
Use the click event on the buttons and use the element properties to get the data to post.
$(document).on('click','.filter-form input[type=submit]',function(event){
event.preventDefault();
$.ajax({
type:'GET',
url:'filter/',
data : {[this.name]: this.value}
dataType: 'json',
success: function (data) {
$('#product-main').html(data['form']);
},
error: function (data) {
alert("error" + data);
}
});
});
First added a clicked property to the identify which submit is clicked. Then used the clicked property to get the value & name of the submit to pass in form submit event handler.
$(document).ready(function(){
// To identify which submit is clicked.
$("form.filter-form input[type=submit]").click(function() {
$("input[type=submit]", $(this).parents("form")).removeAttr("clicked");
$(this).attr("clicked", "true");
});
// Form submit event handler
$("form.filter-form").submit(function(event) {
event.preventDefault();
$clickedInput = $("input[type=submit][clicked=true]");
dataString = {[$clickedInput.prop('name')]: $clickedInput.val()};
console.log('dataString', dataString);
$.ajax({
type:'GET',
url:'filter/',
data : dataString,
dataType: 'json',
success: function (data) {
$('#product-main').html(data['form']);
},
error: function (data) {
console.log("error" + data);
}
});
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<form class="filter-form">
<input type="submit" name="price" value="new">
<input type="submit" name="discount" value="discount">
<input type="submit" name="old" value="old">
</form>

Why does Ajax form submit twice?

Why does the below script cause the form to submit twice? I can't figure this out, even after trying other solutions posted around the internet. Submitting twice is causing duplicate entries in the database. Thank you in advance for looking into this!
<script type="text/javascript">
$(document).ready(function(){
$('#form-error').hide();
$("#form-submit").click(function(){
$("#form").submit();
});
});
$('#form').submit(function(e) {
register();
e.preventDefault();
});
function register()
{
jQuery.ajax({
method: 'POST',
url: 'actions/add.php',
data: $('#form').serialize(),
dataType:'json',
success: function(msg){
if(parseInt(msg.status)==1)
{
window.location=msg.txt;
}
else if(parseInt(msg.status)==0)
{
error(1,msg.txt);
}
}
});
}
function hideshow(el,act)
{
if(act)
{
$('#'+el).hide(0).slideDown(500, 'linear');
}
else $('#'+el).hide();
}
function error(act,txt)
{
if(txt)
{
$('#form-error').html(txt);
}
$('#form-error').hide(0).slideDown(500, 'linear');
}
</script>
HTML Form:
<form id="form">
<p>First Name:</p>
<input type="text" name="firstname" />
<p>Last Name:</p>
<input type="text" name="lastname" />
<p>E-Mail Address:</p>
<input type="text" name="emailaddress" />
<p>Sequence Assignment:</p>
<select name="sequence">
<option value="1">Default Sequence</option>
</select>
<button id="form-submit">Add User</button>
<p id="form-error"></p>
</form>
There are duplicated event listeners for the submit event:
1. When submit button clicked:
$("#form-submit").click(function(){
$("#form").submit();
});
2. When form is submitted:
$('#form').submit(function(e) {
register();
e.preventDefault();
});
You need only one of them.
Change your code like:
<script type="text/javascript">
$(document).ready(function(){
$('#form-error').hide();
$('#form').submit(function(e) {
register();
e.preventDefault();
});
});
function register()
{
.
.
.
I had a similar issue to this. If you just single click on the button does it enter duplicate data?
The way I got around it is once the click happened I disabled the button until after the Ajax call.
function register()
{
//disable button
jQuery.ajax({
method: 'POST',
url: 'actions/add.php',
data: $('#form').serialize(),
dataType:'json',
success: function(msg){
if(parseInt(msg.status)==1)
{
window.location=msg.txt;
}
else if(parseInt(msg.status)==0)
{
error(1,msg.txt);
}
}
});
//Enable Button
}
Another option would be to do some checks in the php code that submits it to the database to see if that data already exists.

How to clear all inputs after form submission

I want to clear all inputs value whenever result succeed.
I have tried unbind from Jquery but doesn't get any result
so any suggestion would be great
<html>
<head>
<script src="http://ajax.aspnetcdn.com/ajax/jQuery/jquery-2.1.1.min.js"></script>
</head>
<body>
<div id="Result"></div>
<form id="Form" action="File.php" autocomplete="off">
<input type="text" name="Name" />
<br/>
<input type="text" name="Pass" />
<br/>
<input type="button" id="Submit" value="Run Code" />
</form>
<script>
$(document).ready(function()
{
$("#Submit").click(function()
{
$("#Form").submit(function(e)
{
$.ajax(
{
url: $(this).attr("action"),
type: "POST",
data: $(this).serializeArray(),
success: function(data, textStatus, jqXHR)
{
$("#Result").html(data);
}
});
e.preventDefault();
});
$("#Form").submit();
});
});
</script>
</body>
</html>
please feel free to ask for more details
You can clear all inputs using
$("input[type='text']").val('');
You are binding an event handler inside another event handler. Each time the button is clicked, a new handler is attached to the form. So, after n number of clicks, you'll be sending n number of ajax requests, as you can see here
Ideally, your code should be
$(document).ready(function () {
$("#Submit").click(function () {
$("#Form").submit();
});
$("#Form").submit(function (e) {
e.preventDefault();
$.ajax({
url: $(this).attr("action"),
type: "POST",
data: $(this).serializeArray(),
success: function (data, textStatus, jqXHR) {
$("input[type='text']").val(''); // reset the input values
$("#Result").html(data);
}
});
});
});
Demo.
Side note: You can simply use a submit button instead of triggering the form submission manually like this
Here you go:
$(document).find('input').each(function(){
$(this).val('');
});
More info on: http://api.jquery.com/val/

Submit form when enter key is pressed

I currently have a live chat room up and running and just asked some users what I can do to make the chat room even better. One thing that was asked multiple times was this...
"Can you please add a feature where pressing the enter button will send my message instead of adding a new line in the text box?"
I tried to apply some jQuery from a different post on StackOverflow but couldn't get it to work. Here is my current code...
jQuery:
<!-- jQuery for submitting form -->
<script>
var msgForm = false;
$(function () {
$('.expand').keyup(function(event) {
if (event.keyCode == 13) {
this.form.submit();
msgForm = true;
return true;
}
});
if( msgForm = true ) {
$('#formSend').on('submit', function (e) {
e.preventDefault();
var formData = $('form').serialize();
$('.expand').prop("disabled", true)
$.ajax({
type: 'post',
url: 'send.php',
data: formData,
success: function () {
$(".expand").val('');
$('.expand').prop("disabled", false)
}
});
});
}
});
</script>
Here ^^ an Ajax request is made to send the message so no page refresh is involved like a usual form.
Here is the HTML markup for the form if needed...
<form action="send.php" method="post" name="formSend" id="formSend" />
<textarea id="styled" class="expand" name="msg" placeholder="Your Message Here" onfocus:"setbg(\'#e5fff3\');"required></textarea>
<input type="submit" name="submit" value="Send" class="send" />
</form>
I just tested this in a jsfiddle and it works fine.
html:
<form>
<textarea></textarea>
<input type="submit" value="Submit"/>
</form>
javascript:
$("textarea").keyup(function(event){
if(event.keyCode == 13){
$("form").submit();
}
});
$("form").on('submit', function(e){
e.preventDefault();
alert('abcde');
});
Demo
Why not just put them in one action. No need to separate. Like this:
<form action="send.php" method="post" name="formSend" id="formSend" />
<textarea id="styled" class="expand" name="msg" placeholder="Your Message Here" onfocus:"setbg(\'#e5fff3\');" required></textarea> <br/>
<input type="submit" name="submit" value="Send" class="send" />
</form>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function(){
$('.expand').keyup(function(event) {
if(event.keyCode == 13) {
var formData = $('#formSend').serialize();
$(this).prop('disabled', true);
console.log(formData);
$.ajax({
type: 'POST',
url: 'send.php',
// url: document.URL,
data: formData,
success: function(response) {
$('.expand').attr('placeholder', 'Sending Message...');
setTimeout(function(){
$('.expand').attr('placeholder', 'Your Message Here').prop('disabled', false);
// sample delay
}, 1000);
$(".expand").val('');
}
});
}
});
});
</script>
Why not trigger an event click if the user press the enter key
$('selector').on('keyup', function(e) {
if(e.which == 13) {
$('button_selector').trigger('click');
}
}
$('button_selector').on('click', function() {
//do ajax request here.....
});
// get from my code hope it hepls....

clear form values after submission ajax

I am using the following script for validate my contact form.
//submission scripts
$('.contactForm').submit( function(){
//statements to validate the form
var filter = /^([a-zA-Z0-9_\.\-])+\#(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+$/;
var email = document.getElementById('e-mail');
if (!filter.test(email.value)) {
$('.email-missing').show();
} else {$('.email-missing').hide();}
if (document.cform.name.value == "") {
$('.name-missing').show();
} else {$('.name-missing').hide();}
if (document.cform.phone.value == "") {
$('.phone-missing').show();
}
else if(isNaN(document.cform.phone.value)){
$('.phone-missing').show();
}
else {$('.phone-missing').hide();}
if (document.cform.message.value == "") {
$('.message-missing').show();
} else {$('.message-missing').hide();}
if ((document.cform.name.value == "") || (!filter.test(email.value)) || (document.cform.message.value == "") || isNaN(document.cform.phone.value)){
return false;
}
if ((document.cform.name.value != "") && (filter.test(email.value)) && (document.cform.message.value != "")) {
//hide the form
//$('.contactForm').hide();
//show the loading bar
$('.loader').append($('.bar'));
$('.bar').css({display:'block'});
/*document.cform.name.value = '';
document.cform.e-mail.value = '';
document.cform.phone.value = '';
document.cform.message.value = '';*/
//send the ajax request
$.post('mail.php',{name:$('#name').val(),
email:$('#e-mail').val(),
phone:$('#phone').val(),
message:$('#message').val()},
//return the data
function(data){
//hide the graphic
$('.bar').css({display:'none'});
$('.loader').append(data);
});
//waits 2000, then closes the form and fades out
//setTimeout('$("#backgroundPopup").fadeOut("slow"); $("#contactForm").slideUp("slow")', 2000);
//stay on the page
return false;
}
});
This is my form
<form action="mail.php" class="contactForm" id="cform" name="cform" method="post">
<input id="name" type="text" value="" name="name" />
<br />
<span class="name-missing">Please enter your name</span>
<input id="e-mail" type="text" value="" name="email" />
<br />
<span class="email-missing">Please enter a valid e-mail</span>
<input id="phone" type="text" value="" name="phone" />
<br />
<span class="phone-missing">Please enter a valid phone number</span>
<textarea id="message" rows="" cols="" name="message"></textarea>
<br />
<span class="message-missing">Please enter message</span>
<input class="submit" type="submit" name="submit" value="Submit Form" />
</form>
I need to clear the form field values after submitting successfully. How can i do this?
$("#cform")[0].reset();
or in plain javascript:
document.getElementById("cform").reset();
You can do this inside your $.post calls success callback like this
$.post('mail.php',{name:$('#name').val(),
email:$('#e-mail').val(),
phone:$('#phone').val(),
message:$('#message').val()},
//return the data
function(data){
//hide the graphic
$('.bar').css({display:'none'});
$('.loader').append(data);
//clear fields
$('input[type="text"],textarea').val('');
});
use this:
$('form.contactForm input[type="text"],texatrea, select').val('');
or if you have a reference to the form with this:
$('input[type="text"],texatrea, select', this).val('');
:input === <input> + <select>s + <textarea>s
$('.contactForm').submit(function(){
var that = this;
//...more form stuff...
$.post('mail.php',{...params...},function(data){
//...more success stuff...
that.reset();
});
});
Simply
$('#cform')[0].reset();
it works: call this function after ajax success and send your form id as it's paramete. something like this:
This function clear all input fields value including button, submit, reset, hidden fields
function resetForm(formid) {
$('#' + formid + ' :input').each(function(){
$(this).val('').attr('checked',false).attr('selected',false);
});
}
* This function clears all input fields value except button, submit, reset, hidden fields
* */
function resetForm(formid) {
$(':input','#'+formid) .not(':button, :submit, :reset, :hidden') .val('')
.removeAttr('checked') .removeAttr('selected');
}
example:
<script>
(function($){
function processForm( e ){
$.ajax({
url: 'insert.php',
dataType: 'text',
type: 'post',
contentType: 'application/x-www-form-urlencoded',
data: $(this).serialize(),
success: function( data, textStatus, jQxhr ){
$('#alertt').fadeIn(2000);
$('#alertt').html( data );
$('#alertt').fadeOut(3000);
resetForm('userInf');
},
error: function( jqXhr, textStatus, errorThrown ){
console.log( errorThrown );
}
});
e.preventDefault();
}
$('#userInf').submit( processForm );
})(jQuery);
function resetForm(formid) {
$(':input','#'+formid) .not(':button, :submit, :reset, :hidden') .val('')
.removeAttr('checked') .removeAttr('selected');
}
</script>
$.post('mail.php',{name:$('#name').val(),
email:$('#e-mail').val(),
phone:$('#phone').val(),
message:$('#message').val()},
//return the data
function(data){
if(data==<when do you want to clear the form>){
$('#<form Id>').find(':input').each(function() {
switch(this.type) {
case 'password':
case 'select-multiple':
case 'select-one':
case 'text':
case 'textarea':
$(this).val('');
break;
case 'checkbox':
case 'radio':
this.checked = false;
}
});
}
});
http://www.electrictoolbox.com/jquery-clear-form/
Set id in form when you submitting form
<form action="" id="cform">
<input type="submit" name="">
</form>
set in jquery
document.getElementById("cform").reset();
$('#formid).reset();
or
document.getElementById('formid').reset();
Vanilla!
I know this post is quite old.
Since OP is using jquery ajax this code will be needed.
But for the ones looking for vanilla.
...
// Send the value
xhttp.send(params);
// Clear the input after submission
document.getElementById('cform').reset();
}
just use form tag alone, like this :
$.ajax({
type: "POST",
url: "/demo",
data: dataString,
success: function () {
$("form")[0].reset();
$("#test").html("<div id='message'></div>");
$("#message")
.html("<h2>Contact Form Submitted!</h2>")
.append("<p>We will be in touch soon.</p>")
.hide()
.fadeIn(1500, function () {
$("#message").append(
"<img id='checkmark' src='images/check.png' />"
);
});
}
});
e.preventDefault();
});
Using ajax reset() method you can clear the form after submit
example from your script above:
const form = document.getElementById(cform).reset();
If you are using a form tag in your form. Then
$("#cform")[0].reset();
This code will work perfectly but in case you are not using any form tag then you can try to set an empty value to each input field Like this.
$('input[type="text"],textarea').val('');

Categories