I am trying to link the submit
button with the option
list. If there is any one item
of the from the option
list of both list got selected from the drop down list then only the submit
button will enabled.
Example – User have to select one option from category {ABC,DEF,GHI} and one option from category {XYZ,MNO,PQR} then the tag submit will activate. If one option from these two was missing then tag submit
const dropdown1 = document.getElementById("dropdown");
const dropdown2 = document.getElementById("dropdown");
const submitbutton = document.getElementById("btn");
dropdown1.addEventListener("input", function() {
submitbutton.disabled = dropdown1.value = dropdown2.value === "";
});
<form>
<select id="dropdown1">
<option>ABC</option>
<option>DEF</option>
<option>GHI</option>
</select>
<select id="dropdown2">
<option>XYZ</option>
<option>MNO</option>
<option>PQR</option>
</select>
<input type="submit" id="btn" disabled>
</form>
willn’t activate.
Find below code.
Try with above code but not happen.
5
Answers
Update your javascript code, the code has Incorrect Assignment in Condition, incorrect getElementById. Here is the code that will enable button only when both dropdown are selected.
The code has several errors. Below is a proposal about how to fix it.
document.getElementById
.Array.prototype.forEach
to add an event listener to each selector.disabled
attribute.select
options don’t explicitly include a value attribute. This doesn’t follow the "best practices" but has the advantage that the logic could later use other values to enable / disable the button without setting the value properties for the option elements.Below is the same code with a couple of changes.
value
property to satisfy the "best practices" evangelists.This is a workaround that you may try:
OUTPUT
The issue is that you are using wrong operator in the event listener logic.
Ensure the dropdown elements are referenced correctly with dropdown1 and dropdown2 IDs.
and in this script the updateSubmitButtonState function checks whether either dropdown has not selected a value (""). The submit button is disabled if either dropdown is unselected.
the normal HTML5 way for coding this with
required
attribute:(nothing will be submitted if required forms element are missing)
and there no needs in JS code
HTML5 form engine will show a corresponding warning for required information
If you really want to see a
disabled
button: