I have a dropdown menu that allows multiple selections. Now I want to make it when one particular option has selected all others to be disabled and enabled for selection. If that one particular is de-selected all others should be enabled again.
This is my select dropdown:
<select class="input-fields selectpicker" id="select_heigh" name="search[]" multiple>
<option value="all" selected>Search all</option>
<option value="tag">Tags</option>
<option value="username">Username</option>
<option value="email">Email</option>
<option value="full_name">Full Name</option>
</select>
And here is what I have tried for the js
$(document).ready(function() {
$('.selectpicker').selectpicker();
$('.selectpicker').on('change', function() {
if ($('option[value="all"]', this).is(':selected') && $(this).val().length > 1) {
$('option[value="all"]', this).prop('selected', false);
$('.selectpicker').selectpicker('refresh');
}
var selected = $(this).val();
if (selected.includes("tag")) {
$('option[value!="tag"]', this).prop('disabled', true);
} else {
$('option[value!="tag"]', this).prop('disabled', false);
}
if (selected.length > 3) {
$(this).selectpicker('setStyle', 'selected-count', 'btn-danger');
$(this).selectpicker('setTitle', selected.length + ' select(s)');
} else {
$(this).selectpicker('setStyle', 'selected-count', 'btn-default');
$(this).selectpicker('setTitle', 'Select');
}
});
});
I want when "Tag" is selected the other options to be disabled. When "Tag" is de-selected the others are enabled. When any other option is selected to no effect on others.
Also, the counting of selected choices doesn't work as expected. It should start showing Selected(3), Selected(4) ... after the third selection. Currently, it shows all of them not count of them.
I'm not that familiar with JS and not sure if I'm on the right path here
What the OP wants to achieve is a rather unexpected behavior of a native form control.
And in case one changes the behavior it should be based on using what form elements or elements in particular do support natively like the disabled- and the dataset-property.
An implementation then could be as simple as querying the correct select element and subscribing an event listener to any click event which occurres on the very select element. The change event can not be used since any further changes are impossible once a single option is selected but all other option are disabled. An option element's dataset gets used as lookup in order to detect whether the very element already has been selected before the current click handling.
function handleOptionClickBehavior({ target }) {
const optionNode = target.closest('option');
const nodeValue = optionNode?.value;
if (nodeValue === 'tag') {
const optionNodeList = [...optionNode.parentNode.children]
.filter(node => node !== optionNode);
const { dataset } = optionNode;
if (dataset.hasOwnProperty('selectedBefore')) {
Reflect.deleteProperty(dataset, 'selectedBefore');
optionNode.selected = false;
optionNodeList
.forEach(node => node.disabled = false);
} else {
dataset.selectedBefore = '';
optionNodeList
.forEach(node => node.disabled = true);
}
}
}
document
.querySelector('.selectpicker')
.addEventListener('click', handleOptionClickBehavior)
body { zoom: 1.2 }
<select class="input-fields selectpicker" id="select_heigh" name="search[]" size="5" multiple>
<option value="all" selected>Search all</option>
<option value="tag">Tags</option>
<option value="username">Username</option>
<option value="email">Email</option>
<option value="full_name">Full Name</option>
</select>
Related
Given a standard select as per below, is is possible by jQuery (or otherwise) to trigger a change event on individual options - As multiple may be selected, I don't want to trigger on the select but on the option?
<select multiple="">
<option>Test 2</option>
<option>Testing 3</option>
</select>
Something like:
$(`option`).trigger(`change`);
One way is to keep a reference of the last state of the multi-select, then compare to find the most recently clicked option.
let sels = [];
$(`select`).on(`change`, function() {
$(this).val().forEach(v => {
if (sels.indexOf(v) === -1) {
console.log(`The option most recently selected is ${v}`);
}
})
sels = $(this).val();
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<select multiple="">
<option value='2'>Test 2</option>
<option value='3'>Testing 3</option>
</select>
There is no change on an option. If you want it to act like a user is selecting option by option in the select, you would need to select the option and trigger the change event on the select.
const mySelect = document.querySelector("#mySelect");
mySelect.addEventListener("change", function () {
const selected = Array.from(mySelect.querySelectorAll("option:checked")).map(x => x.value);
console.log(selected);
});
function triggerEvent(elem, event){
const evt = document.createEvent("HTMLEvents");
evt.initEvent(event, true, true );
elem.dispatchEvent(evt);
}
const values = ['1','2','4'];
values.forEach(val => {
const opt = mySelect.querySelector(`[value="${val}"]`);
if (opt) {
opt.selected = true;
triggerEvent(mySelect, 'change');
}
});
/*
const values = ['1','2','4'];
const options = mySelect.querySelectorAll("option");
options.forEach(opt => {
const initial = opt.selected;
opt.selected = values.includes(opt.value);
if (opt.selected !== initial) {
triggerEvent(mySelect, 'change');
}
});
*/
<select id="mySelect" multiple>
<option value="1">one</option>
<option value="2">two</option>
<option value="3">three</option>
<option value="4">four</option>
</select>
The real solution is why is your page not set up to handle default values? Seems like you should just be able to call a method with the values and be done. Seems odd to rely on events.
I have two dropdown lists.
<select id="cat_user">
<option value="Super Admin">Super Admin</option>
<option value="Event Admin">Event Admin</option>
</select>
<select id="event_name">
<option value="ICT">ICT</option>
<option value="Fun Run">Fun Run</option>
</select>
I want that the second drop-down list should get enabled only if we choose Event Admin in the first drop-down list. It should again get disabled if we deselect the Event Admin from the first drop-down list.
May I know how can this be achieved using javascript?
You just need to handle dropdown change event.
<script>
$('#cat_user').change(function(){
if($('#cat_user option:selected').text() == "Event Admin")
{
$('#event_name').prop('disabled',false);
}
else
{
$('#event_name').prop('disabled',true);
}
});
</script>
you can refere below link for working demo
https://jsfiddle.net/t7jswp8r/
If you don't want to use jquery, you can do something like this in your Javascript,
document.getElementById('event_name').disabled = true;
document.getElementById('cat_user').addEventListener('change', function(event) {
if(event.target.value === "Event Admin") {
document.getElementById('event_name').disabled = false;
} else {
document.getElementById('event_name').disabled = true;
}
})
How do you select a value from a dropdown list, by using the text, instead of the value or the index?
The HTML:
<select name="category_group" id="category_group" sel_id="" >
<option value="0" selected="selected">Kies de rubriek</option>
<option value='1000' style='background-color:#dcdcc3;font-weight:bold;' disabled="disabled" id='cat1000' >
-- VOERTUIGEN --
</option>
<option value='1020' id='cat1020' >
Auto's
</option>
<option value='1080' id='cat1080' >
Auto's: Onderdelen
</option>
<option value='1040' id='cat1040' >
Motoren
</option>
<option value='1140' id='cat1140' >
Motoren: Onderdelen
</option>
</select>
the script:
this.fillSelectors('form[name="formular"]', {
'select[name="category_group"]': 'Motoren'
}, false);
This does not work, but it works using the value of "Motoren" (which is 1140).
How can I make it work, using fillSelectors, with the text?
CasperJS' fill functions only work by using the value. In your case this doesn't work because you're trying to set the shown value not the assigned option value. Though, this can be easily extended:
casper.selectOptionByText = function(selector, textToMatch){
this.evaluate(function(selector, textToMatch){
var select = document.querySelector(selector),
found = false;
Array.prototype.forEach.call(select.children, function(opt, i){
if (!found && opt.innerHTML.indexOf(textToMatch) !== -1) {
select.selectedIndex = i;
found = true;
}
});
}, selector, textToMatch);
};
casper.start(url, function() {
this.selectOptionByText('form[name="formular"] select[name="category_group"]', "Motoren");
}).run();
See this code for a fully working example on the SO contact page.
I have a select with loads of options. (Code below shortened for sake of example).
I want it to set the value of the input textfield "hoh" to "10" when you click/select all dropdown options, except one, that should set it to 50.
I imagined something like this would work, but its not. What am I doing wrong here?
<select>
<option onselect="document.getElementById('hoh').value = '50'">Hey</option>
<option onselect="document.getElementById('hoh').value = '10'">Ho</option>
<option onselect="document.getElementById('hoh').value = '10'">Lo</option>
....
</select>
<input type="text" id="hoh" value="10">
Something like this should work:
<script>
function myFunc(val) {
if (val == '50') {
document.getElementById('hoh').value = val;
} else {
document.getElementById('hoh').value = '10';
}
}
</script>
<select onchange="myFunc(this.value)">
<option value="1">one</option>
<option value="2">two</option>
<option value="50">fifty</option>
</select>
http://jsfiddle.net/isherwood/LH57d/3
The onselect event refers to selecting (or highlighting) text. To trigger an action when a dropbox selection changes, use the onchange event trigger for the <select> element.
E.g. Since you didn't already set the value attribute of your option tags.
<select id="myselect" onchange="myFunction()">
<option value="50">Hey</option>
<option value="10">Ho</option>
<option value="10">Lo</option>
....
</select>
and somewhere inside of a <script> tag (presumably in your HTML header) you define your javascript function.
<script type="text/javascript>
function myFunction() {
var dropbox = document.getElementById('myselect');
document.getElementById('hoh').value = dropbox[dropbox.selectedIndex].value;
}
</script>
I'm not sure it's wise to repeat the same value among different options in a droplist, but you could expand on this to implement the result other ways, such as if the sole option which will have value 50 is in a certain position, you could compare the selectedIndex to that position.
you could add an onchange event trigger to the select, and use the value of an option to show in the textbox
see http://jsfiddle.net/Icepickle/5g5pg/ here
<select onchange="setValue(this, 'hoh')">
<option>-- select --</option>
<option value="10">Test</option>
<option value="50">Test 2</option>
</select>
<input type="text" id="hoh" />
with function setValue as
function setValue(source, target) {
var tg = document.getElementById(target);
if (!tg) {
alert('No target element found');
return;
}
if (source.selectedIndex <= 0) {
tg.value = '';
return;
}
var opt = source.options[source.selectedIndex];
tg.value = opt.value;
}
Try this code
var inp = document.getElementById('hoh');
sel.onchange = function(){
var v = this.value;
if( v !== '50'){
v = '10';
}
inp.value = v;
};
I have the following multi select and I am using Jquery Chosen plugin
<select multiple="multiple" class="chzn-select span3" name="requestCategory" id="requestCategory">
<option selected="selected" value="">All</option>
<option value="2">Electrical</option>
<option value="4">Emails</option>
<option value="3">Filming Permits</option>
<option value="10">test1</option>
</select>
Client wants to make sure that i do not allow user to select ALL if any other value is selected or if user selects any other value then automatically deselect/remove ALL; because ALL = all categories so having individual option does not make sense. How do i do this?
Check if more than one item is selected, or if only one item is selected that it is not the first one - in these cases disable All.
$('.chzn-select').on('change', function() {
var selectedOpts = $('option:selected', this);
if(selectedOpts.length > 1 || selectedOpts.first().index() !== 0) {
$('option', this).first().attr('disabled', 'disabled');
}
});
http://jsfiddle.net/zCk2z/5/
at first change of option [simple] removes the All category.
but i recomand to disable the item, it looks better use .attr('disabled', 'disabled') instead of .remove();
$('#requestCategory').change(
function(){
$(this).find('option:contains("All")').remove()
})