<form class="container" style="margin: 30px;">
<input type="text" class="first-name" placeholder="first name">
<input type="text" class="first-name" placeholder="last name">
<button type="button">next</button>
</form>
<form class="container" style="margin: 30px;">
<input type="radio" id="age1" name="age" value="30">
<label for="age1">0 - 30</label><br>
<input type="radio" id="age2" name="age" value="60">
<label for="age2">31 - 60</label><br>
<input type="radio" id="age3" name="age" value="100">
<label for="age3">61 - 100</label><br><br>
<input type="submit" value="Submit">
</form>
I am creating a multi-step form and want the "Next" and "Submit" buttons to be active only when the input field are filled or selected. Can you help me with the right JS code?
3
Answers
Use
.value
to check whether is undenied or not, if it’s undenied, set thebutton.disable=true
, elsebutton.disable=false
. If the radio input, you can useinput.check
and find out whether the input is selected.You might try an approach like this – please see the comments throughout the code to indicate what is happening at that stage.
Extending my answer from here, the easiest way to do this would be to add a
change
event to the form. Then, for each button, you can check if the inputs have been filled out, and set the button’s.disabled
accordingly. I’ve modified the original form to use some radios and multiple inputs for example purposes.To check if an
<input>
has been filled out, just take its.value
,.trim()
the string to get rid of unnecessary whitespace, then check if its length is 0. For radios, you can use a query selector to check if there are any elements of the radio’s name that have thechecked
attribute. If there are not, then it will returnnull
. To combine these, just use the boolean OR (||
)