Need to enable a button on a page only if all questions have been answered, I have 5 dropdowns for this and need to make sure user answer all of them before letting him go to next step.
Tried to iterate through each select on each change, but can't make it work, bad JS knowledge.
arr = $('.select1, .select2, .select3, .select4, .select5')
$('.select1, .select2, .select3, .select4, .select5').on('change', function(event) {
$.each(arr, function(index, val) {
/* tried here something */
});
});
I was wondering may be there is a better way to do this, something like in one line: select.selected.size = 5
.
Thank you for any kind of help - ideas, solutions, links, etc..
I had a few moments, so I thought I'd offer a potential solution; given HTML like the following:
<select name="test1">
<option value="-1">Please select</option>
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
</select>
<!-- HTML repeated as much as you like -->
The following plug-in would work:
(function($){
$.fn.allSelected = function(){
return this.filter(function(){
return parseInt(this.value, 10) > 0;
}).length >= this.length;
};
})(jQuery)
And can be called like so:
$('select').on('change', function(){
console.log($('select').allSelected());
});
JS Fiddle demo.
Updated the above so that a value can be passed into the plug-in to be considered an invalid choice (in the demo I've, arbitrarily, used 3
), but which defaults to -1
if the user supplies no argument. In this case if any of the elements have a value equal to the noChoiceValue
(for want of a better name) the plug-in returns false
:
(function($){
$.fn.allSelected = function(opts){
var s = $.extend({
'noChoiceValue' : -1
}, opts);
return this.filter(function(){
return this.value !== s.noChoiceValue.toString();
}).length >= this.length;
};
})(jQuery);
$('select').on('change', function(){
console.log($('select').allSelected({
'noChoiceValue' : 3
}));
});
JS Fiddle demo.
References:
$.extend()
.filter()
.on()
.parseInt()
.Try
var arr = $('.select1, .select2, .select3, .select4, .select5');
arr.change(function () {
if (arr.filter('option[value!=""]:selected').length == arr.length) $('#bntid').prop('enabled', true);
});
.filter()
:selected
Attribute Not Equal Selector [name!="value"]
arr.filter('option[value!=""]:selected').length
filter options selected in dropdown whose value is not ""
and get it's lenght
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With