Reputation: 13
I have some input elements and would like to include a checkbox that is disabled if the input elements are not complete. However, I cannot use an onClick attribute. A fiddle is below. As you can see, my goal is that the result checkbox should be disabled if input1 and input2 are left blank. Any advice?
fiddle: http://jsfiddle.net/0jozk5uL/
HTML
Input 1:<select name="input1" id="input1" initialvalue="">
<option class="no-op" value="">-- Please select --</option>
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
</select><br>
Input 2:<select name="input2" id="input2" initialvalue="">
<option class="no-op" value="">-- Please select --</option>
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
</select><br>
Result:<input type="checkbox" name="result" id="result">
Javascript
var input1 = document.getElementById('input1');
var input2 = document.getElementById('input2');
var result = document.getElementById('result');
function(){
if(input1 == "" && input2 == ""){
result.disabled = true;
} else {
result.disabled = false;
}
}
Upvotes: 0
Views: 3623
Reputation: 14800
You need to check input1.value == ""
, not simply input1 == ""
You also need to fire your method originally, and also run it every time your select lists change value.
Give the function a name
function setCheckState(evt) {
if (input1.value == "" || input2.value == "") {
result.disabled = true;
} else {
result.disabled = false;
}
}
Add event listeners
input1.addEventListener('change', setCheckState);
input2.addEventListener('change', setCheckState);
Fire the method to get the initial checkbox state set
setCheckState();
See my update to your fiddle
Finally, you can reduce your if()
statement to a simple assignment...
function setCheckState(evt) {
result.disabled = input1.value == "" || input2.value == "";
}
[edit] ... thanks dave, based on the question statement "disabled if the input elements are not complete." I believe you are correct about using ||
instead of &&
... updating this answer and making one more fiddle change.
Upvotes: 3
Reputation: 1305
I think this is what you want:
function update(dropdown, check) {
if(dropdown.options[dropdown.getSelectedIndex].text != "--Please select--") {
check.disabled = false; // if value is not equal to --Please select--...
} else {
check disabled = true;
}
}
var check // = checkbox elem
var in1 // = dropdown 1 elem
var in2 // = dropdown 2 elem
in1.onchange = function() {
update(in1, check); // update checkbox
}
in2.onchange = function() {
update(in2, check); // update checkbox
}
Hope this helps, sorry for any typing errors, I'm on a phone.
Upvotes: 0