0

I am trying to validate the user input in my the case the input is the color name entered by user, here is the code snippet

let valideColor = false;

do{

      const selected_color = $('#SelectedColorPicker').val();

        if (selected_color === '') {
            console.log('Not valid')
        }
        else {
            validColor = true;
        }

}while(!validColor)

the code above produces an infinite loop leading my browser to crash, I would appreciate if anyone can tell me where the problem is .

3
  • 2
    You could use required attribute, or an event, more like change event to check that. And change const to let or var... Commented Sep 5, 2019 at 20:01
  • What is your ultimate goal? Commented Sep 5, 2019 at 20:06
  • the goal is to display a modal box instead of console.log when the input is not valid Commented Sep 5, 2019 at 20:08

3 Answers 3

4

You've got an infinite loop because you're running code continuously in a loop, not giving the user a chance to enter any input - when user input would be the only way to make validColor true and therefore break out of the loop.

A loop is totally the wrong approach here. You only need check at certain points, presumably when the user tries to submit whatever form this input is part of. So you should do something like this:

$("#idOfMyForm").submit(function(e) {
    const selected_color = $('#SelectedColorPicker').val();

    if (selected_color === '') {
        console.log('Not valid');
        e.preventDefault();
    }
});

to warn the user (although of course a mere console.log will not be noticeable to anyone who doesn't have the browser console open, so not the vast majority of users), and stop the form submitting.

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

Comments

0

You can use this

let validColor = false
  $('#SelectedColorPicker').on("change",function(){
      if ($(this).val() === '') {
        console.log('Not valid')
      }
      else {
        validColor = true;
      }

  });

Comments

0

You can use input

$('#SelectedColorPicker').on("input", function() {
   var selected_color = this.value;
   console.log(selected_color);
});

Comments

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.