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!

2 Answers 2

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).

Sign up to request clarification or add additional context in comments.

2 Comments

thanks, so basically I just missed adding required="required"
In your computer/server you probably missed the required, yeah.
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.

2 Comments

okey thanks, that does the trick. But have you noticed that if I delete/unfill the input text the submit button does not go back to the disabled mode? How can we fix that?
Add required="required" to the input

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.