NotRocketScientist NotRocketScientist - 1 month ago 11
Javascript Question

enable/disable submit button based in input field (filled/not filled)

what I am missing in this code, If I just want the input submit button to enable/disable/enable.. as long as I fill or unfill the input text?
sorry I am doing my best to learn javascript...can anyone help me fix this code?

<form name="myform" method="post">
<input onkeyup="checkFormsValidity();" id="input_id" type="text" name="input_name" value=""/>
<input type="submit" name="submit_name" value="OK" class="submit_class" id="SubmitButton"/>
</form>

<script>
var sbmtBtn = document.getElementById("SubmitButton");
sbmtBtn.disabled = true;

function checkFormsValidity(){
var myforms = document.forms["myform"];
if (myforms.checkValidity()) {
sbmtBtn.disabled = false;
} else {
sbmtBtn.disabled = true;
}
}
</script>


This is the fiddle: https://jsfiddle.net/1zfm6uck/

Am I missing declaring onLoad mode or something like this?
Thanks!

Answer
function checkFormsValidity(){

needs to be change to:

checkFormsValidity = function(){

Personally I wouldn't check validity that way, but in terms of making your code work without error, that will do it.

Edit: Also add required="required" to the input.