0

I am working on an assignment for school which uses javascript to create functions using forms. I have created the function and does what I need it to do, but to some extent. The function i am creating is to check if a text box follows the constraints i am setting for it using the javascript function. if the user enters a number that is outside of the range, an alert box will show up saying to enter a number between the specified range. I know a lot of people will be using if statements, but i wanted to try a different approach. I am trying with while and do...while statements. I have the function created, but everytime the alert box shows up and i press ok, the alert still keeps showing up. Is there a way from my coding to have it so the alert box does not appear after everytime i click ok? My code:

function checkPrice(formData)
{

 while(!(formData.stickerPrice.value > 0) || (formData.stickerPrice.value < 100000))
 {
    alert("Enter a value between 0 andd 100000");
    setTimeout (function()
    {
        formData.stickerPrice.focus();
    })
 }
}
1
  • since you want the alert to happen only "if" certain conditions hold, i don't believe you will be able to avoid having an "if" statement somewhere in your code.... Commented Apr 22, 2013 at 16:04

1 Answer 1

1

Just change it from while to if. That way it won't continuously loop. The while loop's condition will continue to be true until you break away from the Javascript and let the user type something in. The condition will always be true once it's entered, since nothing in the condition changes before the next iteration.

Sign up to request clarification or add additional context in comments.

7 Comments

yea, i had already coded it that way. but i was just trying to see if there was another way to code this without using an if statement?
@bobGlenn I don't think so. The while's condition will always be true since the values never change. You need to let the user type in a new value and then re-evaluate the situation.
yea, i would like to let the user type in a new value, but the alert box continuously shows up when the user clicks ok
@bobGlenn Right, so you can't use a while loop for something like this. How are you calling checkPrice anyways?
yea, so i guess i will have to use an if statement then. Like i said, i wanted to try and code this differently than everyone. i am calling checkPrice using the onblur event handler
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.