Javascript Confirm with action? - javascript

wording this question was hard, but here i go. ok, i am using code from this site:
http://www.switchonthecode.com/tutorials/javascript-tutorial-getting-user-input-with-prompt-and-confirm
<script type="text/javascript">
function confirmInput()
{
var ans = confirm("Install a virus and delete all your files?");
alert(ans ? document.getElementById('level').value = "0";
: "If no, do nothing");
}
</script>
<input type="button" onclick="confirmInput()" value="Show me the Question!" />
I have even tried to replace the Text for the answer with the actions, but i get nothing.
How do i add a action to the answer, so when it is yes, i do something, and when no i do not.

I think this is what you are looking for:
function confirmInput()
{
if(confirm("Install a virus and delete all your files?"))
document.getElementById('level').value = "0";
}

there is a syntax error in your code here:
alert(ans ? document.getElementById('level').value = "0"; // this semicolon is invalid
: "If no, do nothing");
It executes till this semicolon and that terminates. Check your console, there should be an error message.
Another thing is that ?: operator can only return a value. It shouldn't contain operations, only values or function, which returns the value.

Related

javascript compute mistake (calculator)

I need to make a calculator using JavaScript, HTML and CSS. Everything worked out fine until I came to coding the compute (=) button.
This is my HTML:
<input type="button" value=" = " onclick="compute()">
This is my JS:
function compute() {
var input_var = document.getElementById('input');
ans = Math.floor(+eval(input_var.value));
document.getElementById('answer').value = '=' + 'ans';
}
If anyone that knows how to solve what's wrong, I would greatly appreciate it if you could reply.
First of all, you should post the whole code to get accurate solution!
Probably these could be some of the errors:
Set id attribute of your = button with value "input"
3rd line should be: ans = Math.floor(eval(+input_var.value));
4th line should be: document.getElementById('answer').value = '=' + ans; as StaticBeagle has also mentioned.
You should be lucky that you made the mistake to put the variable in quotes. That's why you don't get a value other than the literal string =ans(maybe, we don't know as you didn't post all code that's needed to give a better answer).
Back to why you're lucky.
Never use eval! eval is evil. (Unless you know what you do, but you don't the next couple of years). To parse a number, you'd use Number(input_var.value).
The next error is that you create a global variable by omitting one of var, let, const for your ans declaration.
The next thing you shouldn't do is to use inline javascript. We use eventListener instead. As said before, it's impossible to answer more specific as your question lacks too many details - however I'll show you how you get a value by pressing a button in the console.
document.getElementById('foo').addEventListener('submit', e => {
// prevent submitting the form (I guess another error in your code)
e.preventDefault();
const value = Number(document.getElementById('input').value);
console.log('The value is: ' + value);
}, false);
<form id="foo">
<input type="number" id="input">
<input type="submit" value=" = ">
</form>
Not sure if ans is a local or global variable, but if its intention is to be a local variable then you should have it like this:
var ans = Math.floor(eval(+input_var.value));
Also, because you're setting the value of your element to '=' + 'ans' you're actually setting it to the actual string 'ans'. If you want to refer to what ans is you should write it like this:
document.getElementById('answer').value = '=' + ans;

Slicing a string from a textbox

I am trying to take a string entered by user from a textbox. Check the length of that string and if the string is over a given number perform the slice operation on it.
Here's what I came up with but my code does nothing. Checked console, no errors given.
html:
<form id="slice">
Enter a pharse:<input type="text" id="text_box_2"><br>
<input type="button" value="slice" onclick="Slice()">
Result: <input type="text" id="slice_result"><br>
</form>
Javascript function:
function Slice(){
var UserString = document.getElementById("text_box_2").value;
var UserStringValue = UserString.length;
var Result = Userstring.slice(1,6);
if (UserStringValue > 6){
document.getElementById("Slice_result").value = Result;
}
else{
alert("Please enter a longer phrase.")
}
}
what or where did I go wrong?
Be mindful of case-sensitivity.
This:
var Result = Userstring.slice(1,6);
Should be using UserString (capital "S") as defined earlier in your code.
Next, the input ID should be all lowercase, slice_result, to match to HTML, but your code uses different casing:
document.getElementById("Slice_result")
Here's a working JSBin with these fixes.
EDIT: As JaromandaX mentioned in the comments, if you want to take the first 6 characters you should use slice(0, 6).
from cursory reading of your code. it seems caused by this line
var Result = Userstring.slice(1,6);
and also this one
document.getElementById("Slice_result").value = Result
it should be
var Result = UserString.slice(1,6);
and
document.getElementById("slice_result").value = Result
Usually use of the following
var Value = $('#input_id').val();
will pull the requested information for you.
You can also set up arguments for your slice function and pass in the value when you run onclick();
I'd also note that slice() is a current js function, though your implentation with the capital 'S' is some what different, it may be better practice to change that name a bit.

Issue with an infinite loop?

I'm having some issues with an accidental infinite loop. I've just been starting with javascript, and so I've been trying to make a simple game as practice. I keep getting an infinite loop, and I can't tell why. I'm fairly sure it's not a syntax error, since the console isn't telling me about any. Here's the code where the problems are happening:
HTML:
<input id="lemonadePrice" class="buytextbox" placeholder="Lemonade price">
<input class="submit" onclick="begin();" type="submit" value="Begin!">
JavaScript:
while (isNaN(lemonadePrice)) {
document.getElementById("introduction").innerHTML="Uh-oh! Your lemonade price is not a
number!Please remove any words or symbols like '$'.";
lemonadePrice = document.getElementById("lemonadePrice");
}
Here's a link to the full code: jsfiddle
This might be because of your while() loop. What might be happening is that the while loop goes on infinitely while this isNAN(lemonadePrice) returns true, and this is what happens in your case, given that you say it runs infinitely.
You can try using an if(). Since .getElementById of "lemonadePrice" will not be returning a number, the isNAN() would be evaluating to true all the time. isNAN() simply means "is not a number". If you think for a second, you know where the bug is.
I think you are looking to get the value of "lemonadePrice", so instead of just getting the element, you should also consider pulling in the value that lies inside it. I do not see this in your code but it would simply be this DOM: var value = document.getElementById(id).value;
I think you want an if instead of while
The definition while taken from wikipedia
In most computer programming languages, a while loop is a control flow
statement that allows code to be executed repeatedly based on a given
boolean condition. The while loop can be thought of as a repeating if
statement.
It means while loop will repeat under condition that inside the brackets. In this case, what you need is a conditional statement (if())
If will be executed only once. While will be executed repeatedly until the condition is false. In your case, the condition will be always true. That is why you ended up in infinite loop.
See code below
if (isNaN(lemonadePrice)) {
document.getElementById("introduction").innerHTML="Uh-oh! Your lemonade price is not a
number!Please remove any words or symbols like '$'.";
lemonadePrice = document.getElementById("lemonadePrice");
}
If we assume begin() is basically this:
function begin(){
var lemonadePrice = document.getElementById("lemonadePrice");
while (isNaN(lemonadePrice)) {
document.getElementById("introduction").innerHTML="Uh-oh! Your lemonade price is not a number!Please remove any words or symbols like '$'.";
lemonadePrice = document.getElementById("lemonadePrice");
}
}
then your loop will never have a chance to exit, since lemonadePrice is always set to the "value" of the lemonadePrice DOM element; that means lemonadePrice will always be NaN, so the loop is infinite. Like others have already mentioned, you need to use an if() statment instead of a loop, and remove the last line. You also want to look at the value of the element:
function begin(){
var lemonadePrice = document.getElementById("lemonadePrice").value;
if(isNaN(lemonadePrice)) {
document.getElementById("introduction").innerHTML="Uh-oh! Your lemonade price is not a number!Please remove any words or symbols like '$'.";
}
}
You better use onsubmit and prevent form submit if not valid.
Its also better to use regular expression to check if its valid float number.
<!DOCTYPE html>
<html>
<head>
</head>
<body>
<form action="yourfile.php" method="post" onsubmit="validate();">
<input id="lemonadePrice" class="buytextbox" placeholder="Lemonade price" /> <span id="lemonade_error"></span>
<br>
<input class="submit" type="submit" value="Begin!" />
</form>
<script type='text/javascript'>//<![CDATA[
function validate() {
var lemonade_price = document.getElementById("lemonadePrice").value;
if (lemonade_price.match(/\d+\.*\d*/i)){
document.getElementById("lemonade_error").innerHTML = "Not valid.";
if (event.preventDefault){
event.preventDefault();
} else {
event.returnValue = false; // for IE as dont support preventDefault;
}
return false;
}
return true;
}
//]]>
</script>
</body>
</html>
Code here : http://jsfiddle.net/Pxuey/5/

What is wrong with this form validation?

Basically, what I am trying to do is alert the same message if one of the seven text boxes in my form is empty. I have been playing around with it a lot, but now I am starting to feel exasperated; help! Sometimes I get a function validepiste() is not defined error and sometimes I don't get an error, but there is an alert even if all the boxes have something in them. I think the error might be due to an incorrect use of the || (or) operator, or the length bit. Here is the function (which is within the head tags):
<script type="text/javascript">
function validatepiste()
{
// all form fields must be filled in
var a= document.piste.nom.length;
var b= document.piste.email.length;
var c= document.piste.numtel.length;
var d= document.piste.adresse.length;
var e= document.piste.ville.length;
var f= document.piste.length;
var g= document.piste.travaux.length;
if (a||b||c||d||e||f||g==0){
alert("Vous devez remplir toutes les cases.");
return false;
}
return true
}
</script>
And the call to that function which is in the html:
<input type="submit" name="Submit" value="Envoyer" onClick="return validatepiste()"/>
Thank you!
There are two issues with your code that I can see.
First Problem
It appears you're trying to access a length property directly on a form element (which doesn't exist). What you really want to do is access the length of a form value. So instead of this:
var a= document.piste.nom.length;
Do this:
var a= document.piste.nom.value.length;
I didn't see this at first but #Napster mentioned it in his answer. So thank him.
Second Problem
You're if statement has some bad logic. Try the following instead.
if (a==0||b==0||c==0||d==0||e==0||f==0||g==0) { ... }
Your original expression was asking the following...
If a is truthy,
or b is truthy,
or c is truthy,
or d is truthy,
or e is truthy,
or f is truthy,
or g is equal to 0
then show the alert.
The only scenario which would not have triggered the alert using your existing code would be if all the fields were blank except for g.
You can read an article about what truthy means if you like.
You should test each variable's value independently, i.e.:
if (a==0||b==0||c==0||e==0||f==0||g==0)
Your code is fine. Only you have to add a single thing between where the variable is defined.
Your code:
var a= document.piste.nom.length;
var b= document.piste.email.length;
var c= document.piste.numtel.length;
Modify it by
var a= document.piste.nom.value.length;
var b= document.piste.email.value.length;
var c= document.piste.numtel.value.length;
same for all the variable, add value in between them. And your code will run.
First you are not using your || operator correctly. it is only doing comparison of g==0. You are getting always a message because browser takes if(a) as a has some value. So do comparison differently for each varriable like this
if (a==0||b==0||c==0||d==0||e==0||f==0||g==0){
and second use else condition to return true. It always return true because it is not having else condition. return true always executes. and put semicolon after return true;
I think its enough if u give
onsubmit="validatepiste()"
return is not required.
Firstly try:
if (a||b||c||d||e||f||g==0){
alert("Vous devez remplir toutes les cases.");
return false;
}
else{
return true;
}
secondly try
<input type="submit" name="Submit"
value="Envoyer" onclick="validatepiste()"/>
Thirdly:
var a= document.getElementByID('nom').length;
assuming your form fields have IDs as well as names

Javascript not working in firefox

I have a PHP form validation function that I developed in chrome and now will not work in firefox or Opera.
The function checks to see if a section of the form is blank and shows and error message. If there is no error then then the form submits through document.events.submit();
CODE:
function submit_events()
{
//Check to see if a number is entered if the corosponding textbox is checked
if (document.events.dj_card.checked == true && dj_amount.value==""){
//Error Control Method
//alert ('You didn\'t enetr an Amount for DJ\'s Card!');
var txt=document.getElementById("error")
txt.innerHTML="<p><font color=\"#FF0000\"> You didn\'t enetr an Amount for DJ\'s Card!</font></p>";
window.document.getElementById("dj_card_label").style.color = '#FF0000';
//Reset
window.document.getElementById("company_amount_label").style.color = '#000000';
window.document.getElementById("own_amount_label").style.color = '#000000';
}else{
document.events.submit();
}
The document.events.submit();does work across all my browsers however the check statements do not.
If the box is not ticked the form submits. If the box is ticked it does not matter whether there is data in the dj_amount.value or not. The form will not submit and no error messages are displayed.
Thanks guys.
Here are some things I noticed. Not sure if it will solve the problem, but you need to fix some of these; some of them are just observations.
dj_amount is not declared nor referenced; my guess is you mean documents.events.dj_amount
You should put a ; at the end of every statement in javascript, including the end of var txt = document.getElementById("error")
You don't need to escape the string in the txt.innerHTML line; you only need to escape like quotes, such as "\"" or '\'', not "'" or '"'
You don't need the window.document referenced; document will do in almost all cases
EDIT - As Guffa points out, FONT is an old and deprecated element in HTML. It's not the cause of your problems, but modern markup methods mean you don't need it. Consider omitting and applying the style to the paragraph tag instead.
See edits below.
function submit_events() {
//Check to see if a number is entered if the corosponding textbox is checked
if (document.events.dj_card.checked == true && document.events.dj_amount.value == "") {
//Error Control Method
//alert ('You didn't enetr an Amount for DJ\'s Card!');
var txt = document.getElementById("error");
txt.innerHTML = "<p style=\"color: #FF0000;\"> You didn't enter an Amount for DJ's Card!</p>";
document.getElementById("dj_card_label").style.color = '#FF0000';
//Reset
document.getElementById("company_amount_label").style.color = '#000000';
document.getElementById("own_amount_label").style.color = '#000000';
} else {
document.events.submit();
}
}
Consider Firebug so that you can see and log to console javascript errors and messages:
http://getfirebug.com
I believe one of the above answers would solve your problem. For future reference, although it might not be suitable for your project, please know that writing forms and javascript feedback is much easier and faster when you use a library like jQuery.
To have minimal changes in code, just add this line before the first if statement:
var dj_amount = document.forms["events"].elements["dj_amount"];
However your code need serious optimization let us know if you're interested.
Edit: here is the optimization. First the "small" things - instead of whatever you have now for "error" container, have only this instead:
<p id="error"></p>
Now add this CSS to your page:
<style type="text/css">
#error { color: #ff0000; }
</style>
This will take care of the red color, instead of hard coding this in the JS code you now control the color (and everything else) from within simple CSS. This is the correct approach.
Second, right now you are submitting the form as response to onclick event of ordinary button. Better approach (at least in my humble opinion) is having submit button then overriding the form onsubmit event, cancelling it if something is not valid. So, first you have to change the function name to be more proper then have proper code in the function. Cutting to the chase, here is the function:
function ValidateForm(oForm) {
//declare local variables:
var oCardCheckBox = oForm.elements["dj_card"];
var oAmoutTextBox = oForm.elements["dj_amount"];
//checkbox cheched?
if (oCardCheckBox.checked) {
//store value in local variable:
var strAmount = oAmoutTextBox.value;
//make sure not empty:
if (strAmount.length == 0) {
ErrorAndFocus("You didn't enter amount for DJ's Card!", oAmoutTextBox);
return false;
}
//make sure it's numeric and positive and not too big:
var nAmount = parseInt(strAmount, 10);
if (isNaN(nAmount) || nAmount < 1 || nAmount > 1000000) {
ErrorAndFocus("DJ's Card amount is invalid!", oAmoutTextBox);
return false;
}
}
//getting here means everything is fine and valid, continue submitting.
return true;
}
As you see, when something is wrong you return false otherwise you return true indicating the form can be submitted. To attach this to the form, have such form tag:
<form ... onsubmit="return ValidateForm(this);">
And instead of the current button have ordinary submit button:
<input type="submit" value="Send" />
The code will be called automatically.
Third, as you can see the function is now using "helper" function to show the error and focus the "misbehaving" element - this makes things much more simple when you want to validate other elements and show various messages. The function is:
function ErrorAndFocus(sMessage, element) {
var oErrorPanel = document.getElementById("error");
oErrorPanel.innerHTML = sMessage;
document.getElementById("dj_card_label").style.color = '#FF0000';
document.getElementById("company_amount_label").style.color = '#000000';
document.getElementById("own_amount_label").style.color = '#000000';
}
Last but not least, the "new" code also makes sure the amount is positive number in addition to check its existence - little addition that will prevent server side crash.
Everything else is pretty much self explanatory in the function: naming conventions, using local variables.... most important is have as little redundancy as possible and keep the code readable.
Hope at least some of this make sense, feel free to ask for clarifications. :)
You should bring up the error console so that you see what the error actually is.
Lacking that information, I can still make a guess. Try some less ancient HTML code; the parser can be picky about code you add to the page using innerHTML:
txt.innerHTML="<p style=\"color:#FF0000\"> You didn\'t enetr an Amount for DJ\'s Card!</p>";

Categories