jConfirm message cannot work properly - javascript

The confirmation popup always return true. Please advice the correction needed.
$('#btnDelete').click(function () {
var check = false;
var aCheckbox = document.getElementsByTagName('input');
for (var i = 0; i < aCheckbox.length; i++) {
if (aCheckbox[i].type === 'checkbox' && aCheckbox[i].checked) {
check = true;
}
}
if (check === true) {
return jConfirm('Do u really want to delete?', 'Confirmation');
} else {
jAlert("Please select serial number", 'Alert');
return false;
}
});

Hope this help :
if (check === true) {
var answer = confirm('Do u really want to delete?', 'Confirmation');
if(answer)
return true;
else
return false;
}
else {
jAlert("Please select serial number", 'Alert');
return false;
}

Yes it creates problem you need to use third parameter as callback function of jconfirm like,
if (check === true) {
jConfirm('Do u really want to delete?', 'Confirmation', function(r) {
jAlert('Confirmed: ' + r, 'Confirmation Results');
});
return false;
} else {
.....
Also remove extra closing }); from your code, see last two lines.

Related

Simplifying IF/ELSE IF/ELSE Block

I'm creating my own validation code. I need to separate the if statements per input box for the error to show at the same time. I noticed that if it's on same if block, only the first error will show. Any way to simplify my code?
flag = 0;
//first if
if (first_name.length == 0) {
flag = 0;
$("label[for='firstname'").text('This field is required').css("display", "inline-block");
} else if (!first_name.match(name_regex)) {
flag = 0;
$("label[for='firstname'").text('Firstname must be composed of letters only').css("display", "inline-block");
} else if (first_name.length < 3) {
flag = 0;
$("label[for='firstname'").text('3 letters are required for lastname').css("display", "inline-block");
} else {
flag = +1;
$("label[for='firstname'").hide();
}
//second if
if (last_name.length == 0) {
flag = 0;
$("label[for='lastname'").text('This field is required').css("display", "inline-block");
} else if (!last_name.match(name_regex)) {
flag = 0;
$("label[for='lastname'").text('Lastname must be composed of letters only').css("display", "inline-block");
} else if (last_name.length < 2) {
flag = 0;
$("label[for='lastname'").text('2 letters are required for lastname').css("display", "inline-block");
} else {
$("label[for='lastname'").hide();
flag += 1;
}
//third if
if (validateEmail(email)) {
if (data.result) {
$("input#userEmail").css("border-color", "#ac2925");
$("label[for='email'").text('Email exists').css("display", "inline-block");
} else {
$("input#userEmail").css("border-color", "#e3e3e3");
$("label[for='email'").hide();
flag += 1;
}
} else {
$("input#userEmail").css("border-color", "#ac2925");
$("label[for='email'").text('Please input a valid email address').css("display", "inline-block");;
}
//fourth if on verification success
if (flag == 3) {
alert("All validation succeded!");
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
Just extract it into a function:
function validate(inputName, labelName, minLetters, regex){
const el = $(inputName);
const label = $(labelName);
if(!el || !!label) throw "validate: el not found";
if(!el.val()){
label.text("You need to fill in this!");
return false;
}
if(regex && !el.val().test(regex)){
label.text("The input contains invalid chars!");
return false;
}
if(minLetters && el.val().length < minLetters){
label.text("to short!");
rerurn false;
}
return true;
}
I would suggest to make the validation routine more generic. Please see following solution (note: untested):
function validate(funcName, minLength) {
if (this[funcName].length == 0) {
$("label[for='"+funcName+"'").text('This field is required').css("display", "inline-block");
} else if (!this[funcName].match(name_regex)) {
flag = 0;
$("label[for='"+funcName+"'").text(funcName +' must be composed of letters only').css("display", "inline-block");
} else if (this[funcName].length < minLength) {
$("label[for='"+funcName+"'").text(minLength + ' letters are required for ' + funcName).css("display", "inline-block");
} else {
$("label[for='"+funcName+"'").hide();
return true;
}
return false;
}
if (validate("firstname", 2)
&& validate("lastname", 3)
&& validateEmail(email)
) {
// everything seems to be OK.
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
My approaches will be :
Have individual If blocks for each validations by which all the validations will be checked. And build/append the validation error message on each check.
Write if else blocks within a function. That function can be called for each fields being validated. And the function will return validation error message for each invokation which can be appended into a single string.

JavaScript Submithandler Issue

$("#myform").validate({
submitHandler: function (form) {
var cboxes = ($('input:checkbox:checked').filter(":checked").length);
var nboxes = ($(":checkbox:not(:checked)").length);
var flag = false;
if ((cboxes > 0) && (nboxes > 0)) {
flag = confirm('You have Checked only few locations among the List. \n Are you sure, you do not want to Prescribe from the other locations? ');
} else if (cboxes == 0) {
alert('Please select atleast One Address \n Where you would prefer to prescribe from.');
}
else {
flag = true;
}
return flag;
}
});
When the Confirm box pop up if I clicks ok it should accept the submit, but it is not.
Can anyone tell me why is this happening?
Replace return flag with form.submit.
$("#myform").validate({
submitHandler: function (form) {
var cboxes = ($('input:checkbox:checked').filter(":checked").length);
var nboxes = ($(":checkbox:not(:checked)").length);
var flag = false;
if ((cboxes > 0) && (nboxes > 0)) {
flag = confirm('You have Checked only few locations among the List. \n Are you sure, you do not want to Prescribe from the other locations? ');
} else if (cboxes == 0) {
alert('Please select atleast One Address \n Where you would prefer to prescribe from.');
}
else {
flag = true;
}
if(flag)
form.submit();
}
});
If you're not using AJAX, this is the way described in the .validate() docs.

How to validate multiple functions with one IF statement - Javascript, jQuery

I want to validate multiple functions, and for each one returning false, do some animations.
Here's the code:
function validarChido(){
var dedo = $('#dedo_pick');
if(dedo.children().size() < 2){
dedo.animate({'background-color' : 'red'},200);
dedo.animate({'background-color' : '#EEE'},200);
return false;
}
else{return true;}
}
function validarEx(){
var valEx = $('#rate1');
if(valEx.children().size() < 2){
valEx.animate({'background-color' : 'red'},200);
valEx.animate({'background-color' : '#EEE'},200);
return false;
}
else{return true;}
}
$('#form').submit(function(){
if( validarChido() && validarEx() )
{return true }
else
{return false; }
});
When I send the form, I only see the first function doing the color animation, obviously because the form validation IF statement doesn't evaluate the next function because the first resulted in false here if( validarChido() && validarEx() )
Is there a way to evaluate all the functions and see the animation in each one and then send the form if everything is true?
Instead of returning false or true do something similar to the following:
function validarChido() {
var dedo = $('#dedo_pick');
if(dedo.children().size() < 2){
dedo.animate({'background-color' : 'red'},200);
dedo.animate({'background-color' : '#EEE'},200);
return "error";
}
else{return "";}
}
function validarEx(){
var valEx = $('#rate1');
if(valEx.children().size() < 2){
valEx.animate({'background-color' : 'red'},200);
valEx.animate({'background-color' : '#EEE'},200);
return "error";
}
else{return "";}
}
$('#form').submit(function(){
var check = validarChido();
check += validarEx();
if( check == "" )
{return true }
else
{return false; }
});
It can be something like this:
$('#form').submit(function(){
var validarChidoResult = validarChido(),
validarExResult = validarEx();
if( validarChidoResult && validarExResult )
{return true }
else
{return false; }
});
var result = validarChido();
result = validarEx() && result;
return result;

Checkbox validation - at least one selected

I have number of checkboxes and another checkbox for "Select All"
I want to check if the user has selected at least one checkbox. Need modification in javascript
<script language="Javascript">
function doSubmit(){
function check_checkboxes()
{
checked=false;
var c = document.getElementsByTagName('INPUT');
for (var i = 1; i < c.length; i++)
{
if (c[i].type == 'checkbox')
{
if (c[i].checked) {
return true}
else {alert("Please identify what warehouses comply:"); }
}
} //if I place my struts action here..its not working?
}
document.holiDay.command.value= 'addingApp'; //My Struts action if something checked.
document.holiDay.submit();
}
var all=document.getElementById('holiDay');
In HTML IDs should be unique, so getElementById will only return 1 element. Perhaps you could try getElementsByTagName - http://msdn.microsoft.com/en-us/library/ms536439(VS.85).aspx ?
Something like...
function check_checkboxes()
{
var c = document.getElementsByTagName('input');
for (var i = 0; i < c.length; i++)
{
if (c[i].type == 'checkbox')
{
if (c[i].checked) {return true}
}
}
return false;
}
and change your Validate function to...
function Validate()
{
if(!check_checkboxes())
{
alert("Please identify what warehouses comply:");
return false;
}
return true;
}
Select at least one check box using jqQery. Try the following code.
$('input[type="checkbox"][name="class"]').on('change', function () {
var getArrVal = $('input[type="checkbox"][name="class"]:checked').map(function () {
return this.value;
}).toArray();
if (getArrVal.length) {
//execute the code
} else {
$(this).prop("checked", true);
alert("Select at least one column");
return false;
}
;
});
(function() {
for(x in $ = document.getElementsByTagName("input"))
with($[x])
return (type == "checkbox" ? checked == true : 0)
})

ajax hidding div problem in IE

I have a javascript page which checks an email and username, this works fine in every browser but Internet Explorer. The div box where errors are shown should be hidden unless an error is given e.g. username taken or invalid email.
If the email gets an error this is shown in the div tag, but doesnt work for username (in all browsers)
below is my code:
<script type="text/javascript">
var usernameok;
var emailok;
function checksubmit()
{
if (usernameok && emailok) {
document.getElementById("button").disabled = false;
} else {
document.getElementById("button").disabled = true;
}
}
function username(username)
{
make_request();
function stateck()
{
if (httpxml.readyState == 4) {
if (httpxml.responseText.indexOf("Username Ok") >= 0) {
usernameok = true;
} else {
usernameok = false;
}
checkCanSubmit();
}
}
httpxml.onreadystatechange = stateck;
user_url = "check_username.php?username=" + username.value;
httpxml.open("GET", user_url, true);
httpxml.send(null);
}
function email(email)
{
make_request();
function stateck()
{
if (httpxml.readyState == 4) {
if (httpxml.responseText.indexOf("Email Ok") >= 0) {
emailok = true;
} else {
emailok = false;
}
checkCanSubmit();
}
}
httpxml.onreadystatechange = stateck;
email_url = "check_email.php?email=" + email.value;
httpxml.open("GET", email_url, true);
httpxml.send(null);
}
</script>
I see your function stateck() is the return function from the HTTP request. However, you are defining it within another function. Not as an anonymous function, but just as a function within another function.
I see what you're doing now...ok, try this instead:
httpxml.onreadystatechange = function()
{
if (httpxml.readyState == 4) {
if (httpxml.responseText.indexOf("Email Ok") >= 0) {
document.getElementById("email").style.backgroundColor = "green";
document.getElementById("email").style.color = "white";
document.getElementById("email_div").style.display = 'none';
emailok = true;
} else {
document.getElementById("email").style.backgroundColor = "red";
document.getElementById("email_div").innerHTML=httpxml.responseText;
emailok = false;
}
checkCanSubmit();
}
};
Do you need to set your initial state to display: none? I think IE may initialize the divs with a non-0 height whereas the divs may be technically visible in other browsers but too short to see.
Edit:
Okay I think I misunderstood your question. Your problem is not with hiding the divs but with displaying errors for the username.
Nothing obvious jumps out at me. Try stepping through the code using VS or VWDE:
http://www.berniecode.com/blog/2007/03/08/how-to-debug-javascript-with-visual-web-developer-express/

Categories