Submit a form with enter button - javascript

With this code, i only can send the form if i press the button.
How can i send it also, if i press the enter button when the cursor is in the keyword text input? For example, i type in what im searching for, and press enter.
$(document).ready(function(e) {
$('#preloader').hide();
$('#searchButton').click(function(e) {
e.preventDefault();
var keyword = $("input[name='keyword']").val();
var kereses_helye = $("select[name='kereses_helye']").val();
var kereses_rendezes = $("select[name='kereses_rendezes']").val();
var kereses_sorrend = $("select[name='kereses_sorrend']").val();
if (keyword != "") {
$.ajax({
type: 'POST',
url: 'files/get_keszlet.php',
data: {
keyword: keyword,
kereses_helye: kereses_helye,
kereses_rendezes: kereses_rendezes,
kereses_sorrend: kereses_sorrend
},
dataType: "html",
cache: false,
beforeSend: function() {
$('#preloader').show();
},
success: function(data) {
var result = $.trim(data);
$('#result').html(result);
},
complete: function() {
$('#preloader').hide();
}
});
} else {
alert("Nem adta meg, hogy mit keres.");
}
});
});

Use keypress event and check for correct key
const input = document.querySelector('your-input-field');
input.addEventListener('keypress', event => {
if (event.key === 'Enter') {
// your code goes here
}
});

As you said, the cursor would be in any input,
You can do with this jquery code:
$('.input').keypress(function (e) {
if (e.which == 13) { // 13 is the ASCII number of Enter key.
sendRequest(); // Calling your function if Enter is pressed.
return false;
}
});

Write you logic in different function and call that function on click event an on keypress event.
$(document).ready(function(e) {
$('#preloader').hide();
$('#searchButton').click(function(e) {
sendRequest();
});
$("input[name='keyword']").keypress(function(e) {
if (e.which == 13) sendRequest();
});
function sendRequest() {
e.preventDefault();
var keyword = $("input[name='keyword']").val();
var kereses_helye = $("select[name='kereses_helye']").val();
var kereses_rendezes = $("select[name='kereses_rendezes']").val();
var kereses_sorrend = $("select[name='kereses_sorrend']").val();
if (keyword != "") {
$.ajax({
type: 'POST',
url: 'files/get_keszlet.php',
data: {
keyword: keyword,
kereses_helye: kereses_helye,
kereses_rendezes: kereses_rendezes,
kereses_sorrend: kereses_sorrend
},
dataType: "html",
cache: false,
beforeSend: function() {
$('#preloader').show();
},
success: function(data) {
var result = $.trim(data);
$('#result').html(result);
},
complete: function() {
$('#preloader').hide();
}
});
} else {
alert("Nem adta meg, hogy mit keres.");
}
}
});

You have to use submit event in jquery :
<form id="search-form">
<input type="text" name="keyword"/>
<button type="submit">Search</button>
</form>
$('#search-form').submit(function(){
// Your code here
});

Related

How to have another "alert" for every form in ajax requesting?

let getLoginPassSystem = function (getPassForgotSystem, getLoginCheckSystem) {
$(document).ready(function () {
$('#login,#lostpasswordform,#register').submit(function (e) {
e.preventDefault();
$.ajax({
type: "POST",
url: 'http://www.virtuelles-museum.com.udev/spielelogin/logsystem.php',
data: $(this).serialize(),
success: function (response) {
var data = JSON.parse(response);
if (data.success == "accepted") {
document.getElementById('inner').innerHTML = 'Herzlich Willkommen';
// location.href = 'index.php';
} else {
alert('Ungültige Email oder Password!');
}
}
});
});
})
}
Well, I want to have for every form(#login,#lostpasswordform,#register) an different "alert". Is it actually possible?
You can save an alert massage in each div tag as data attribute. For example:
<div id="login" data-msg="message1"></div>
<div id="lostpasswordform" data-msg="message2"></div>
<div id="register" data-msg="message3"></div>
// then you can invoke them like this
let getLoginPassSystem = function (getPassForgotSystem, getLoginCheckSystem) {
$(document).ready(function () {
$('#login,#lostpasswordform,#register').submit(function (e) {
e.preventDefault();
let current_form = $(this);
$.ajax({
type: "POST",
url: 'http://www.virtuelles-museum.com.udev/spielelogin/logsystem.php',
data: $(this).serialize(),
success: function (response) {
var data = JSON.parse(response);
if (data.success == "accepted") {
document.getElementById('inner').innerHTML = 'Herzlich Willkommen';
// location.href = 'index.php';
} else {
alert(current_form.attr('data-msg'));
}
}
});
});
})
}
It seems like you can simply check the e.target - it will be different for every form.
You can get more information about Event.target here: https://developer.mozilla.org/en-US/docs/Web/API/Event/target

Ajax call is not returning to success from controller

In the code below, I am doing an ajax call and calling a controller '/feedback', and from controller, I am returning a String value as "Y". But everytime, it's redirecting me to error Jsp.
Any help would be appreciated.
Ajax call:
document.getElementById("modal_feedback").addEventListener("submit", function(e) {
var form = this;
var name = form.name.value;
var rating = form.overall.value;
var msg = form.message.value;
if(name == "") {
alert("Please enter your Name");
form.name.focus();
e.preventDefault();
} else if(rating == "") {
alert("Please select a rating");
form.overall[0].focus();
e.preventDefault();
} else if(msg == "") {
alert("Please enter your comment in the Message box");
form.message.focus();
e.preventDefault();
}
$.ajax({
type: "POST",
url: "feedbackData.htm?ratingId="+rating+"&msg="+msg,
success: function(response) {
console.debug(response);
if(response == 'Y'){
$('#contact_form').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/icon_pdf.png' />");
});
}
}
});
return false;
}, false);
Controller code:
#RequestMapping(value = "/feedbackData")
public #ResponseBody String getFeedbackData(String ratingId, String msg) throws UnsupportedEncodingException{
System.out.println("Inside FeedbackController..");
try{
feedbackService.updateFeedback(ratingId,msg);
return "Y";
}catch(Exception e)
{
logger.error("Exception in Login :" + e);
return "N";
}
}
}
I have tried the datatype:"html" which start returning the response and not taking to the error.jsp. Updated JS code as below
document.getElementById("modal_feedback").addEventListener("submit", function(e) {
e.preventDefault();
var form = this;
var name = form.name.value;
var rating = form.overall.value;
var msg = form.message.value;
if(name == "") {
alert("Please enter your Name");
form.name.focus();
e.preventDefault();
} else if(rating == "") {
alert("Please select a rating");
form.overall[0].focus();
e.preventDefault();
} else if(msg == "") {
alert("Please enter your comment in the Message box");
form.message.focus();
e.preventDefault();
}
$.ajax({
type: "POST",
url: "feedbackData.htm?ratingId="+rating+"&msg="+msg,
async : false,
dataType: "html",
success: function(response) {
console.debug(response);
if(response == 'Y'){
$('#modal_window').html("<div id='message'></div>");
$('#message').html("<h2>Feedback Form Submitted!</h2>").append("<p>We will be in touch soon.</p>")
}
},
error : function(e) {
alert('Error: ' + e);
}
});
return false;
});
Try updating your ajax code by adding dataType : "html" so that it accepts response as string like below:
$.ajax({
type: "GET",
url: "feedbackData.htm?ratingId="+rating+"&msg="+msg,
dataType: "html",
success: function(response) {
console.debug(response);
if(response == 'Y'){
$('#contact_form').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/icon_pdf.png' />");
});
}
}
});
Also read jquery ajax official documentation for more clarification here

Jquery popup modal, how to call from a js function

After I submit form, below line opens a popup modal.
<input class="js__p_start" type="submit" value="submit" name="submit"/>
I want to open this popup from a JS function where I will check if form field is not empty then only call this popup modal, otherwise will give alert to fill the form field.
Any way I call call this popup using that class from another JS function.
In case you need source code, see the source code of http://www.hunt4flat.com
Here is my code:
<script>
$(document).ready(function(){
$("#hidden_form").submit(function(){
var mobile = $("#mobile").val();
var name = $("#name").val();
var dataString = 'mobile='+ mobile + '&name='+ name;
if(name=='')
{
alert("Please Enter your name");
}
else
{
$.ajax({
type: "POST",
url: "ritz.php",
data: dataString,
cache: false,
success: function(result){
alert(result);
//I Want to call Popup here, so that popup will appear only after user properly entereed form fields
}
});
}
return false;
});
});
</script>
How to do it?
JS file is:
(function($) {
$.fn.simplePopup = function(event) {
var simplePopup = {
settings: {
hashtag: "#/",
url: "popup",
event: event || "click"
},
initialize: function(link) {
var popup = $(".js__popup");
var body = $(".js__p_body");
var close = $(".js__p_close");
var routePopup = simplePopup.settings.hashtag + simplePopup.settings.url;
var cssClasses = link[0].className;
if (cssClasses.indexOf(" ") >= 0) {
cssClasses = cssClasses.split(" ");
for (key in cssClasses) {
if (cssClasses[key].indexOf("js__p_") === 0) {
cssClasses = cssClasses[key]
}
};
}
var name = cssClasses.replace("js__p_", "");
// We redefine the variables if there is an additional popap
if (name !== "start") {
name = name.replace("_start", "_popup");
popup = $(".js__" + name);
routePopup = simplePopup.settings.hashtag + name;
};
link.on(simplePopup.settings.event, function() {
simplePopup.show(popup, body, routePopup);
return false;
});
$(window).on("load", function() {
simplePopup.hash(popup, body, routePopup);
});
body.on("click", function() {
simplePopup.hide(popup, body);
});
close.on("click", function() {
simplePopup.hide(popup, body);
return false;
});
$(window).keyup(function(e) {
if (e.keyCode === 27) {
simplePopup.hide(popup, body);
}
});
},
centering: function(popup) {
var marginLeft = -popup.width()/2;
return popup.css("margin-left", marginLeft);
},
show: function(popup, body, routePopup) {
simplePopup.centering(popup);
body.removeClass("js__fadeout");
popup.removeClass("js__slide_top");
location.hash = routePopup;
document.getElementById("menu_but").style.visibility = "hidden";
document.getElementById("toTop").style.visibility = "hidden";
document.getElementById("cbp-spmenu-s1").style.visibility = "hidden";
},
hide: function(popup, body) {
popup.addClass("js__slide_top");
body.addClass("js__fadeout");
location.hash = simplePopup.settings.hashtag;
document.getElementById("menu_but").style.visibility = "visible";
document.getElementById("toTop").style.visibility = "visible";
document.getElementById("cbp-spmenu-s1").style.visibility = "visible";
},
hash: function(popup, body, routePopup) {
if (location.hash === routePopup) {
simplePopup.show(popup, body, routePopup);
}
}
};
return this.each(function() {
var link = $(this);
simplePopup.initialize(link);
});
};
})(jQuery);
Using my library:
$.ajax({
type: "POST",
url: "ritz.php",
data: dataString,
cache: false,
success: function(result){
alert(result);
//I Want to call Popup here, so that popup will appear only after user properly entereed form fields
var popup = new jPopup({
title: "<h2>Succes</h2>",
content: "<p>Form has been sent succesfully, results: "+result+"</p>",
buttons: [{
text: "Close"
}]
});
popup.open();
}
});
Library: https://github.com/seahorsepip/jPopup
You can do the same with a jquery ui dialog but jquery ui dialogs require too much js and aren't that great in my opinion :P

Submit form using AJAX and <a> tag

I've been trying to get this to work but unable to.
All my forms normally have submit input on them and I process AJAX submission like below;
<script>
$("input#submit").click(function () {
$("#login-form").submit(function (e) {
$('#loader').show();
// Client side validation
if ($("#email").val() == "" || $("#password").val() == "") {
$('#loader').hide();
fieldError();
} else {
var postData = $(this).serializeArray();
var formURL = $(this).attr("action");
$.ajax({
url: formURL,
type: "POST",
data: postData,
success: function (response) {
switch (response) {
case "Valid":
$('#loader').hide();
$('#login-form').trigger("reset");
window.location.href = "index.php";
break;
case "not eValid":
$('#loader').hide();
emailError();
break;
case "not Valid":
$('#loader').hide();
credError();
break;
}
}
});
}
e.preventDefault(); //STOP default action
e.unbind();
});
});
</script>
Now I want to achieve the same thing using an tag. Below is my code that doesn't work;
<script>
$("a.update").click(function () {
$("#address-form").submit(function (e) {
$('#loader').show();
// Client side validation
if ($("#addressLine1").val() == "" || $("#addressLine2").val() == "" || $("#addressLine3").val() == "") {
$('#loader').hide();
fieldError();
} else {
var postData = $(this).serializeArray();
var formURL = $(this).attr("action");
$.ajax({
url: formURL,
type: "POST",
data: postData,
success: function (response) {
switch (response) {
case "Valid":
$('#loader').hide();
$('#address-form').trigger("reset");
//window.location.href="index.php";
break;
case "not Valid":
$('#loader').hide();
credError();
break;
}
}
});
}
e.preventDefault(); //STOP default action
e.unbind();
});
});
</script>
No error provided in Chrome console.
Thanks for any help provided.
use document ready &
$("a.update").click(function (e) {
$('#loader').show();
// Client side validation
if ($("#addressLine1").val() == "" || $("#addressLine2").val() == "" || $("#addressLine3").val() == "") {
$('#loader').hide();
fieldError();
} else {
var postData = $("#address-form").serializeArray();
var formURL = $("#address-form").attr("action");
$.ajax({
url: formURL,
type: "POST",
data: postData,
success: function (response) {
switch (response) {
case "Valid":
$('#loader').hide();
$('#address-form').trigger("reset");
//window.location.href="index.php";
break;
case "not Valid":
$('#loader').hide();
credError();
break;
}
}
});
e.preventDefault(); //STOP default action
e.unbind();
});
Your logic is wrong:
$("a.update").click(function () {
$("#address-form").submit(function (e) {
$('#loader').show();
// Client side validation
// etc.
When the link is clicked, you bind the an action to the submit event to your form. That is not what you want; you probably want to trigger the submit action code when the link is clicked.
Apart from that you are not cancelling the default click action of the link so it will be followed.
You only need:
$("a.update").click(function (e) {
e.preventDefault();
$('#loader').show();
// Client side validation
// etc.
Edit: Good point by #Andreas, you need to address your form correctly in the modified code:
var postData = $("#address-form").serializeArray();
var formURL = $("#address-form").attr("action");

Can't set HTML using jQuery

For some reason, my script isn't writing out the text after I remove the textbox element. Am I incorrectly using the .html or is something else wrong?
$('.time').click(function () {
var valueOnClick = $(this).html();
$(this).empty();
$(this).append("<input type='text' class='input timebox' />");
$('.timebox').val(valueOnClick);
$('.timebox').focus();
$('.timebox').blur(function () {
var newValue = $(this).val();
var dataToPost = { timeValue: newValue };
$(this).remove('.timebox');
if (valueOnClick != newValue) {
$.ajax({
type: "POST",
url: "Test",
data: dataToPost,
success: function (msg) {
alert(msg);
$(this).html("88");
}
});
} else {
// there is no need to send
// an ajax call if the number
// did not change
alert("else");
$(this).html("88");
}
});
});
OK, thanks to the comments, I figured out I was referencing the wrong thing. The solution for me was to change the blur function as follows:
$('.timebox').blur(function () {
var newValue = $(this).val();
var dataToPost = { timeValue: newValue };
if (valueOnClick != newValue) {
$.ajax({
type: "POST",
url: "Test",
data: dataToPost,
success: function (msg) {
}
});
} else {
// there is no need to send
// an ajax call if the number
// did not change
}
$(this).parent().html("8");
$(this).remove('.timebox');
});
$(this) in your success handler is refering to msg, not $('.timebox') (or whatever element that you want to append the html to)
$(this) = '.timebox' element but you have removed it already,
$.ajax({
type: "POST",
url: "Test",
data: dataToPost,
success: function (msg) {
alert(msg);
$(this).html("88"); // This = msg
}
and
else {
// there is no need to send
// an ajax call if the number
// did not change
alert("else");
$(this).html("88"); // this = '.timebox' element but you have removed it already,
}
The value of this changes if you enter a function. So when u use this in the blur function handler, it actually points to '.timebox'
$('.time').click(function () {
var valueOnClick = $(this).html();
var $time=$(this);//If you want to access .time inside the function for blur
//Use $time instead of$(this)
$(this).empty();
$(this).append("<input type='text' class='input timebox' />");
$('.timebox').val(valueOnClick);
$('.timebox').focus();
$('.timebox').blur(function () {
var newValue = $(this).val();
var dataToPost = { timeValue: newValue };
$(this).remove(); //Since $(this) now refers to .timebox
if (valueOnClick != newValue) {
$.ajax({
type: "POST",
url: "Test",
data: dataToPost,
success: function (msg) {
alert(msg);
$(this).html("88");
}
});
} else {
// there is no need to send
// an ajax call if the number
// did not change
alert("else");
$(this).html("88");
}
});
});

Categories