I am making A ajax login form great progress so far thanks to A few users on stack flow so far.
Now when I check all the fields out if it responds to enter being pressed it is working fine except when I tab to the submit button it is submitting the data twice according to the Chrome networking tab.
I think it is executing the .click function aswill as the .keycode function.
How can i say in the code if keycode enter is false and I click the button execute the function or if its true don't execute the .click function.
$(document).ready(function () {
$('#field').keyup(function (e) {
if(e.keyCode == 13) {
//If enter is pressed vailidate the form
$.ajax({
url: 'ajax/check.php',
type: 'post',
data: {
method: 'fetch'
},
success: function (data) {
$('.chat .messages').html(data);
}
});
};
});
$('#submit').click(function () {
alert('Do something here this is just a test');
});
});
just add preventDefault and return false to the keyup function like that:
$('#field').keyup(function (e) {
if(e.keyCode == 13) {
//If enter is pressed vailidate the form
e.preventDefault();
$.ajax({
url: 'ajax/check.php',
type: 'post',
data: {
method: 'fetch'
},
success: function (data) {
$('.chat .messages').html(data);
}
});
return false;
};
});
This will prevent the form from submitting when users press ENTER.
Related
I have a search box at the top of page that makes an ajax call when a user hits the adjacent button. I am trying to update the input tag so that when a user hit the 'enter' key, the appropriate JavaScript takes place without reloading the page. without using form
$('#Searchbar').bind("enterkey", function (e) {
$("#Searchbar").load('Search(1);');
e.preventDefault();
});
$('#Searchbar').keyup(function (event) {
if (event.keyCode === 10 || event.keyCode === 13) {
$(this).trigger("enterKey");
event.preventDefault();
}
});
}
$('#Searchbar').on("enterkey", function(e) {
//
search('whatever your search string might be', function(result) {
// get the result and put in the resultcontainer
$('.resultContainer').html(result);
});
e.preventDefault();
});
$('#Searchbar').keyup(function(event) {
if (event.keyCode === 10 || event.keyCode === 13) {
$(this).trigger("enterKey");
event.preventDefault();
}
});
function search(data, callback) {
//Do an ajax call and call the callback on succes
//Check for proper syntax in jquery documentation
$.post({
'data': data,
'url': your search url,
success: function(result) {
callback(result);
}
});
}
I'm having a problem with the unbind event from jquery.
I load a modal after clicking a button and in this modal I have two possibilities, continue or cancel. If I continue there are some validations and if something goes wrong an alert should appear, or if I click cancel I close the modal. But if i cancel the modal and then I click the button that loads the modal with an ajax call again when clicking continue the alert appears 2 times, when it should appear only once. I've tried using the unbind event as is seen in the code but it doesn't seem to work, any ideas?
The ajax call is done by the followinenter code hereg code:
function ValidacionGeneral() {
var frmObs = $("#frmCreate");
$.ajax({
url: '#Url.Action("ValidacionGeneral", "Viajes")',
type: 'POST',
dataType: "text",
data: frmObs.serialize(),
success: function (data) {
if (data == "OK") {
$('#frmCreate').submit();
}
else {
$.unblockUI();
$.modal(data);
}
}
});
}
And the script of the modal is:
<script type="text/javascript">
$(document).ready(function () {
$("#btnAceptarValidacionGeneral").unbind("click");
$("#btnAceptarValidacionGeneral").live("click", function (e) {
e.preventDefault();
var error1 = false;
var error2 = false;
var error3 = false;
var error4 = false;
if ($('#ddlMotivosDistancia').length) {
error1 = $("#ddlMotivosDistancia").val() == '00000000-0000-0000-0000-000000000000';
}
if ($('#ddlMotivosRendimiento').length) {
error2 = $("#ddlMotivosRendimiento").val() == '00000000-0000-0000-0000-000000000000';
}
if ($('#ddlMotivosCarga').length) {
error3 = $("#ddlMotivosCarga").val() == '00000000-0000-0000-0000-000000000000';
}
if ($('#ddlMotivosDuracion').length) {
error4 = $("#ddlMotivosDuracion").val() == '00000000-0000-0000-0000-000000000000';
}
if (error1 || error2 || error3 || error4) {
alert('Debe seleccionar los motivos de tolerancia correspondientes para las alertas');
} else {
var form = $('#frmCreate');
if (form.html() == null) {
form = $('#frmEdit');
}
form.submit();
}
});
$("#btnCancelarValidacionGenral").live("click", function () {
$("#IdMotivoToleranciaDistancia").val('00000000-0000-0000-0000-000000000000');
$("#IdMotivoToleranciaRendimiento").val('00000000-0000-0000-0000-000000000000');
$("#IdMotivoToleranciaCarga").val('00000000-0000-0000-0000-000000000000');
$("#IdMotivoToleranciaDuracion").val('00000000-0000-0000-0000-000000000000');
});
});
Use off("click") to unbind all click events:
$("#frmCreate").off("click")
Further, if it's a one-time thing use $.one to bind it in the first place:
$("#frmCreate").one("click", function(){/*do this once and once only */});
HTH
Your unbind $("#btnAceptarValidacionGeneral").unbind("click"); is executed once only when DOM is ready, I think you must move it to function ValidacionGeneral()
After seaching I found that to unbind events attached with .live() the proper way is using .die()
Here is the documentation: http://api.jquery.com/die/
It solved my problem.
I got a barcode scanner gun which scans very fast. Since barcode scanner is treated like a keyboard action, there are times when I fire the gun twice consecutively, the textbox would not stop itself from entering values on it (even though the gun automatically fires an enter command keycode 13 after entering all the scanned values).
Here is my code:
$('#sku_upc_input').keyup(function(e) {
var code = (e.keyCode ? e.keyCode : e.which);
switch (code) {
case 13:
$(this).attr('disabled', 'disabled');
$(this).parents('form').submit();
break;
}
});
So on submission, it would fire an ajax.
$('#add_scans_sku_form').submit(function (e) {
$.ajax({
url: '/netsuite/po/checkUPCSkipCapture/',
data: {
po_num: current_po.id,
upc_code: $('#upcCode').val(),
sku_id: sku_id
},
type: 'POST',
dataType: 'json',
success: function(data) {
if (data['status'] != false) {
initUPCPopup(sku_id, desc);
} else {
$('#sku_upc_input').val('');
$('#sku_upc_input').focus();
}
}
});
)};
I did a solution that after keycode 13 (enter), the textbox would disable itself so the gun won't enter extra values (if fired again immediately) on the textbox but another flaw of this is that sometimes, when you fire the gun fast consecutively, the textbox that receives the scanned value would input incomplete values lets say for example. If the barcode is WORAS012-Z it would sometimes be RAS012-Z or even S012-Z.
The gun's action is so fast that it's hard to perfectly get a complete value in it when fired consecutively. I hope my problem is understood. I hope there are solutions to this. Please give me some ideas. Thank you!
If you want the scanner to only scan once the ajax call is complete you should set a variable to know whether it has been completed or not.
var completed = true; //<<<<< define the variable
$('#sku_upc_input').keyup(function(e) {
var code = (e.keyCode ? e.keyCode : e.which);
switch (code) {
case 13:
if ( !completed ) return; //<<<<< cancel action if it's not completed yet
$(this).attr('disabled', 'disabled');
$(this).parents('form').submit();
break;
}
});
$('#add_scans_sku_form').submit(function (e) {
completed = false; //<<<<< set to false when fired
$.ajax({
url: '/netsuite/po/checkUPCSkipCapture/',
data: {
po_num: current_po.id,
upc_code: $('#upcCode').val(),
sku_id: sku_id
},
type: 'POST',
dataType: 'json',
success: function(data) {
completed = true //<<<<< set back to true when complete
if (data['status'] != false) {
initUPCPopup(sku_id, desc);
} else {
$('#sku_upc_input').val('');
$('#sku_upc_input').focus();
}
}
});
)};
I'm not sure what kind of scanner that is or how it works, but based on what you said I think a better approach would be to cancel everything for 200-500ms and not based on how fast your ajax call is like so:
var completed = true;
// at the start of your event handler
if ( !completed ) return;
completed = false;
setTimeout(function(){
completed = true;
},200)
I have a form which on submit should see if the text area has no text or the place holder text.
iif it does it shouldn't submit it. something like validation. I am not able to stop the form submission.
$(document).ready(function () {
var options = {
target: '.user-status',
// target element(s) to be updated with server response
beforeSubmit: showRequest,
// pre-submit callback
success: showResponse,
// post-submit callback
// other available options:
//url: url // override for form's 'action' attribute
//type: type // 'get' or 'post', override for form's 'method' attribute
//dataType: null // 'xml', 'script', or 'json' (expected server response type)
//clearForm: true // clear all form fields after successful submit
resetForm: true // reset the form after successful submit
// $.ajax options can be used here too, for example:
//timeout: 3000
};
$('#updateStatus').submit(function () {
$(this).ajaxSubmit(options);
return false; // prevent a new request
});
function showRequest(formData, jqForm, options) {
var textbox = $('#StatusMessageMessage').val();
if ((textbox == '') || (textbox == "What have you been eating ?")) {
alert(text);
return false;
} else {
$('#StatusMessageMessage').attr('disabled', true);
}
}
function showResponse(responseText, statusText, xhr, $form) {
$('#StatusMessageMessage').attr('disabled', false);
}
statusMEssagebox();
});
function statusMEssagebox() {
var textholder = $('#StatusMessageMessage').val();
$('#StatusMessageMessage').focus(function () {
if ($(this).val() == textholder) $(this).val("");
$(this).animate({
"height": "48px",
}, "fast");
$('.share').slideDown("fast");
$(this).TextAreaExpander(48, 75);
});
$('#StatusMessageMessage').blur(function () {
if ($(this).val() == "") {
$(this).val(textholder);
$('.share').slideUp("fast");
$(this).animate({
"height": "18px",
}, "fast");
}
});
}
I see that you are using the jquery form plugin to ajaxify your form. There's an example in the documentation illustrating how to achieve this in an elegant way. You don't need to subscribe for the .submit event of the form and manually submit it using .ajaxSubmmit. You could simply try this:
$(function() {
$('#updateStatus').ajaxForm({
beforeSubmit: function(formData, jqForm, options) {
var value = $('#StatusMessageMessage').val();
if (value == '' || value == 'What have you been eating ?') {
return false;
}
}
});
});
You are using equality operator rather than comparison.
This:
if ((textbox = '') || (textbox = "What have you been eating ?")) {
Problem -----^
Should be:
if (textbox == '' || textbox == "What have you been eating ?") {
You may also want to see how the submit form via Ajax using jQuery:
http://net.tutsplus.com/tutorials/javascript-ajax/submit-a-form-without-page-refresh-using-jquery/
I have a form. I want to add an event handler using jquery.
$("form").submit(function blah() {
$.post('ping-me-please.php', params, function (response) {
// only submit the form once this goes through!
});
}
How can I make this happen?
Like this:
$("form").submit(function (e) {
var form = $(this);
if (!form.data('pinged')) {
e.preventDefault(); // Cancel the submit
$.post('ping-me-please.php', params, function (response) {
// only submit the form once this goes through!
// First we set the data, then we trigger the submit again.
form.data('pinged', true).submit();
});
}
}
var postWasSent = false;
$("form").submit(function blah() {
if (!postWasSent)
{
$.post('ping-me-please.php', params, function (response) {
postWasSent=True;
$("form").submit();
});
return false;
}
}