I am using JavaScript to validate some form fields. My question is about the code inside
$("#alias").keyup(function(){
This is my script for the validation:
<script type="text/javascript">
$(document).ready(function(){
console.log("principio");
// Setup the ajax indicator
// Ajax activity indicator bound to ajax start/stop document events
$(document).ajaxStart(function(){
$('#ajaxBusy').show();
}).ajaxStop(function(){
$('#ajaxBusy').hide();
});
//control de alias
$("#alias").keyup(function(){
var ID=$("#alias").val();
var REST=$("#rest").val();
var ACTUAL = "<?php echo $row_Recordset1['alias_mesero']?>";
$.post("check_username_edit.php", { username: ID, rest: REST, actual: ACTUAL},
function(result){
console.log(result);
//if the result is 1
if(result == 1){
document.getElementById('mensajealias').innerHTML ="Nombre corto disponible";
document.getElementById('boton').style.visibility='visible'; // hide
document.getElementById('mensajeboton').innerHTML ="Ahora puede insertar los datos";
}
else if(result == 2){
document.getElementById('mensajealias').innerHTML ="No ha modificado el nombre corto";
document.getElementById('boton').style.visibility='visible'; // hide
document.getElementById('mensajeboton').innerHTML ="Ahora puede insertar los datos";
}
else if(result == 0){
document.getElementById('mensajealias').innerHTML ="Nombre corto no disponible, ya existe";
document.getElementById('boton').style.visibility='hidden'; // hide
document.getElementById('mensajeboton').innerHTML ="No se puede insertar hasta que no modifique los datos";
}
});
});
//control de rest
$("#rest").change(function(){
var ID=$("#alias").val();
var REST=$("#rest").val();
var ACTUAL = "<?php echo $row_Recordset1['alias_mesero']?>";
$.post("check_username_edit.php", { username: ID, rest: REST, actual: ACTUAL},
function(result){
console.log(result);
//if the result is 1
if(result == 1){
document.getElementById('mensajealias').innerHTML ="Nombre corto disponible";
document.getElementById('boton').style.visibility='visible'; // hide
document.getElementById('mensajeboton').innerHTML ="Ahora puede insertar los datos";
}
else if(result == 2){
document.getElementById('mensajealias').innerHTML ="No ha modificado el nombre corto";
document.getElementById('boton').style.visibility='visible'; // hide
document.getElementById('mensajeboton').innerHTML ="Ahora puede insertar los datos";
}
else if(result == 0){
document.getElementById('mensajealias').innerHTML ="Nombre corto no disponible, ya existe";
document.getElementById('boton').style.visibility='hidden'; // hide
document.getElementById('mensajeboton').innerHTML ="No se puede insertar hasta que no modifique los datos";
}
});
});
});
</script>
If the user enters the text character by character, the validation takes place like a charm.
But I have detected that if the user enters the text very quickly, then sometimes the validation doesn't return the right value.
I guess I could use change(function) instead of keyup(function), but I would prefer that the user doesn't have to leave the field to be validated.
Any advice is welcome.
I have used this approach on a search box that I only wanted to execute the search when the user stopped typing for a short period of time:
var delay = (function () {
var timer = 0;
return function (callback, ms) {
clearTimeout(timer);
timer = setTimeout(callback, ms);
};
})();
$("#alias").on('propertychange keyup input paste', function () {
delay(function () {
//validate
}, 1000);
});
It starts a timer for 1 second when any of those events fire and only executes the validation if the timer expires. If any new events are received the timer is reset to 1 second. This event handler also works for cutting and pasting from/to the input.
Two points for you to consider:
1) Old style Keyup keydown events are not reliable. You always need backup validation from the backend if you use them. If the user inputs quickly, few keyup events will be fired but you are not even sure which event first.
2)Morden Browsers support new events like "input", if possible you should use new events.
Related
I have a form where I ask for an email that I validate trought a regular expression, if the email is correct, I do a submit, if not I send an alert.
When I put an invalid email the alert is shown, but if I put a valid email the alert is shown and then the submit() is done, I don't even know how is this posible! Here is my code.
$('#sinCopago').on('click', function(event){
if($('#nombreContratante').val() != "" && $('#motivo').val() != ""){
if($('#fechaNac').val() > hoy){
alert("Ingresa una fecha de nacimiento válida.");
}else{
if(validarMail($("#correo")) == true){
event.preventDefault();
$('#progressBarSisnova').modal({show:true});
$('#payment-form-Sisnova').submit();
}
else{
alert("Ingresa un correo válido");
}
}
}
else{
alert("Por favor llene todos los campos");
}
});
function validarMail(email){
var caract = /^\w+([\.-]?\w+)*#\w+([\.-]?\w+)*(\.\w{2,4})+$/;
if(caract.test(email) == false){
return false;
}
else{
return true;
}
}
You're currently passing the $("#correo") jQuery object to validarMail:
if(validarMail($("#correo")) == true){
and proceed to test that object:
if(caract.test(email) == false){
Which won't work, of course, because you're not testing a string. Try passing the .val() of #correo instead. so that the eventual .test( is called with the value string, not the jQuery object:
if(validarMail($("#correo").val()) == true){
Feel free to remove the == true part, validarMail already returns a boolean:
if(validarMail($("#correo").val())){
You should also preventDefault when the test fails, not when the test succeeds - that way, the form will be submitted as normal without interruption only when the test succeeds. The code will also probably be flatter and easier to read if you return when there's an error:
$('#sinCopago').on('click', function(event){
if($('#nombreContratante').val() === "" || $('#motivo').val() === "") {
event.preventDefault();
return alert("Por favor llene todos los campos");
}
if($('#fechaNac').val() <= hoy){
event.preventDefault();
return alert("Ingresa una fecha de nacimiento válida.");
}
if(!validarMail($("#correo").val())){
event.preventDefault();
return alert("Ingresa un correo válido");
}
$('#progressBarSisnova').modal({show:true});
$('#payment-form-Sisnova').submit();
});
If clicking #sinCopago submits the form without preventDefault, then there's no need for the final line there $('#payment-form-Sisnova').submit();. (Otherwise, then there may be no need for preventDefault at all, if the event's default action doesn't cause a form submission or other undesirable behavior)
you should pass the value of field for function validarMail(), so replace the current cod
if(validarMail($("#correo")) == true)
for
if(validarMail($("#correo").val()) == true)
an you can improve you function.
function validarMail(email){
var caract = /^\w+([\.-]?\w+)*#\w+([\.-]?\w+)*(\.\w{2,4})+$/;
return caract.test(email)
}
I'm using Angular in Javascript to connect to the server, What I want to do is make reusable code.
The problem if that for each service that have to obtain data from server I have to know status response and if was 200 I have to know if the success was 1 or 0.
So... This is my code at today (using promise):
function obtenerUltimasOperacionesComplejo() {
return $http
.get(ultimasOperacionesUrl,
{params: {idComplejo: 11}})
.then(obtenerDatosUltimasOperaciones)
.catch(generarError);
}
function obtenerDatosUltimasOperaciones(data) {
var mensaje = '';
var status = data.status;
if(status == 401){
mensaje = 'Acceso no autorizado.';
return $q.reject(mensaje);
}
else if (status <> 200){
mensaje = 'Ups! Hubo un problema al conectarse al servidor. Intente nuevamente.';
return $q.reject(mensaje);
}
else if(status == 200){
var exito = data.data.success;
if(exito == 0){
mensaje = data.data.mensaje;
return $q.reject(mensaje);
}
else if(exito == 1){
ultimasOperaciones = data.data.ultimasOperaciones;
return ultimasOperaciones;
}
}
}
function generarError(e){
var newMessage = 'XHR error! :';
if (e.data && e.data.description) {
newMessage = newMessage + '\n' + e.data.description;
}
e.data.description = newMessage;
logger.error(newMessage);
return $q.reject('Ups! Hubo un problema al conectarse al servidor. Intente nuevamente');
}
This part of code:
if(status == 401){
mensaje = 'Acceso no autorizado.';
return $q.reject(mensaje);
}
else if (status <> 200){
mensaje = 'Ups! Hubo un problema al conectarse al servidor. Intente nuevamente.';
return $q.reject(mensaje);
}
else if(status == 200){
var exito = data.data.success;
if(exito == 0){
mensaje = data.data.mensaje;
return $q.reject(mensaje);
}
...
I have to use it for each service that I have...
The problem that I have is that I can't put in a function the code above, because I don't know how to set the variable with the corresponding service, I mean:
else if(exito == 1){
ultimasOperaciones = data.data.ultimasOperaciones;
return ultimasOperaciones;
}
This part of code changes for each service because "ultimasOperaciones" var is for this service in particular, for another service I have to use another variable and so on...
So... There is a way to disjoin this two part of code so I can reuse and don't have to copy and paste the most of the code?
Thanks!
please create a interceptor for checking every time the status of your response
http://thecodebarbarian.com/2015/01/24/angularjs-interceptors
I have a HTML form with a textarea in it.
When entering a text with some enters in it, my Javascript malformes and wont load.
The forms submits to a PHP script that outputs the javascript below.
How can I fix this?
function confirmsms() {
var redirect = confirm("Er zullen 791 smsjes worden verzonden, klik op OK om door te gaan");
if (redirect == true) {
window.location.href = 'send.phpregio=%&vakgebied=Loodgieter&disciplines=&bericht=aasdasd
asdasda
sdasdasd';
}
}
</script>
Change to this:
function confirmsms() {
var redirect = confirm("Er zullen 791 smsjes worden verzonden, klik op OK om door te gaan");
if (redirect == true) {
window.location.href = 'send.php?'
+ 'regio=%&vakgebied=Loodgieter&disciplines=&'
+ 'bericht=aasdasdasdasdasdasdasd';
}
}
UPDATE: It seems that your php variable $bericht has line returns in it. Let's sanitize the variable to remove spaces and line returns like so:
$bericht = str_replace(array(' ', "\n", "\t", "\r"), '', $bericht);
Then you can use your code as before. To be safe, I would sanitize all your php variables that are going to be dropped right into javascript.
<HTML>
<HEAD>
<script type=\"text/javascript\">
function confirmsms() {
var redirect = confirm(\"Er zullen $count smsjes worden verzonden, klik op OK om door te gaan\");
if (redirect == true) {
window.location.href = 'send.php?regio=$regio&vakgebied=$vakgebied2&disciplines=$disciplines&bericht=$bericht'; }
}
Looks like the problem is you are not encoding your URL! As in your problem you are passing data using GET method your data will be the part of the URL itself!
Simply use encodeURI() before sending! So your code should look like
function confirmsms() { var redirect = confirm("Er zullen 791 smsjes worden verzonden, klik op OK om door te gaan"); var encodedValue = encodeURI("YOUR TEXTAREA VALUE HERE"); if (redirect == true) { window.location.href = 'send.php?VAR1=VAL1&VAR2=VAL2'; }}
And at the back-end you can decode URL using string urldecode ( string $str )
Hope you this is what you are looking for!
I tried to refresh the page after deleting an item from my back-end list.
Here's the HTML
<a href="index.php?id=<?php
echo $array[id_news];
?>&?action=delete" onClick="return conferma()">Remove</a>
Here's the PHP
if ($_POST['action'] = "delete") {
$sql="DELETE FROM news WHERE id_news=".$_GET['id'];
if (!mysql_query($sql)) {}
}
Here's the Javascript
function conferma() {
return confirm('Confermi di voler cancellare la news selezionata?');
window.location.reload();
}
The popup appears but after clicking OK the page don't refresh.
You are returning on the confirm() line, so the reload never gets executed. Change to:
function conferma() {
if(confirm('Confermi di voler cancellare la news selezionata?')){
// call the delete script via ajax now.....
window.location.reload();
}
return false;
}
It looks like you need to use AJAX to call the delete script, because otherwise the reload will happen and the anchor's href will never be visited.
You are return the boolean result from confirm dialog action, and then reloading, so the script never reach the reload
function conferma() {
ritorno = confirm('Confermi di voler cancellare la news selezionata?');
if(ritorno)
window.location.reload();
else console.log('ok nothing to do');
}
To Fix:
if ($_POST['action'] = "delete") {
by
if ($_POST['action'] == "delete") {
I'm developing a cross platform application using Appcelerator Titanium.
I'm going to fire logout method when user clicks Android back button, in the next windows after login window.
Everything works, but the second time I tried to login and then logout alert dialog shows up two time.
Hope someone will help. Giacomo.
var win = Titanium.UI.currentWindow;
var msg = Titanium.UI.createLabel({
text:"Mail: " + win.email + "\nNome: " + win.name,
top:10,
left:10,
width:300,
height:'auto'
});
win.add(msg);
//definisco una finestra di dialogo per informare l'utente sul logout
var dialog = Ti.UI.createAlertDialog({
buttonNames: ['Si', 'No'],
message: 'Vuoi effettuare il logout?',
title: 'Attenzione'
});
//intercetto il tasto indietro di android e gestisco il Logout
var listener = win.addEventListener('android:back',function(e){
//aggiungo un event listener alla finestra di dialogo intercettando il tasto si o no
dialog.show();
dialog.addEventListener('click', function(e){
if (e.index == 1){
//è stato cliccato il tasto NO, quindi nessuna azione
}else if(e.index == 0){
//è stato cliccato il tasto Si, quindi effettuo il logout, cancello la variabile di sessione ...
win.close();
win.remove(msg);
win.remove(dialog);
}
});
});
I have pulled your answer out of the question and posted it here. This will allow future users to more easily see your solution.
The solution end up being this code
var handlerBack = function (e){
//aggiungo un event listener alla finestra di dialogo intercettando il tasto si o no
dialog.show();
dialog.addEventListener('click', function(e){
if (e.index == 1){
//è stato cliccato il tasto NO, quindi nessuna azione
}else if(e.index == 0){
//è stato cliccato il tasto Si, quindi effettuo il logout, cancello la variabile di sessione ...
win.close();
win.remove(msg);
win.remove(dialog);
win.removeEventListener('android:back', handlerBack);
}
});
};
win.addEventListener('android:back', handlerBack);