I am using Chosen to give my <select> a proper look and a search input.
The problem is that with a <select multiple> when the user open the dropdown menu to choose the options he wants I want to keep the dropdown open between the clicks. It is really annoying to have the re-open the menu between each option selection.
I searched through the Chosen documentation and through the internet but I couldn't find to do it with Chosen.
Here is how I wrote my <select> and how applied Chosen to it (nothing special) :
<select multiple="multiple" id="foo" class="chosenSelect">
<option value="NULL" disabled>Chose multiple somthing</option>';
<option value="bar1">foobar1</option>';
<option value="bar2">foobar2</option>';
<option value="bar3">foobar3</option>';
</select>
and
$('.chosenSelect').chosen();
Any help is welcomed.
Set hide_results_on_select to false.
I am not familiar with the Chosen library; so if there exists a better solution in the library itself, I'd defer to that solution.
However, if you do not find a better solution, and you still need the functionality, you can use this little hack.
$('.chosen-results').bind('click', function(e) {
setTimeout(function() {
$(e.currentTarget).parent().siblings('.chosen-choices').click()
});
});
I reiterate, this is a hack and you should only use this if you've found nothing else. I'll edit the answer if I find something better.
Add a click trigger to the change event
$("select").chosen().change(function() {
$(".search-field").trigger("click")
})
I agree with the solution #squgeim posted.
However, after I selected something, the search criteria don't get kept. If I have a super long dropdown list, the scroll bar will bounce to the top.
In order to keep my previous search criteria, I made some update on #squgeim's answer:
//restore previous search value
var chosenSearchValue = "";
$(".chosen-container-multi .search-field input").keyup(function(){
chosenSearchValue = $(this).val();
})
//make chosen multiple select dropdown menu stay open after click
$('.chosen-results').bind('click', function(e) {
if (chosenSearchValue){
$(this).parents(".chosen-container-multi").find(".search-field input").val(chosenSearchValue);
}
setTimeout(function() {
$(e.currentTarget).parent().siblings('.chosen-choices').click();
});
});
Just use set hide_results_on_select to false if you want to keep showing the dropdown after chosing in option
Related
I have an HTML form with a Javascript custom dropdown function taken from W3Schools. It replaces the ugly default dropdown with a really neat one, and works in most cases. However, I ran into a problem.
The custom dropdown code uses the function "selectedIndex" in order to define which label should be selected when the user clicks. It seems to work, but I am also using the Sisyphus "save form data" plugin, and when I refresh the page, the user changes are lost.
I know it is not a problem with Sisyphus or my implementation, because if I unhide the default original dropdown, I click on it, and upon refresh the options are saved just fine.
This inquiry shows that the "selectedIndex" function doesn't give exactly the same result as if the user had physically clicked on the label. It appears to change the value but somehow doesn't really register it, spooky....
After reading similar issues on stackoverflow, I added the two following lines under the "selectIndex" function: trying to programmatically set it's "selected" state to "true", and also to trigger a click:
s.selectedIndex = i;
s.options[i].selected = true;
s.options[i].click();
Still no luck. Here is a wider view of the code:
// When an item is clicked, update the original select box, and the selected item
for (i = 0; i < sl; i++) {
if (s.options[i].innerHTML == this.innerHTML) {
//update the original select box
s.selectedIndex = i;
s.options[i].selected = true;
s.options[i].click();
//update the new select box
h.innerHTML = this.innerHTML;
}
}
Here is the HTML:
<div class="dropdown has-label">
<label for="jours_entiers_de_travail">Number of days</label>
<div class="select-wrapper">
<select name="jours_entiers_de_travail" id="jours_entiers_de_travail">
<option value="1">1 day</option>
<option value="2">2 days</option>
<option value="3">3 days</option>
</select>
</div>
</div>
And a full version of the dropdown can be seen on this Codepen:
https://codepen.io/benviatte/pen/OJNYwRy
This codepen appears to work, but again, the issue comes when I try to use the value assigned by selectedIndex, for example with Sisyphus. The value doesn't seem to have been properly assigned.
Thank you dearly for your help
Sisyphus documentation hints that it uses change events to monitor updates of form elements. Source code appears to confirm this in JSDoc markup for the bindSaveDataOnChange function.
Hence try triggering a change event on the select box instead of clicking the option element programmatically. Untested but possibly like
//update the original select box
s.selectedIndex = i;
s.options[i].selected = true;
// s.options[i].click(); // replace with:
$(s).trigger("change"); // trigger change event on select box
Also see Trigger change event <select> using jquery for a variety of ways of triggering change events in both jQuery and plain JavaScript, and trigger() | jQuery API Documentation.
I'm having a problem in Chrome with the following:
var items = $("option", obj);
items.each(function(){
$(this).click(function(){
// alert("test");
process($(this).html());
return false;
});
});
The click event doesn't seem to fire in Chrome, but works in Firefox.
I wanna be able to click on a option element from a combo, if I do instead another kind of element, lets say <li> it works fine. Any ideas? Thanks.
I don't believe the click event is valid on options. It is valid, however, on select elements. Give this a try:
$("select#yourSelect").change(function(){
process($(this).children(":selected").html());
});
We can achieve this other way despite of directly calling event with <select>.
JS part:
$("#sort").change(function(){
alert('Selected value: ' + $(this).val());
});
HTML part:
<select id="sort">
<option value="1">View All</option>
<option value="2">Ready for Review</option>
<option value="3">Registration Date</option>
<option value="4">Last Modified</option>
<option value="5">Ranking</option>
<option value="6">Reviewed</option>
</select>
The easy way to change the select, and update it is this.
// BY id
$('#select_element_selector').val('value').change();
another example:
//By tag
$('[name=selectxD]').val('value').change();
another example:
$("#select_element_selector").val('value').trigger('chosen:updated');
I've had simmilar issue. change event was not good for me because i've needed to refresh some data when user clicks on option. After few trials i've got this solution:
$('select').on('click',function(ev){
if(ev.offsetY < 0){
//user click on option
}else{
//dropdown is shown
}
});
I agree that this is very ugly and you should stick with change event where you can, but this solved my problem.
I found that the following worked for me - instead on using on click, use on change e.g.:
jQuery('#element select').on('change', (function() {
//your code here
}));
<select id="myselect">
<option value="0">sometext</option>
<option value="2">Ready for Review</option>
<option value="3">Registration Date</option>
</select>
$('#myselect').change(function() {
if($('#myselect option:selected').val() == 0) {
...
}
else {
...
}
});
Looking for this on 2018.
Click event on option tag, inside a select tag, is not fired on Chrome.
Use change event, and capture the selected option:
$(document).delegate("select", "change", function() {
//capture the option
var $target = $("option:selected",$(this));
});
Be aware that $target may be a collection of objects if the select tag is multiple.
I use a two part solution
Part 1 - Register my click events on the options like I usually would
Part 2 - Detect that the selected item changed, and call the click
handler of the new selected item.
HTML
<select id="sneaky-select">
<option id="select-item-1">Hello</option>
<option id="select-item-2">World</option>
</select>
JS
$("#select-item-1").click(function () { alert('hello') });
$("#select-item-2").click(function () { alert('world') });
$("#sneaky-select").change(function ()
{
$("#sneaky-select option:selected").click();
});
What usually works for me is to first change the value of the dropdown, e.g.
$('#selectorForOption').attr('selected','selected')
and then trigger the a change
$('#selectorForOption').changed()
This way, any javascript that is wired to
Maybe one of the new jquery versions supports the click event on options. It worked for me:
$(document).on("click","select option",function() {
console.log("nice to meet you, console ;-)");
});
UPDATE: A possible usecase could be the following: A user sends a html form and the values are inserted into a database. However one or more values are set by default and you flag this automated entries. You also show the user that his entry is generated automatically, but if he confirm the entry by clicking on the already selected option you change the flag in the database. A rare sue case, but possible...
I know that this code snippet works for recognizing an option click (at least in Chrome and FF). Furthermore, it works if the element wasn't there on DOM load. I usually use this when I input sections of inputs into a single select element and I don't want the section title to be clicked.
$(document).on('click', 'option[value="disableme"]', function(){
$('option[value="disableme"]').prop("selected", false);
});
Since $(this) isn't correct anymore with ES6 arrow function which don't have have the same this than function() {}, you shouldn't use $( this ) if you use ES6 syntax.
Besides according to the official jQuery's anwser, there's a simpler way to do that what the top answer says.
The best way to get the html of a selected option is to use
$('#yourSelect option:selected').html();
You can replace html() by text() or anything else you want (but html() was in the original question).
Just add the event listener change, with the jQuery's shorthand method change(), to trigger your code when the selected option change.
$ ('#yourSelect' ).change(() => {
process($('#yourSelect option:selected').html());
});
If you just want to know the value of the option:selected (the option that the user has chosen) you can just use $('#yourSelect').val()
Workaround:
$('#select_id').on('change', (function() {
$(this).children(':selected').trigger('click');
}));
I have this select drop-down where in my drop-down when i select one of the choices the div for that particular choice will be displayed and the rest will remain hidden.
I tried using this Demo but it don't work.
<form id="nl-form" class="nl-form">
<select id="choices">
<option value="family" selected>family</option>
<option value="closefriend">close friend</option>
<option value="acquaintance">acquaintance</option>
</select>
<div class="nl-overlay"></div>
</form>
<div id="family" class="chosentree">family</div>
<div id="closefriend" class="chosentree">closefriends</div>
<div id="acquaintance" class="chosentree">acquaintance</div>
$(function() {
$('.chosentree').hide();
$('#choices').change(function(){
//$('.chosentree').hide();
$('#' + $(this).val()).show();
});
});
What could be the problem?
and also on the div family, I want to place this ff. Demo how should it be done? Notice that it has a link script file check external sources in jsfiddle
I'm new with this and I don't know what should be the proper placing of codes.
your code need
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>// you can add what ever is latest version available.
since you have written change event better add a dummy select option like:
<option value="select" selected>select</option>
otherwise it is working.
Here is your working demo after loading above library
FiddleDemo
I solved it by putting
$(this.elOriginal).find('option').removeAttr("selected");
$(this.elOriginal).find('option:eq('+this.selectedIdx+')').attr("selected", "selected");
$(this.elOriginal).trigger('change');
in close function in nlform.js
Then by listening to change event of the select element I get my goodies!
Not sure if this is still relevant, but nl-form doesn't actually use the select inputs. If you observe the page in Firebug, you'll notice the actual Select elements have a visibility of "none". What nl-form does is actually take the options in the select that you create and turns them into a series of different html elements (div, a, and ul elements). So when you change an option on an nl-form select, you cannot listen for the change event because it doesn't actually happen.
It turns out it's not real easy or fun to do. What I did to monitor the changes was create a custom event at the bottom of the close() method in nlform.js. Then in my javascript, I listened for that particular event and had to write a lot of javascript to find the elements I needed...it did eventually work. It's a lot of work though.
The title seems confusing but what I want to do is...
I know how to handle only if the user select new option with this - $('select').change(function(){}).`
But not if the user wants to select the already selected option.
I've also tried with radio but same thing.
Okay for example I have a select with an option (red,blue,green).
<select>
<option value="red">RED</option>
<option value="blue">BLUE</option>
<option value="green">GREEN</option>
</select>
and I have this script:
$('select').change(function(){
var val = $(this).val();
alert(val);
});
When I select option 'blue' it alerts a value 'blue', then I select 'green' it alerts 'green' as well. but when I select 'green' again nothing happens.
This question comes to my attention as this is pretty basic stuff but no one actually dig into it further. OP has been using change(), but when you reselect the current selected option nothing is fired!
I tried click(), but it's firing before you can even choose an option.
With blur(), after you're done selecting nothing is fired because the the select element is still being focused, so you need to focus out like clicking outside for it to execute.
So I just suggested OP to switch to a radio type input then handle execution with click() event. That way you can still reselect already marked radio button.
But then I noticed that you just need to get the second click on <select> element because the first click opens the drop down list of options the second click returns the value of your selected option. So I came up with this:
$('select').click(function(){
var $this = $(this);
if ($this.hasClass('open')) {
alert($this.val());
$this.removeClass('open');
}else {
$this.addClass('open');
}
});
But now the problem is when you first click on <select> the drop down is being showned and we've also added the class 'open'. Then clicking elsewhere (without selecting an option) the drop down is hidden so when you click back on <select> the event is fired before you can even select an option.
So I added this code to fix that:
$(document).click(function(e){
var $select = $('select');
if (!$select.is(e.target)){
$select.removeClass('open'); //reset the steps by removing open
}
});
You can test it out in this jsfiddle. Cheers!
I think when <select> loses its focus is also a concern. So I added blur() event. See this update jsfiddle
i solved using onclick='this.value=-1' that reset the selection to nothing...
I have solved this problem by using:
$('#id_selec').on('click', 'option', function (e) {
value = $(this).val();
// ....
The handler works if you select any (including the already selected) option.
In instances where nothing should happen when the user selects the already-selected option I suppose it is a "feature" of the DOM rather than a bug to have no Event occur. However, if your code is doing more with <select> than making a simple selection it is also a nuisance, so I'm grateful others have tackled it here.
The current accepted answer is clever in the use of the click event to capture selection of an already selected <select> option, but if you are willing to specify the length of your list as (in this case) <select size=3>, you can simply set the selected value to "" from your "change" Event, and the same selection will trigger every time.
In this case the OP's example would change to:
HTML:
<select size=3>
<option value="red">RED</option>
<option value="blue">BLUE</option>
<option value="green">GREEN</option>
</select>
jQuery:
$('select').change(function(){
var val = $(this).val();
alert(val);
$('select').val("");
});
The only side-effect is that the selection element may now display to the user as three rows rather than one.
(Credit goes to Kirby L. Wallace for the idea of setting the select's value to "").
Unfortunately i'm not too familiar with javascript/jQuery. I have a form with a dropdown. What i need to do is to populate a text field depending on the selection of the dropdown. First voice of the dropdown is "other" so the text field must be writable, then from the second i want to assign a value automatically and disable the text field.
The value of the dropdown will be saved in the db so it must remains the name of the option.
I found several solutions with google but none of them fits my needs...hope someone could help me.
To create the functionality you're looking for, there are a few basic things you'll need to learn.
jQuery Selectors
First, if you aren't already familiar with jQuery's selector syntax, learn about it here.
The .change() Event
Next, you'll need to know how to bind to the dropdown menu's .change event. One way to do this is $('#dropdownId').change(function() { ... });, which is just a shortcut for $('#dropdownId').on('change', function() { ... }); . Within the callback functions, you can access the dropdown element with this and as a result, the jQuery object with $(this).
We can then grab the dropdown's value with $(this).val() and use some basic logic to enable/disable the textbox and set its value.
Enabling/Disabling the textbox
In order to enable/disable the textbox, you can use: $('#txt').removeAttr('disabled');and$('#txt').attr('disabled', 'true');` respectively.
Example
I've combined all of these for you in an example fiddle to show you how you can put these together in this jsFiddle. Let me know if you have any questions about how it works :)
Here is the fiddle for you...
http://jsfiddle.net/G3V3v
HTML:
<select id="ddl">
<option value="0">[ Other ]</option>
<option value="1">First</option>
<option value="2">Second</option>
</select>
<input id="txt" />
jQuery:
$('#ddl').change(function() {
if ($(this).val() == 0) {
$('#txt').val('').removeAttr("disabled").focus();
} else {
$('#txt').val($(this).children('option:selected').text());
$('#txt').attr("disabled", "disabled");
}
});