JFM
JFM

Reputation: 3

How to get on fly while text input is completed

I need to get (on fly, not while submitting the form) if an input text is completed or not, to have a javascript confirmation on submitting button.

The input is <input type="text" name="first" value="" />

The submitting button is "<input type="submit" name="submit" />

In this button, I would like a JavaScript script to confirm popup when the field "first" is empty, like onclick="return(confirm('Are you sure ?')" I don't want to have any confirm while the field is filled.

I know how to control after submitting button, but not before. I think I have to use AJAX to pass a variable through the form to get the correct value, but I don't know to achieve this.

Upvotes: 0

Views: 300

Answers (1)

Nata Khitsan
Nata Khitsan

Reputation: 288

You can add more code to onclick handler (check the text and if it's empty return confirmation state).

document.getElementById('submitButton').onclick = function() {
  var text = document.getElementById('textInput').value;
  if (!text) {
    // run only text is falthy (empty string, null, undefined etc)
    return confirm('Are you sure ?');
  }
}
<form>
<input type="text" name="first" id='textInput' value="" />
<input type="submit" name="submit" id='submitButton'/>
</form>

More variants how to add click handler you can find here:

Upvotes: 1

Related Questions