0

The code is suppose to validate an input and then execute a function when a button is clicked, but it is not working and the console does not suggest why. The only difference is that when you take away toString() on input it says it is not a function. This is my first big project at university and not really sure which part is wrong?

function check(evt){
    const value = input.value;

    if (!value) {
      input.dataset.state = ''
      return
    }

    const trimmed = input.toString().trim();

    if (trimmed) {
      input.dataset.state = 'valid'
    } else {
      input.dataset.state = 'invalid'
    }
  }

Function to be executed

function addRow() {
something...
}

validating if this function is true then execute this function.

function validate(){
         if(check()){
            addRow();
            }
}
document.getElementById('input').addEventListener('input', check);
document.getElementById('btn').addEventListener('click', validate);

Html

 <input type="text" id="input" class="input" autofocus autocomplete="off" placeholder="Add items in your list..">
 <button id='btn' class="add">+</button>

4
  • At input.toString().trim();, what value is input? And what are you trying to do there? Commented Apr 24, 2020 at 13:27
  • Input should be a string without spaces Commented Apr 24, 2020 at 13:31
  • Trim will only strip value from the start and on the end: " test test "=> "test test" Commented Apr 24, 2020 at 13:33
  • Yes that is what I need, it can be string with space in the middle Commented Apr 24, 2020 at 13:35

1 Answer 1

1

Although the input variable is not declared in your code, I assume that it is supposed to represent the <input type="text"> element.

With the validation step you should validate the value of the input, not the input itself.

But your logic is still missing something. The else statement will never be reached. If the value is empty then the state will be set to '' and the function is stopped. If there is a value, and it has been trimmed, then you're always left with a string with a value in it and there for your value is truthy. So the else would not make without an if statement which would allow the value to be false when the validation is incorrect.

function check(evt){
  const value = input.value;

  if (!value) {
    input.dataset.state = ''
    return
  }

  // Trim the value.
  const trimmed = value.trim();

  if (trimmed) {
    input.dataset.state = 'valid'
  } else {
    input.dataset.state = 'invalid'
  }
}
Sign up to request clarification or add additional context in comments.

1 Comment

Had to scrap it and use Jquery function for the button, thanks for the effort though

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.