1

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!

Dekel
  • 60,707
  • 10
  • 101
  • 129

2 Answers2

3

Actually - if it wasn't a jsfiddle example your code would work great:

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;
  }
}
input[type='submit']:disabled{
 color:red;
}
<form name="myform" method="post">
<input onkeyup="checkFormsValidity();" id="input_id" type="text" name="input_name" value="" required="required" />
<input type="submit" name="submit_name" value="OK" class="submit_class" id="SubmitButton"/>
</form>

The problem was the jsfiddle put your javascript code inside a clousure, so the checkFormsValidity function is not available in the scope of your input.

I added a required="required" to your input to make sure it's a required field (which will affect the checkValidity() of your form).

Dekel
  • 60,707
  • 10
  • 101
  • 129
1
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.

K Scandrett
  • 16,390
  • 4
  • 40
  • 65