Crossbrowser issue - jquery don't show first entry of select - javascript

I got this selectbox in a searchform:
<select name="searchFor" id="searchFor">
<option name="option0" value="Choice">Pick one</option>
<option name="option1" value="person">Person</option>
<option name="option2" value="title">Title</option>
</select>
Because the top option shouldn't be selectable, I remove it using JQuery:
$("#searchFor").focus(function() {
$(this).find("option").eq(0).remove();
});
Works like a charm except offcourse for Internet Explorer.
In All browsers the option0 is removed when the select-tag is selected.
In IE the option only gets removed after one of the options gets selected. which makes you always choose the wrong one.
The action is repeated as well untill all of the options are gone.
Anyone got an idea on how to get this working in IE?
So the top-option should be removed from a select-tag when the select gets activated.
cheers

unbind the focus event like this
$("#searchFor").on('change',function() {
$(this).find("option").eq(0).remove();
$(this).off('change');
});
Fiddle Demo

Try the following, use "focusin" event and one() function to make the event handler run only once.
$("#searchFor").one("focusin", function() {
$(this).find("option").eq(0).remove();
});

Related

Safari doesn't produce a click event in <select> element

I have a use case, where I need to open a new tab on users choice in select.
<select ng-model="selected" ng-click="switchAction(data.id, selected)">
<option disabled hidden selected value=""></option>
<option value="run">1</option>
<option value="edit">2</option>
<option value="deleteEnvironment">3</option>
<option value="addSoftware">4</option>
<option value="openLandingPage">5</option>
</select>
Javascript:
function switchAction(id, selected) {
vm[selected](id);
}
vm.openLandingPage = function (id) {
window.open(vm.landingPage + "?id=" + id);
};
This code works perfectly in Chrome and Firefox, but doesn't in Safari. It could be partially solved, if I replace ng-click to ng-change. But then browser blocks a pop-up. Since, I render this code inside a grid cell, bootstrap's dropdown doesn't work either. I tried to put ng-click directly in option element, but it works only in firefox.
Is there any way to fix it?
Following plunker proofs that safari doesn't send a mouse-click event.
https://plnkr.co/edit/g3W2JLKxZFkzp1dGgrg4?p=preview
Found a solution. With angular-ui/bootstap and dropdown-append-to-body option I was able to break throw the ag-grid border. Issue is finally fixed!

Jquery Click select box option not work on Chrome [duplicate]

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');
}));

Run function when a select option is selected twice in a row

I have a AJAX-loaded dropdown that runs a function when it's changed, but I also want it to run the function if the option that is already selected is clicked. (For example, someone selects option A two times in a row, I want it to run the function both times without having to select a different option between them)
JAVASCRIPT:
$(document).on('change','#dropdown',function(e){
//do stuff
}
HTML:
<select id="dropdown">
<option value="optionA">option A</option>
<option value="optionB">option B</option>
<option value="optionC">option C</option>
</select>
It took a bit of experimentation, but there is a way to detect if the dropdown menu of the select was clicked.
Move your code into the click event, and wrap an if tag around it as such:
if(event.pageY<0)
{
// The dropdown menu on the select was clicked!
}
The reason that only this if is needed, is because of the fact that both browsers I've managed to test this on, make it seem like the cursor is outside of the actual page when the event was triggered.
You can find the demo at http://jsfiddle.net/Entoarox/ATm43/.
The pageY property of the event object is one of the properties that jQuery normalizes for cross-browser consistency.
http://api.jquery.com/category/events/event-object/
Replace your on change script with:
$(document).on('click','#dropdown',function(event){
if(event.pageY >= 0) return; // return and don't do anything
// The dropdown menu on the select was clicked!
// do stuff
});
Use
$(document).on('select','#dropdown',function(e){
//do stuff
}
or
$(document).on('click','#dropdown',function(e){
//do stuff
}

How to reselect already selected option

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 "").

How to make the "change event" work on a select drop-down menu when using .attr()

I have the select drop-down menu below:
<select id="select-param-num">
<option value='0'>0</option>
<option value='1'>1</option>
<option value='2'>2</option>
</select>
I have the trigger bellow, to update things on my page when the user change the selected option: (I am calling that first)
$('#select-param-num').change(function () {
//update stuff
});
And then in my initialization I am setting the drop-down menu at a specific value like this:
$("select#select-param-num option[value=2]").attr('selected', true);
I was expecting that .change() would have been called, to automatically update my page but it doesn't.
Do you have any suggestion to make it happen?
Thanks
Just trigger the event, 3 ways for that:
$('#select-param-num').change(); //same as .trigger('change')
$('#select-param-num').trigger('change'); //same as .change()
$('#select-param-num').triggerHandler('change'); //same as others but just because change event doesn't bubble
Use .triggerHandler to run your event handling code:
$("#select-param-num").triggerHandler('change');
You should also not use .attr to set the value of the dropdown. Do this instead:
$("#select-param-num").val("2");
You can use trigger for that .
$('#select-param-num').trigger('change');
.trigger()
In your select, there's no option with value=6. If you add it, and change a little the code, it works. Have a look here: http://jsfiddle.net/sjJkN/
code
$('#select-param-num').change(function () {
$("select#select-param-num option[value=6]").attr('selected', 'selected');
});

Categories