I've below code in JS file:
$(document).ready(function() {
$("#key_verify").click(function () {
$("#errrmsg").html("<img src=\"/images/shim.gif\"/>");
if($.trim($("#key").val()).length != 0){
$.ajax({
type : "POST",
cache : false,
async : true,
url : "/issuekey?key="+$("#key").val(),
success : function(data) {
var json_obj = $.parseJSON(data);
if(json_obj === undefined || json_obj == null){
}else{
if(json_obj.result == "true"){
top.location.href="/register"
}else{
$("#errrmsg").html(invalid_key);
}
}
},
error : function(data) {
$("#errrmsg").html(invalid_product_key);
}
});
}
});
}
How can I invoke above code in below lines so that when user hits enter key, it should make a call on enter key as well??
$("#key_verify").keypress(function(e) {
if(e.which == 13){
??????
}
});
Thanks!
Make the function you are passing to the click handler into a named function like so:
var verify = function(e) {
// your current anonymous function
$("#errrmsg").html("<img src=\"/images/shim.gif\"/>");
// ... the rest of your function
}
Then pass it as an argument into your event handlers:
$("#key_verify").click( verify );
$("#key_verify").keypress(function(e) {
if(e.which == 13){
verify( e );
}
});
Related
I have the following Javascript code in my web page that SHOULD ensure data validation and then (if the form is valid) submit the data to an AJAX call:
<script>
$(document).ready(function () {
$("#frmInfo").submit(function (event) {
event.preventDefault();
var forms = document.getElementsByName('frmInfo');
var validation = Array.prototype.filter.call(forms, function (form) {
if (form.checkValidity() == false) {
form.classList.add('was-validated');
alert('Hit invalid user input');
return false;
}
else {
alert('Everything is valid');
form.classList.add('was-validated');
}
});
var obj = Object.fromEntries(new FormData(event.target));
if (obj.Is_Body_HTML == 1)
obj.Is_Body_HTML = true;
else
obj.Is_Body_HTML = false;
if (obj.Is_Active == 1)
obj.Is_Active = true;
else
obj.Is_Active = false;
setDisabled();
var json = JSON.stringify(obj);
alert(json);
var request = $.ajax({
url: "../handlers/test.ashx",
method: "POST",
data: json,
dataType: "json"
});
request.done(function (msg) {
if (msg.Success == false) {
$('#infoErr').html('Should not have reached this!');
$('#toastInfoFail').toast('show');
}
else {
localStorage.setItem('cust_no', msg.ID);
document.location.href = 'getaddress.aspx';
}
});
request.fail(function (jqXHR, textStatus) {
$('#infoErr').html('Unable to contact server to process change request. Please try again later.');
$('#toastInfoFail').toast('show');
});
request.always(function (jqXHROrData, textStatus, jqXHROrErrorThrown) {
setEnabled();
});
});
$('#BestTelephone').inputmask("999-999-9999");
$('#FirstName').focus();
});
function setDisabled() {
$('#btnNext').prop('disabled', true);
}
function setEnabled() {
$('#btnNext').prop('disabled', false);
}
</script>
The problem is, the validation works, but it doesn't. When the form fields are not valid, it hits this block:
if (form.checkValidity() == false) {
form.classList.add('was-validated');
alert('Hit invalid user input');
return false;
}
and the alert is displayed. The very next line should force the function to exit, stopping execution of any remaining code, but for some reason it doesn't. Instead, the remainder of the code executes as if the form is valid, and the alert for the AJAX failure pops up.
Why does the 'return false' not actually force the function to exit, and what am I missing here?
return false is a statement of the anonymous function function (form) {... which is called for each form element. The anonymous function function (event) {... doesn't have a return statement. The filter function in Array.prototype.filter.call(forms, has to return either true or false for each element to work as expected, not false or undefined. You could use e.g. Array.prototype.every and/or Array.prototype.map instead of Array.prototype.filter:
<script>
$(document).ready(function () {
$("#frmInfo").submit(function (event) {
event.preventDefault();
var forms = document.getElementsByName('frmInfo');
var validation = Array.prototype.map.call(forms, function (form) {
if (!form.checkValidity()) {
form.classList.add('was-validated');
alert('Hit invalid user input');
return false;
}
else {
alert('Everything is valid');
form.classList.add('was-validated');
return true;
}
});
if (!validation.every(el => el)) return false;
var obj = Object.fromEntries(new FormData(event.target));
if (obj.Is_Body_HTML == 1)
obj.Is_Body_HTML = true;
else
obj.Is_Body_HTML = false;
if (obj.Is_Active == 1)
obj.Is_Active = true;
else
obj.Is_Active = false;
setDisabled();
var json = JSON.stringify(obj);
alert(json);
var request = $.ajax({
url: "../handlers/test.ashx",
method: "POST",
data: json,
dataType: "json"
});
request.done(function (msg) {
if (msg.Success == false) {
$('#infoErr').html('Should not have reached this!');
$('#toastInfoFail').toast('show');
}
else {
localStorage.setItem('cust_no', msg.ID);
document.location.href = 'getaddress.aspx';
}
});
request.fail(function (jqXHR, textStatus) {
$('#infoErr').html('Unable to contact server to process change request. Please try again later.');
$('#toastInfoFail').toast('show');
});
request.always(function (jqXHROrData, textStatus, jqXHROrErrorThrown) {
setEnabled();
});
});
$('#BestTelephone').inputmask("999-999-9999");
$('#FirstName').focus();
});
function setDisabled() {
$('#btnNext').prop('disabled', true);
}
function setEnabled() {
$('#btnNext').prop('disabled', false);
}
</script>
I have made this custom ajax function to avoid writing ajax code multiple times. My issue is that if there is no option passed for failcmds variable & obj.status is "failure", then also code execution moves to the succcmds code block & execute available commands. e.g. reload(2500) in the example code.
Pls help me to identify the missing part.
Custom Ajax function
function gr(url, varr, succcmds, failcmds, divid, drestype) {
$.ajax({
url: url,
type: "POST",
data: varr,
beforeSend: function(){
$('#loadingDiv').show();
},
complete: function(){
$('#loadingDiv').hide();
},
success: function(response){
if(response){
var obj = $.parseJSON(response);
if(obj.status == "failure") {
console.log('failcmds : ' + failcmds);
if(obj.message) {
gm("e",obj.message);
}
if(typeof failcmds === "undefined") {
return;
}else {
$.each(failcmds,function(index, value) {
value;
});
}
}else if(obj.status == "success"){
if(obj.message) {
gm("s",obj.message);
}
if(succcmds && succcmds !== null) {
$.each(succcmds,function(ind, val) {
val;
});
}
if (divid && divid !== null){
if(drestype && drestype == "html"){
$("#"+ divid).html(obj.data);
}else{
$("#"+ divid).append(obj.data);
}
}
}
}else{
gm("e", "Invalid Request");
}
},
error: function(){}
});
}
Sample usage of function
$(document).on("click", '.xyz', function() {
var d = $(this).prop('id');
var data = 'd='+ $(this).prop('id') + '&typ=sts';
gm('c','Are you sure you want to do this?');
$(document).on("click", '#btnYes', function() {
var sarr = [reload(2500)];
gr(basepath + "deletereq?", data, sarr);
});
});
then also code execution moves to the succcmds code block & execute available commands
No it doesn't. You executed those commands before you even called your function:
var sarr = [reload(2500)];
This will execute reload(2500) and put the result of that execution in the sarr array.
Instead, wrap that in a function:
var sarr = [function () { reload(2500); }];
Then you can later execute that function where you like:
$.each(succcmds,function(ind, val) {
val();
});
Basically you want your "commands" to be executable functions, not the results of executed functions.
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
});
I have one function in java script. I want to send my form in ajax call after validation. I wrote ajax code for this but it's neither working nor giving any error on console even .
What can i do ?
javascript
function resetValidation(){
$(_reqForm).find('input, select, textarea, fieldset').removeClass('invalid');
$(_reqForm).find('.error-indicator').attr('aria-hidden', true);
$(_reqForm).find('#errorSummary').remove();
}
function handleSubmit(e){
e.preventDefault();
var formValid = true;
var errorMessages = [];
$.ajax({
type: "POST",
url: "quoteProcess.php",
data : $('#testform').serialize(),
success: function(data) {
alert(data);
//var obj = jQuery.parseJSON(data); if the dataType is not specified as json uncomment this
// do what ever you want with the server response
},
error: function() {
alert('error handing here');
}
});
$(_reqForm).find('#errorSummary').remove();
$(_reqForm).find('[data-do-validate="true"]').each(function(){
var validationResult = validateField($(this));
if (!validationResult.isValid) {
var fieldMsg = getFieldMessage($(this), validationResult.type);
errorMessages.push({ elem: $(this).prop('id'), msg: fieldMsg });
showFieldError($(this), fieldMsg);
formValid = false;
} else {
clearFieldError($(this));
}
});
if (!formValid) {
if (settings.showErrorSummary) {
showErrorSummary(errorMessages);
}
return false;
} else {
if (typeof(settings.submitFunction) !== 'undefined') {
settings.submitFunction();
} else {
_reqForm[0].submit();
}
}
}
I have been working on a JavaScript validator, but for some reason, evalid always returns as false even if it has passed validation... this is a bug as if evalid is false, the form doesn't submit.
function signup_validate()
{
document.getElementById("email_error").innerHTML = "";
document.getElementById("password_error").innerHTML = "";
evalid = false;
pvalid = false;
email = null;
pass = null;
confpass = null;
email=document.forms["signup_form"]["email"].value.replace(/^\s+|\s+$/g, '');
atpos=email.indexOf("#");
dotpos=email.lastIndexOf(".");
pass=document.forms["signup_form"]["pass"].value;
confpass=document.forms["signup_form"]["confpass"].value;
if (atpos<1 || dotpos<atpos+2 || dotpos+2>=email.length)
{
document.getElementById("email_error").innerHTML = "<span class='required'>Email must be valid.</span>";
}
else
{
$.post('/resources/forms/signup.php',{email: email}, function(data){
if(data.exists){
document.getElementById("email_error").innerHTML = "<span class='required'>This email is already in use.</span>";
}
else
{
evalid = true;
}
}, 'JSON');
}
if (pass!=""&&pass!=null&&confpass!=""&&confpass!=null&&confpass==pass)
{
pvalid = true;
}
else
{
document.getElementById("password_error").innerHTML = "<span class='required'>Both passwords must match and cannot be left blank.</span>";
}
alert(evalid);
if (evalid == true && pvalid == true)
{
document.getElementById("signup_form").submit();
}
else
{
return false;
}
}
What could I have missed?
The only moment when you set "evalid" true is inside a function that runs asynchronously. In other words, by the time you set "evalid" true the main function has already reached the end.
You Could try to use $.ajax instead of $.post and use the parameter async:false
Try something like this:
$.ajax({
type: 'POST',
url: '/resources/forms/signup.php',
data: {email: email},
success: function(response){
//your function here
},
dataType:'JSON',
async:false
});