Search code examples
javascriptrequired

Don't execute a function until a HTML <input> required Attribute is TRUE


I want to know if there's a way to execute a JS function until a required attribute returns TRUE. And if it's possible, how.

I have those required inputs:

<input type="text" name="sen1" placeholder="Nombre" required>
<input type="number" name="tre_1" placeholder="Segundos" required>

And I send the value with another input and a function:

<input type="button" name="Ok" value="Guardar" onclick="Dale();">

Finally, this is my function:

function Dale(){

var number1 = [];

number1.push(document.myform.sen1.value);
number1.push(document.myform.log1.value);
number1.push(document.myform.p_v1.value);
number1.push(document.myform.tre_1.value);
number1.push(document.myform.sds1.value);
number1.push(document.myform.pan1.value);

doSend( document.myform.start.value );

doSend( number1 );

doSend( document.myform.end.value );
}

Solution

  • You have to change three things:

    1) change your submit button into type="submit"

    2) remove onClick from submit button

    3) add onSubmit on <form> tag

    After that HTML5 validation should work as expected and do not call your onSubmit function unless conditions are not met.

    If you do not want to make above changes, you have to implement your own validation inside Dale function, checking if inputs are empty or not.