I have a very simple AJAX form that asks for an email address and sends it to me after submitting.
How can I can I get the form to submit when hitting the enter key?
This runs when user clicks submit button:
<script type="text/javascript">
$(document).ready(function () {
$("#submit_btn").click(function () {
// Get input field values:
var user_email = $('input[name=email]').val();
// Simple validation at client's end
// We simply change border color to red if empty field using .css()
var proceed = true;
if (user_email === "") {
$('input[name=email]').css('border-color', 'red');
proceed = false;
}
// Everything looks good! Proceed...
if (proceed) {
/* Submit form via AJAX using jQuery. */
}
});
// Reset previously set border colors and hide all message on .keyup()
$("#contact_form input, #contact_form textarea").keyup(function () {
$("#contact_form input, #contact_form textarea").css('border-color', '');
$("#result").slideUp();
});
});
</script>
I know this question has been asked before -- I'm having trouble getting the keypress function to work.
I tried this to no avail:
$("#contact_form").keypress(function (e) {
if ((e.keyCode == 13) && (e.target.type != "textarea")) {
e.preventDefault();
// Get input field values
var user_email = $('input[name=email]').val();
// Simple validation at client's end
// We simply change border color to red if empty field using .css()
var proceed = true;
if (user_email === "") {
$('input[name=email]').css('border-color', 'red');
proceed = false;
}
// Everything looks good! Proceed...
if (proceed) {
/* Submit form via AJAX using jQuery. */
}
}
});
The form is #contact_form.
Any help would be would appreciated…
Just bind the submit event to your form, and then the enter key will also work:
$("#contact_form").submit(function (e) {
e.preventDefault();
// Get input field values
var user_email = $('input[name=email]').val();
// Simple validation at client's end
// We simply change border color to red if empty field using .css()
var proceed = true;
if (user_email === "") {
$('input[name=email]').css('border-color', 'red');
proceed = false;
}
if (proceed) {
// Insert the AJAX here.
}
});
And the code is here: http://jsfiddle.net/6TSWk/6/
add new class in every fieldbox or checkbox => class keypressbutton
then replace your code on keypress with this, below :
$(document).on("keypress",".keypressbutton",function(event) {
var keyCode = event.which || event.keyCode;
if (keyCode == 13) {
$("#submit_btn").click();
return false;
}
});
$("#myform").keypress(function(event){
if(event.keycode===13){ // enter key has code 13
//some ajax code code here
//alert("Enter key pressed");
}
});
You have two opening brackets in your if statement and miss a closing bracket. Also, I would change e.target.type. Try this:
$("#contact_form").keypress(function (e) {
if ((e.keyCode == 13) && ($('input[name="email"]').is(':focus'))) {
e.preventDefault();
//get input field values
var user_email = $('input[name=email]').val();
//simple validation at client's end
//we simply change border color to red if empty field using .css()
var proceed = true;
if (user_email === "") {
$('input[name=email]').css('border-color', 'red');
proceed = false;
}
}
});
Instead of using button on click function you can use submit button.
Load the validate.js file
function validateEmail(email)
{
var reg = /^\w+([-+.']\w+)*#\w+([-.]\w+)*\.\w+([-.]\w+)*$/
if (reg.test(email))
{
return true; }
else{
return false;
}
}
$("#test-form").validate({
submitHandler: function(form) {
//form.submit();
var email=$("#email").val();
if(email=='' )
{
// Here you can type your own error message
$('#valid').css("display","none");
$('#empty').css("display","block");
return false;
}
if (!(validateEmail(email))) {
$('#empty').css("display","none");
$('#valid').css("display","block");
return false;
}
else {
$.ajax({
url: "signup.php",
type: form.method,
data: $(form).serialize(),
success: function(response) {
}
});
}
}
});
});
Simple way is this:
In HTML codes:
<form action="POST" onsubmit="ajax_submit();return false;">
<b>First Name:</b> <input type="text" name="firstname" id="firstname">
<br>
<b>Last Name:</b> <input type="text" name="lastname" id="lastname">
<br>
<input type="submit" name="send" onclick="ajax_submit();">
</form>
In Js codes:
function ajax_submit()
{
$.ajax({
url: "submit.php",
type: "POST",
data: {
firstname: $("#firstname").val(),
lastname: $("#lastname").val()
},
dataType: "JSON",
success: function (jsonStr) {
// another codes when result is success
}
});
}
Related
i have a live chat messaging system whenever user press enter button it refreshes the page i have tried using prevent default code also but did not worked for me.... here is the code and if there is any problem in the below code please let me know as i'm totally new to website programming
jQuery(document).ready(function() {
jQuery('.btn-success').click(function() {
var form_name = jQuery(this).attr('title');
var obj = jQuery(this);
jQuery(".ajax_indi").show();
switch (form_name) {
case "npost":
var message = jQuery("#message").val();
break;
default:
alert("something went wrong!");
}
if((jQuery(message) == ''))
{
alert("Message Cannot be Empty");
jQuery(".ajax_indi").hide();
return false;
} else {
jQuery(this).attr("disabled", "disabled");
jQuery(this).prop('value', 'Loading...');
jQuery(this).css('cursor', 'default');
}
var str = jQuery("#"+form_name).serialize();
jQuery.ajax({
type: "POST",
url: "chat.php",
data: str,
cache: false,
success: function(html){
jQuery('#chat1').append(html);
obj.attr("disabled", false);
obj.prop('value', 'Post');
obj.css('cursor', 'pointer');
jQuery(".ajax_indi").hide();
document.getElementById(form_name).reset();
}
});
});
});
Edited part
<form id="npost" name="npost">
<input class="form-control" placeholder="Type your message here..."
type="text" name="message">
<input type="hidden" name="id" value="1">
<span class="input-group-btn">
<button type="button" class="btn btn-success" title="npost" >Send</button>
if you want to prevent from submitting the form you can use return false if you want to stop executing the function and stop submitting it
You need to use preventDefault in order to stop form submission on clicking enter because by default form gets submitted when anyone presses enter. So use preventDefault like this:
<script type="text/javascript" >
jQuery(document).ready(function(){
jQuery('.btn-success').click(function(e){ // added e
e.preventDefault(); // added this line
var form_name = jQuery(this).attr('title');
var obj = jQuery(this);
jQuery(".ajax_indi").show();
var message = '';
switch (form_name)
{
case "npost":
var message = jQuery("#message").val();
break;
default:
alert("something went wrong!");
}
if((jQuery(message) == ''))
{
alert("Message Cannot be Empty");
jQuery(".ajax_indi").hide();
return false;
} else {
jQuery(this).attr("disabled", "disabled");
jQuery(this).prop('value', 'Loading...');
jQuery(this).css('cursor', 'default');
}
var str = jQuery("#"+form_name).serialize();
jQuery.ajax({
type: "POST",
url: "chat.php",
data: str,
cache: false,
success: function(html){
jQuery('#chat1').append(html);
obj.attr("disabled", false);
obj.prop('value', 'Post');
obj.css('cursor', 'pointer');
jQuery(".ajax_indi").hide();
document.getElementById(form_name).reset();
}
});
});
});
</script>
Here You should not stop form default action you to prevent enter key default answer here is the code to prevent.
$('#npost').on('keyup keypress', function(e) {
if (e.which== 13) {
e.preventDefault();
return false;
}
});
I am working on discussion that works like a forum. There can be several posts and users are supposed to comment.
I have this html post comment form which repeats itself after every post
<form method="POST" action="/discussion/post-comment" id="post-comment-form" class="form-horizontal subcommentcofrm" role="form">
<div class = "form-group">
<div class = "col-sm-6">
<input type = "text" class = "form-control comment-yako" id = "comment-field" placeholder = "Type your comment here..." autocomplete="off">
</div>
</div>
</form>
And this is my JQuery code with ajax submission:
$("input.comment-yako").live('keypress', function(e) {
if ((e.which && e.which === 13) || (e.keyCode && e.keyCode === 13)) {
console.log('heey');
$(this).closest('form').submit(function(e){
console.log('heeeeeeey');
var data = $(this).serializeArray();
var url = $(this).attr("action");
$.ajax({
url: url,
type: 'POST',
cache: false,
data: data,
success: function(data) {
var item = $(data).hide().fadeIn(800);
$('.disc-content-reply').append(item);
},
error: function(e) {
alert(e);
}
});
e.preventDefault();
});
$(this).closest(".comment-yako").val("");
return false;
} else {
return true;
}
});
Submission is supposed to take place when the user hits enter key.
My problem is, when I hit enter, the form does not submit. I do not know where the problem is; what am I doing wrong?
Any help will be much appreciated.
Thanks
You should send the AJAX request in the keypress handler itself, not in a submit handler that you bind after the keypress occurs. Most of the time it's wrong to bind one event handler inside another event handler; if you find yourself doing that, think very hard about whether it's really what you want to do.
In addition to changing that, I've converted the .live() call to .on(). I also changed from .serializeArray() to .serialize(), as this is the normal way to send form fields.
$(document).on('keypress', 'input.comment-yako', function(e) {
if ((e.which && e.which === 13) || (e.keyCode && e.keyCode === 13)) {
console.log('heey');
var form = $(this).closest('form');
var data = form.serialize();
var url = form.attr("action");
$.ajax({
url: url,
type: 'POST',
cache: false,
data: data,
success: function(data) {
var item = $(data).hide().fadeIn(800);
$('.disc-content-reply').append(item);
},
error: function(e) {
alert(e);
}
});
e.preventDefault();
$(this).val("");
return false;
} else {
return true;
}
});
I am working on search function which I did it well to get what result I want. I have a search text field which can allow user to key in the value and JavaScript will help me get the relevant data for the text field value. Now I want my text field can be function when I press on it using button "Enter". Once I press on "Enter" button, it will redirect me to a new page which shows all the relevant data of the keyword I key in in the text field.
This is my JavaScript and HTML code inside HTML page:
<script>
$(document).ready(function() {
// Icon Click Focus
$('div.icon').click(function(){
$('input#search').focus();
});
// Live Search
// On Search Submit and Get Results
function search() {
var query_value = $('input#search').val();
$('b#search-string').html(query_value);
if(query_value !== ''){
$.ajax({
type: "POST",
url: "search.php",
data: { query: query_value },
cache: false,
success: function(html){
$("ul#results").html(html);
}
});
}return false;
}
$("input#search").live("keyup", function(e) {
// Set Timeout
clearTimeout($.data(this, 'timer'));
// Set Search String
var search_string = $(this).val();
// Do Search
if (search_string == '') {
$("ul#results").fadeOut();
$('h4#results-text').fadeOut();
}else{
$("ul#results").fadeIn();
$('h4#results-text').fadeIn();
$(this).data('timer', setTimeout(search, 0));
};
});
});
</script>
SEARCH<input type="text" id="search" autocomplete="off">
<ul id="results" style="display:none"></ul>
After keyin value inside the text, JavaScript will call search.php to get all the relevant data. But I can't click on text field to show all value. Hope you guy can give me a solution to work on it. Thanks in advanced.
Try this and use jQuery 1.8 or minimum.
$("input#search").live("keyup", function(e)
if(e.which == 13) {
//perform your operations
}
});
You could make it a form so that it would submit when the user hits enter.
<form method="get" action="search page.php" onsubmit="return validate();">
SEARCH<input type="text" id="search" autocomplete="off">
<ul id="results" style="display:none"></ul>
</form>
<script type="text/JavaScript">
function validate() {
//If the form value is "" (nothing)
if (document.getElementById("search").value == "") {
return false; //Stop the form from submitting
}
return true;
}
</script>
I am working on a text field which is pressable with "enter" button but unfortunately it does not work. I am trying following code inside my project.
This is my JavaScript code:
<script>
$(document).ready(function() {
// Live Search
// On Search Submit and Get Results
function search() {
var query_value = $('input#search').val();
$('b#search-string').html(query_value);
if(query_value !== ''){
$.ajax({
type: "POST",
url: "search.php",
data: { query: query_value },
cache: false,
success: function(html){
$("ul#results").html(html);
}
});
}
return false;
}
$("input#search").live("keyup", function(e) {
var theSearch = $('#search');
// Set Timeout
clearTimeout($.data(this, 'timer'));
// Set Search String
var search_string = $(this).val();
// Do Search
if (search_string == '') {
$("ul#results").fadeOut();
$('h4#results-text').fadeOut();
}else{
$("ul#results").fadeIn();
$('h4#results-text').fadeIn();
$(this).data('timer', setTimeout(search, 0));
};
});
});
$("#search").on('keyup',function(e){
var text = document.getElementById("search").value;
if(text !== ""){
if (e.which == 13){
$("#btnSearch").click();
}
}
});
function doSomething(){
var text = document.getElementById("search").value;
window.location.assign("search.php?value = " + text);
}
});
</script>
This is my HTML code:
<input type="text" id="search">
<input type="button" id="btnSearch" onclick="doSomething();" />
use unique selector id
$("#search").on('keyup',function(e){
if (e.which == 13){
alert('abc');
}
});
demo jsfiddle
use input type selector
$('input[type=text]').each(function(i,e) {
$("#"+e.id).on('keyup',function(e){
if (e.which == 13){
alert('abc');
}
});
});
another demo
Place $("input[type=text]").on... inside $(document).ready and make sure you are using JQuery version before 1.7 If you wish to use live
change your html to
<form onsubmit="doSomething();" >
<input type="text" id="search">
<input type="submit" id="btnSearch" />
</form>
while using this you don't have to listen enter key event your doSomething() function will be called automatically on enter press in input field
DEMO
I have a form that submits shopping cart data to a payment gateway (WorldPay) payment processing page. I need to perform a couple of extra logic the moment the custom decides to proceed to the payment but before the form submission itself. Basically, I simply want to generate a unique reference to the order at the very last moment.
Here is the jQuery code for the submit event:
$(function(){
$('#checkout-form').submit(function(e){
var $form = $(this);
var $cartIdField = $('#cartId');
console.log($cartIdField.val());
if($cartIdField.val() == ''){
e.preventDefault();
$.ajax({
url: baseUrl + '/shop/ajax/retrieve-shopping-cart-reference/',
data: {}, type: 'post', dataType: 'json',
success: function(json){
if(json.error == 0){
$('#cartId').val(json.data.cart_reference_number);
$form.submit();
}else{
alert(json.message);
}
}
});
}else{
console.log('Submitting form...'); //Does not submit!
}
});
});
The problem is that during the second submit triggered within the success: clause, the form isn't submitted still. I am assuming event.preventDefault() persists beyond the current condition.
How can I get around this?
For performe the any operation before form submit i used the following menthod hope it wil help
$('#checkout-form').live("submit",function(event){
//handle Ajax request use variable response
var err =false;
var $form = $(this);
//alert($form);
var values = {};
$.each($form.serializeArray(), function(i, field) {
values[field.name] = field.value;
});
//here you get all the value access by its name [eg values.src_lname]
var $cartIdField = $('#cartId');
console.log($cartIdField.val());
if($cartIdField.val() == ''){
$.ajax({
// your code and condition if condition satisfy the return true
// else return false
// it submit your form
/*if(condition true)
{
var err =true;
}
else
{
var err = false;
}*/
})
}
else
{
return true;
}
if(err)
{
return false
}
else
{
return true;
}
})
e.preventDefault() remove default form submit attribute which can not be reverted if applied once.
Use below code instead to prevent a form before submitting. This can be reverted.
$('#formId').attr('onsubmit', 'return false;');
And below code to restore submit attribute.
$('#formId').attr('onsubmit', 'return true;');
Only call e.preventDefault() when you really need to:
if(not_finished_yet) {
e.preventDefault();
}