I'm new to JavaScript, and I'm wondering how to embed "if" statements within alerts. Specifically, I'm working on a form, and I want the alert that appears after the user clicks "Submit" to display different messages depending on which elements of the user's input are problematic (if any). I know that I could do it the other way around (i.e., use a series of if statements to determine which alert to show), but I was hoping to be able to use "if/else" within the alert code itself. Thanks!
You don't want to use an alert. It's used exclusively to inform the user that something has occurred, and you can't exactly get feedback from it. What you should use instead is a prompt or a confirm. Using the confirm code will allow you to determine whether the user hit OK or Cancel. While this is very limited, it still functions in a manner similar to what you're looking for. For example
var r=confirm("Press a button");
if (r==true)
{
x="You pressed OK!";
}
else
{
x="You pressed Cancel!";
}
Using the prompt code will allow the user to input a value, which you can then append to a variable and use logic from there, such as
var person=prompt("Please enter your name","Harry Potter");
if (person!=null)
{
x="Hello " + person + "! How are you today?";
document.getElementById("demo").innerHTML=x;
}
The standard syntax for the prompt function is
prompt("This text will appear in the alert box","This is the default value");
My source, as well as additional information, is available at W3schools
Edit - I forgot to mention that, if they're using a form you've made in javascript, it could be easier just to run a simple if/else statement that checks if all of the values they've input are not null and have the right datatype before allowing them to continue. Have the else be the alert, I suppose, if you're using the if to confirm validity, as opposed to a lack thereof.
Use a variable:
msg = "";
if (…)
msg = "error 1";
else if (…)
msg = "error 2";
[…]
if (msg.length)
alert(msg);
I was hoping to be able to use "if/else" within the alert code call
You could use the conditional operator, which is basically an else-if inside an expression - which means that the expression as a whole can be passed as an argument:
alert( /* condition */ ? "error 1" : "everything is fine" );
You can write something like
alert(condition ? "Text if true": "text if false");
But it wouldn't be the most readable code. The commented options of
alert(getAlertMessage(anyNeededValue));
or
if (cond) {
alert("true");
} else {
alert("false");
}
sound better. But if you really keen on that "if in the alert", here you have an inline function:
alert((function(){
if (cond) { return "Text when true";}
else {return "Text when false");})());
alert takes a string as an input. Which can come from a variable.
var message;
if ("condition1") {
message = "message1";
} else if ("condition2") {
message = "message2";
} else if ("condition3") {
message = "message3";
}
alert(message);
Unfortunately if is a statement, and can't be directly used as an argument. But you can use the ternary operator instead, which is an expression.
alert(if ("this") { "won't" } else { "work"} );
alert('but' ? 'this' : 'will');
This is also possible, altough I've never seen it used:
alert(
('condition1') ?
'result1' :
('condition2') ?
'result2' :
'result3'
);
Related
I'm checking a website registration form with JavaScript code and onchange listeners.
Empty fields/spaces need to be checked for first before checking for illegal characters, too long strings, etc.
I've read this.
But for a null string,
if (field.value ==="")
alert("Empty field!");
this will not generate the desired alert.
People at the end of the above thread suggested that recent browser versions might not accept such a statement.
So, how do I sort out empty/blank/ignored fields ?
EDIT 1
I've already tried
if (!field.value)
but it only provides an alert if the user has already typed some characters in the field and immediately deleted them before entering a blank field. It will not provide an alert just by clicking the mouse on it and then tabbing on to the next field. It looks like I may need to assign a null value to these form fields at the outset . . I am using implicit adding of the changeEvent listener, i.e. on seeing a value explicitly assigned to the onchange attribute of an element, it is activated without any addEventListener(..) statement.
Also,
if (field.value.length == 0)
does not seem to produce any alert.
EDIT 2
Sorted, I think.
I was using the JavaScript null field check as part of a field-by-field validation check on a web form.
I was using onchange as the event handler. This was wrong. What was needed here was onblur since in the case of a completely null field (i.e. a field on which nothing had been entered before tabbing away from it), no change has been effected -- and therefore no onchange event occurs that would trigger a JavaScript alert.
Thanks for your efforts.
I was stuck on this one across a couple of weeks and only sorted it with the help of some experimental programming by a more experienced guy at work here.
In this script you can see an alert of your variable value ( a console.log would be lees noisy :)
The use of === is for type check but in your example does not make sense as you are using an empty string
<script>
var field= {};
checkEquality(field);
field.value = "";
checkEquality(field);
function checkEquality(object){
alert(object.value);
if (object.value === "")
{
alert("===");
}
if(object.value == ""){
alert("==");
}
}
You can use bellow code for check all four(4) condition for validation like not null, not blank, not undefined and not zero only use this code (!(!(variable))) in javascript and jquery.
function myFunction() {
var data; //The Values can be like as null, blank, undefined, zero you can test
if(!(!(data)))
{
alert("data "+data);
}
else
{
alert("data is "+data);
}
}
Ok hello guys here is my problem i was try to create a jPrompt but i can't understand how can i make a simple if ckeck. I find the code here and i crate it again.Now i want to do something simple, the user click the button and must enter a code for example number 123, and i must check if the number is 123(true) then run an sql query else run this function again unless the user click cancel button and not ok.
I need a good example to learn how t use if statement with Jquery, any simple idea beginner in (jQuery) sorry!!!.
This is what i have try
$("#prompt_button").click( function(e)
{
e.preventDefault();
/*
jPrompt is function which will show custom promt window.
It has three argument.
First argument is label text.
Second is the predefined value for promt.
Third is promt heading.
and has callback function which will perform exatra
code like what user enter.
*/
jPrompt('Type something:', 'Prefilled value', 'Prompt Dialog', function(r)
{
if(r!=123){jPrompt('Enter the right code plese: ');}
else jAlert('Confirmed: ' + r, 'Confirmation Results');
});
});
I don't really understand your problem. Can you supply any code?
I need a good example to learn how t use if statement with Jquery, any
simple idea beginner in (jQuery) sorry!!!.
An "if" statement is fundamental to any client/server language.(Maybe different syntax in some)
var i = 123;
$('.selector').click(function()
{
if(i == 123)
{
alert("Value is " + i);
}
});
Pretty basic click event with an "if" statement. It maybe a good idea to hit a book store or pluralsight.
//Edits
Please remember when creating the later part of an "if / else" statement it needs to be wrapped in curly braces "{}"
Regards,
Sorry guys the answer it was easy to find after 2-3 hours i was searching, and (now i will hit my head to the monitor in front of me), here is the code
$("#prompt_button").click( function(e)
{
e.preventDefault();
/*
jPrompt is function which will show custom promt window.
It has three argument.
First argument is label text.
Second is the predefined value for promt.
Third is promt heading.
and has callback function which will perform exatra
code like what user enter.
*/
jPrompt('Type something:', 'Prefilled value', 'Prompt Dialog', function(r)
{
if( r!=123 ) {$("#prompt_button").click();}
else{window.location.href = "http://stackoverflow.com"}
});
});
It's nice to loose 2-3 hours for something like that, it was simple just call, with the right way, the function (Programming for Dummies( <-This is for Me ). Thanks anyway guys.
I am very close to finishing this program but am unable to get past one last hurdle. I want some very simple code to execute when the command buttons are pressed. When the Submit Order button is pressed the following code should run to check that the form is completed.
function validateForm()
{
if ($("tax").value = 0)
{
alert ("You have not selected anything to order");
}
if ($("shipCost").value = 0)
{
alert("You must select a method of shipping");
}
}
And when the reset button is pressed the following code should run.
function initForm()
{
$('date').value = todayTxt();
$('qty1').focus();
}
Unfortunately the buttons are not executing the code which I am trying to execute through the following set of functions.
window.onload = function ()
{
initForm();
todayTxt();
productCosts();
shipExpense();
$('shipping').onchange = calcShipping;
calcShipping();
$("Submit Order").onclick = validateForm();
$("reset").onclick = initForm();
}
I have created a fiddle so you can see the full program: http://jsfiddle.net/KhfQ2/ Any help is greatly appreciated.
You're doing it way wrong.
With if statements, you use == instead of =.
= in A = B means assign value of B to A
== in A == B means A equals B
Read about .ready and use it instead of window.onLoad, it's quite a bad choice when it comes to binding, ie.
$( document ).ready(function() {
//taken from api.jquery.com/ready/
});
If you're using jQuery, use # when refering to ID objects, ie.
$('#tax').val();
On no account should you use spaces when giving any object a unique name or class!
Pay attention to letters. You had ".clisk()" instead of "click()".
Check it out and provide us with fixed code.
It is simple. $("Submit Order") doesn't work, because the button doesn't have this id. You can change this to something like $("btn-submit-order"). Same thing to reset.
Moreover, when you test $("tax").value = 0 I think you mistyped = instead of ==.
Other issues...
I think you mean
if ($("#tax").val() == 0)
Note:
Uses the correct selector #
Uses the jQuery val() function. The jQuery object doesn't have a value property.
Compares to 0 using loose checking, though personally I would write the line as
if (+$("#tax").val() === 0)
Please help me out guys i have tried to figure this out for ages now. The problem i seem to have is second web page pops up right as the first one does even though it should pop up only after variable x is declared, here is my code try it out and you will see.
<script>
function myFunction()
{
var x;
var r=confirm("By pressing ok you are confirming your username and password");
if (r==true)
{
x="Thank You for Registering!";
}
else
{
x="You pressed Cancel!";
}
document.getElementById("demo").innerHTML=x;
}
var nextpage;
if (x = "Thank You for Registering!"){
window.open('Password.html');
}//end if
</script>
see the problem is that "password.html" is opened right as this page is opened when is should only open after x="thank you for Registering"
Please guys i will be forever grateful if someone figures this one out.
When you do x = "Thank You for Registering!" you are assigning that string to x. After you do the assignment, it tests if the value is "true-ish," which it is. Instead of = (assignment), you want == (comparison).
You are not comparing the variable value correctly. You are doing X= "" which calls assignment not comparison. So for compare a value you need to put this in this way
x == "Thank You for Registering!"
== will do the job. Keep these things in practise.
Learn more here.
'=' is an assignment operator whereas '==' is a comparison operator.
for example.if you write something like this.
if(x=1)//always true
{
}
else //this part will never be executed
{
}
then the above code will always result in true so else part will never be executed,you also are facing the same problem.so
Replace '=' with '=='
if (x == "Thank You for Registering!"){
window.open('Password.html');
}
I have a case where I have a bunch of text boxes and radio buttons on a screen all built dynamically with various DIVs. There are onblur routines for all of the text boxes to validate entry, but depending on the radio button selection, the text box entry could be invalid when it was valid originally. I can't use onblur with the radio buttons because they could go from the radio button into one of the text boxes that was made invalid and create an infinite loop since I'm putting focus into the invalid element. Since each text box has its own special parameters for the onblur calls, I figure the best way to do this is to call the onblur event for the textboxes when the form gets submitted to make sure all entry is still valid with the radio button configuration they have selected. I also need it to stop submitting if one of the onblur events returns false so they can correct the textbox that is wrong. This is what I've written:
for (var intElement = 0; intElement < document.forms[0].elements.length; intElement = intElement + 1)
{
if (document.forms[0].elements[intElement].name.substr(3) == "FactorAmount") // The first 3 characters of the name are a unique identifier for each field
{
if (document.forms[0].elements[intElement].onblur())
{
return false;
break;
}
}
}
return true;
I originally had (!document.forms[0].elements[intElement].onblur()) but the alert messages from the onblur events weren't popping up when I had that. Now the alert messages are popping up, but it's still continuing to loop through elements if it hits an error. I've stepped through this with a debugger both ways, and it appears to be looping just fine, but it's either 1) not stopping and returning false when I need it to or 2) not executing my alert messages to tell the user what the error was. Can someone possibly help? It's probably something stupid I'm doing.
The onblur method that is getting called looks like this:
function f_VerifyRange(tagFactor, reaMin, reaMax, intPrecision, sLOB, sIL, sFactorCode)
{
var tagCreditOrDebit;
var tagIsTotal;
var tagPercentageOrDecimal;
eval("tagCreditOrDebit = document.forms[0]." + tagFactor.name.substr(0,3) + "CreditOrDebitC");
eval("tagIsTotal = document.forms[0]." + tagFactor.name.substr(0,3) + "IsTotal");
eval("tagPercentageOrDecimal = document.forms[0]." + tagFactor.name.substr(0,3) + "PercentageOrDecimal");
if (tagPercentageOrDecimal.value == "P")
{
reaMax = Math.round((reaMax - 1) * 100);
reaMin = Math.round((1 - reaMin) * 100);
if (parseFloat(tagFactor.value) == 0)
{
alert("Please enter a value other than 0 or leave this field blank.");
f_SetFocus(tagFactor);
return false;
}
if (tagIsTotal.value == "True")
{
if (tagCreditOrDebit.checked)
{
if (parseFloat(tagFactor.value) > reaMin)
{
alert("Please enter a value less than or equal to " + reaMin + "% for a credit or " + reaMax + "% for a debit.");
f_SetFocus(tagFactor);
return false;
}
}
else
{
if (parseFloat(tagFactor.value) > reaMax)
{
alert("Please enter a value less than or equal to " + reaMin + "% for a credit or " + reaMax + "% for a debit.");
f_SetFocus(tagFactor);
return false;
}
}
}
}
return true;
}
EDIT: I think I've figured out why this isn't working as expected, but I still don't know how I can accomplish what I need to. The line below:
if (!document.forms[0].elements[intElement].onblur())
or
if (document.forms[0].elements[intElement].onblur())
is not returning what the single onblur function (f_VerifyRange) is returning. Instead it is always returning either true or false no matter what. In the first case, it returns true and then quits and aborts the submit after the first textbox even though there was no error with the first textbox. In the second case, it returns false and runs through all the boxes. Even though there might have been errors (which it displays), it doesn't think there are any errors, so it continues on with the submit. I guess what I really need is how to get the return value from f_VerifyRange which is my onblur function.
This question is a bit too involved for me at this time of the night, but I will give you this bit of advice:
eval("tagCreditOrDebit = document.forms[0]." + tagFactor.name.substr(0,3) + "CreditOrDebitC");
This can be written in a MUCH better way:
tagCreditOrDebit = document.forms[0][tagFactor.name.substr(0,3) + "CreditOrDebitC"];
In javascript, anywhere where you can use dotted syntax, you can use square brackets.
document.body;
document['body'];
var b = 'body';
document[b];
Also, think about giving your forms some sort of identifier. I have no clue at all why document.forms[0] was the standard way to address a form for so long... if you decide to place another form on the page before this one, then everything will break!
Other ways to do it include:
// HTML
<form name="myFormName">
// Javascript
var f = document.myFormName;
or
<form id="myFormId">
var f = document.getElementById("myFormId")
You´re not getting any success with if (!...onblur()) because the return of onblur() is always undefined when used directly. OnBlur() is a Event Handler Function. Like you descovered, you have to create a workaround.
I ended up solving this with a global variable. I originally set a value g_bHardEditsPassed to true assuming we will have no errors. Then in f_VerifyRange, everytime I return a value, I put a line before it to set the g_bHardEditsPassed variable to match. Then I modified the loop to look like this...
g_bHardEditsPassed = true;
for (var intElement = 0; intElement < document.forms[0].elements.length; intElement = intElement + 1)
{
if (document.forms[0].elements[intElement].name.substr(3) == "FactorAmount")
{
document.forms[0].elements[intElement].onblur()
if (!g_bHardEditsPassed)
{
g_bHardEditsPassed = true;
return false;
}
}
}
return true;
Thanks for everyone's suggestions. I'm sure that the jQuery thing especially will be worth looking into for the future.
First, for the love of god and all that is holy, stop writing native javascript and help yourself to some of that jQuery :)
Second, start using a validation framework. For jQuery, jQuery Validate usually works really well. It supports things like dependencies between different fields, etc. And you can also quite easily add new rules, like valid ISBN numbers, etc.
Edit: As for your code, I'm not sure that you can use onunload for this, as at that point there's no way back, you can't abort at that point. You should put this code on the onsubmit event instead.