'My button needs to update after an input field

I have the following problem, I made a form using HTML with some input fields. I also made the submit button disabled using the following JS code:

  if(document.forms['form'].inputfield1.value == "")
    {
    document.forms[0].submit.disabled=true;
    }
    else {  
    document.forms[0].submit.disabled=false;
    }

This works fine, whenever I load the page the button is disabled, but when I fill in something it doesn't get enabled.

But whenever I place a value in my input field like so:

<input type="text" name="inputfield1" size="3" maxlength="3" value="12345">

And I load the page the button is enabled, proving the JS code works just fine.

I don't know if there is anyway to make the button refresh after someone used an input field or anything like that.

I'm completely new to JS and PHP, any help is greatly appreciated!



Solution 1:[1]

You need to use a javascript event to detect when the value changes and to run the validation. I would suggest onkeyup for this as you will likely want it as the user is typing.

This can be done with javascript as follows...

Create an onload event to trigger when the page loads, this will register the events handlers for your input and call the initial check to set the default state:

window.onload = function(){
    document.getElementsByName("inputfield1")[0].onkeyup = validateForm;
    validateForm();
};

Then your function to do the validation:

function validateForm(){
    if(document.forms['form'].inputfield1.value == "")
    {
        document.forms[0].submit.disabled=true;
    }
    else {  
        document.forms[0].submit.disabled=false;
    }
}

Solution 2:[2]

You can use onkeyup function to do this simply

<input type="text" name="inputfield1" size="3" maxlength="3" value="12345" onkeyup='check()'>

function check() {
  if(document.forms['form'].inputfield1.value == ""){
    document.forms[0].submit.disabled=true;
}
else {  
    document.forms[0].submit.disabled=false;
}
}

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1
Solution 2 Ramesh