I'm having some trouble creating a JavaScript function using an select element and id link. The function should depend on the selected option/value of the select dropdon.
What I want to do, is call an event function when the select dropdown is clicked, then apply a class to the appropriate id.
The html is this:
<select class="select-trigger" >
<option value="value1">Value1</option>
<option value="Value2">Value2</option>
<option value="Value3">Value3</option>
</select>
And the elements to get a class added:
<div id="value1"></div>
<div id="value2"></div>
<div id="value3"></div>
And my function so far (almost working):
var trigger = document.querySelectorAll('.trigger');
for (var i =0; i < trigger.length; i++) {
var btn = trigger[i];
btn.addEventListener('click', function () {
var id = this.options[this.selectedIndex].value;
document.querySelector('#' + id).classList.toggle('active');
}, false);
}
I think the trouble I'm having is that I'm calling the function using click event listener. I guess I would need to use an onchange function instead?
Also I only want a single div to have an "active" class at any given time. At the moment, the function is adding the class but not removing it when another is selected.
Here's a fiddle http://jsfiddle.net/2Rcjt/1/
Note - I don't want to put any inline onclick JS in my markup.
You can save the last selected option (div) into some property of the select. Then each time user change the option, just toggle class on the last selected option to make it inactive. Code:
var trigger = document.querySelectorAll('.trigger');
for(var i = 0; i < trigger.length; i++){
trigger[i].onchange = function(){
if(this.lastOption) this.lastOption.classList.toggle('active');
this.lastOption = document.getElementById(this.value);
this.lastOption.classList.toggle('active');
};
trigger[i].onchange();
}
Demo.
Related
This is the thing I have:
A normal select with a few options...
And the thing is, I do need to click in some other div and when I click on that one, I want the select list to show up as they were clicked normally and then allow the user to choose from the select options
I have some code already
<div onclick="set_select()"></div>
<select class='form-control' id='opts'>
<option selected disabled></option>
<option>Contacto</option>
<option>Entrevista</option>
<option>Prensa</option>
<option>Conferencias</option>
</select>
<script type="text/javascript">
function set_select(){
var select = document.getElementById('opts');
return select.active = true;
}
</script>
Not possible with plain html/javascript.
You need some plugin to replace your standard select field with divs and then use your function to trigger that divs. One is selectmenu: https://jqueryui.com/selectmenu/#product-selection
There is a lot more of them available: https://www.google.pl/search?q=js+select+replacement&gws_rd=cr&ei=wN5ZV8SjMIGLsgGP_IboDQ
This is "sort" of possible but not trivial and you will need to possibly do some management of the effect as I do here in the "change" event for the select. Not perfect but perhaps this can give you a start.
Note you MIGHT just want to use the "focus" on the select or, set the visible size as I do here, set the select size on the change to 0 with event.target.size = 0; and so forth.
Revised the markup a bit to allow the click handler:
<div id="clicker">clicker</div>
<select class='form-control' id='opts'>
<option selected disabled></option>
<option>Contacto</option>
<option>Entrevista</option>
<option>Prensa</option>
<option>Conferencias</option>
</select>
Here is the script, as I said, not perfect but you can decide how you handle the change/click events.
window.onload = function() {
var id = "clicker";
var div = document.getElementById(id);
var select = document.getElementById("opts");
div.onclick = function(event) {
console.log('clicker div');
select.size = select.options.length;
select.focus();
};
select.onclick = function(event) {
console.log('opt clicked');
};
select.onchange = function(event) {
console.log('opt change');
var index = event.target.selectedIndex;
console.log(index);
event.target.size = index + 2;
};
}
Here is a fiddle you can use to get you started: https://jsfiddle.net/MarkSchultheiss/mL0b7ubr/
Note that if you wish to use the "default" size for the select you can detect that like so:
if (event.target.type == "select-one") {
event.target.size = 1;
} else {
event.target.size = 4;
}
Here is a fiddle with that change and a bit cleaner on the event attachment: https://jsfiddle.net/MarkSchultheiss/mL0b7ubr/1/
I have a series of hidden html form-groups that I want to display based on the values chosen in two cascading select lists. I'm using jQuery to toggle a class on the second list which is then called by an on change event function.
If I hard-code the class, the subsequent form-groups are shown when the on change is fired.
If I use the toggleClass from jQuery to dynamically change the class, the on change function doesn't fire even though the class is toggled correctly.
HTML
<div class="form-group hidden" id="option_env">
<label class="col-xs-12 col-sm-2 control-label" for="ddl_env">Options</label>
<div class="col-xs-12 col-sm-10">
<select name="category" id="ddl_env" class="form-control ">
<option value="-- Select an option --">-- Select an option --</option>
<option value="horse">Tethered horses</option>
<option value="Watercourses">Watercourses</option>
</select>
</div>
</div>
jQuery
var cascadeSelect = $('#ddlcategory');
var optionSelect = cascadeSelect.on('change', function () {
hideAll();
var option = $(this).val();
var childSelect = showOption(option);
return childSelect;
});
$('.option').on('change', function () {
hideDetail();
var detail = $(this).val();
showDetail(detail);
});
function showOption(option) {
var returnOption = null;
$('#' + option).toggleClass('chosen hidden')
.find('select').toggleClass('option')
;
var ddl_option = option.substr(option.indexOf('_')+1);
return returnOption = $('#ddl_' + ddl_option);
}
This works insofar as the ddl_env select has the option class added by the jQuery find, however, the $('.option').on('change', function () doesn't fire when the select list item is changed.
If I comment out the line .find('select').toggleClass('option') and manually add the option class to the ddl_env select then it works fine.
I get the same result with jQuery.addClass.
Debugging in Chrome shows that the ddl_env select change doesn't fire the change event when the option class isn't hard-coded.
Classic question.
Replace
$('.option').on('change', function()...
with
$(document).on('change', '.option', function()...
The second syntax works on present and future '.option' items.
This handler will only work on anything with the clas option when the page loads
$('.option').on('change', function () {
hideDetail();
var detail = $(this).val();
showDetail(detail);
});
In order for you to get it to work on elements dynamically allocated that class after the page has loadewd you need to delegate the event handler to a higher element, so basically its parent, or if all else fails document
$(document).on('change', '.option', function () {
hideDetail();
var detail = $(this).val();
showDetail(detail);
});
I've got a Problem. I have a Select Option in HTML
<div id="eilig">
<select id="eiligselect" data-role="slider">
<option value="2" selected="selected">n. Eilig</option>
<option value="1">Eilig</option>
</select>
</div>
On page default "n. Eilig" is selected. After I have made a ajax post request (with "Eilig" selected) the select option should go back to default ("n. Eilig")
I have tried it with $('#eiligselect').val(2); but this only change the value back but the select option shows "Eilig" (but internal value is "n. Eilig".
This select is with a data-role "slider" which emulates a on / off switch like in ios.
So I think I have to click that slider with javascript to change it back instead of just change the value.
Do you have a clue? Thanks.
Try this : put selected attribute for option with value="2"
$('#eiligselect option[value="2"]').attr('selected',true);
Bind the event on change for slider on select value change,
$('#eiligselect').on('change', function() {
var activeLabel = $('span.ui-slider-label');
var mySlider = $(this);
var new2 = 'n. Eilig';
var new1 = 'Eilig';
if(mySlider.val() == 1) {
activeLabel.text(new2);
} else {
activeLabel.text(new1);
}
mySlider.slider( 'refresh' ); // .trigger( 'create' )
});
This Code may help you solving your problem,
var eiligselect = $("#eiligselect")[0];
eiligselect.seletedIndex = 0;
I am trying to make a custom select just like this, but without jquery (I just dont want to import a whole new library for one single thing). I made it until this, but I dont know how I can make the selection with regular JS. How can I select something from the list?
If you just want to show the selected item in the dropdown,
You need to wrap the text to be displayed inside a <span> as follows
<div class="label"><span>Select Element</span><b class="button">▾</b>
</div>
Then you can change it's innterHTML to display the selected item using the following js:
var dd = document.querySelector('.label span');
var options = document.querySelectorAll('div.hidden ul li');
for (var i = 0; i < options.length; i++) {
options[i].onclick = select;
}
function show() {
var selectbox = document.getElementById("options");
if (selectbox.className == "hidden") {
selectbox.setAttribute("class", "visible");
} else {
selectbox.setAttribute("class", "hidden");
}
}
function select() {
dd.innerHTML = this.innerHTML;
}
Demo
Listen to clicks on your div#options. Demo
function choose(ev, el) {
var options = el, target = ev.target,
value = ev.target.innerHTML;
options.setAttribute('class', 'hidden');
options.parentElement.querySelector('.label').innerHTML = value;
}
<div id="options" class="hidden" onclick='choose (event, this);'>
Side notes. I don't recommend to use inline handlers. Use addEventListener instead.
You need to define an onclick handler of your li elements. Either in HTML, or in JS by looping through children of div container with li elements http://jsfiddle.net/rWU5t/2/
If you want fancy item highlights on mouse hover, you also need to define onmouseover and onmouseout handlers.
let's say I have a form that contains several "select" element that the User can choose.
when ready to submit, I need to find all the "select" that have changed.
how can I do it?
for example:
<form>
<input type="text" name="a"/>
<select name="b">...</select>
<select name="c">...</select>
<select name="d">...</select>
</form>
Using jQuery, something like this should work:
$('select').change(function() {
$(this).addClass('changed');
});
$('form').submit(function() {
var changed_selects = $('select.changed');
// do what you want with the changed selects
});
I would take advantage of the defaultSelected property on HTMLOptionElement instead of trying to keep track of selects that have changed:
form.onsubmit = function() {
var selects = form.getElementsByTagName("select")
, i
, changedSelects = []
, selected
, select;
/* Iterate over all selects in the form: */
for (i = 0; i < selects.length; i++) {
select = selects[i];
/* Get the currently selected <option> element: */
selected = select[select.selectedIndex];
/* Determine if the currently selected option is the one selected by default: */
if (!selected.defaultSelected) {
changedSelects.push(select);
}
}
alert(changedSelects.length);
}
You can iterate over all of the select elements on your form, determine if the selected option is the one that was selected by default, and push each one whose selected option wasn't the default into an array.
Example: http://jsfiddle.net/andrewwhitaker/abFr3/
You could register an event listener (using onchange, etc.) to determine if any changes were made.
Alternatively, you could keep a private copy of all of the previous values, then run a comparison before submit to check for changes.
Do something like:
var selectedVal = $("select[name='a'] option:selected").val();
//check this with your default selected val
You can attach the onchange event listener to each <select> element. When the event is triggered, you can store the actual elements in an a temporary array and reference it later when you are ready to submit. Note that the array can hold the actual DOM elements.
You need to clarify what you mean by "the select have changed".
If you mean have changed from their default value, then you should have one option on each select (usually the first) set as the default selected option. Then you can iterate over the selects and see if the option with the selected attribute (or where the defaultSelected property is true) is the selected option, e.g.
<script>
function anyChanged(){
var select, selects = document.getElementsByTagName('select');
for (var i=0, iLen=selects.length; i<iLen; i++) {
select = selects[i];
if (!select.options[select.selectedIndex].defaultSelected) {
// the selected option isn't the default
alert('select ' + (select.id || select.name) + ' changed');
}
}
}
</script>
<select name="one">
<option selected>one
<option>two
<option>three
</select>
<button onclick="anyChanged()">Check</button>
However, if you want to see if the user has changed the selected option based on some other logic, you need to say what it is.