Simulate human selection of option item in select menu - javascript

I have a bit of script which technically works. It essentially listens to the hashtag on the URL and updates the select menu with the option value which matches the hashtag. It works on page load and doesn't care how the hashtag is updated, only that it is. Perfect
The problem is, I have a lot of other scripts on that page which does something when you select an option item, they all work when you manually select an option item, but nothing is triggered when I use the below script to automatically select the option item. How can I actually simulate a human selection in this setting? Any ideas?
$( document ).ready(function() {
window.addEventListener('hashchange', fn, false);
window.onload = fn; // fire on pageload
function fn() {
document.getElementById('select-two').value =
window.location.hash.replace('#','');
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select id="select-two" name="colordrop" class="color2" onchange="letsDoThis()">
<option value="Jet" class="jet">Jet</option>
<option value="Cream" class="cream">Cream</option>
<option value="Chocolate" class="chocolate">Chocolate</option>
<option value="Classic Red" class="classic_red">Classic Red</option>
</select>
And here is my JSFiddle, though not sure how to demonstrate hashtags in JSFiddle.
https://jsfiddle.net/liquilife/n9r6af7e/1/
This has been resolved. And I've marked the answer as complete. The final code which works is below:
$( document ).ready(function() {
window.addEventListener('hashchange', fn, false);
window.onload = fn; // fire on pageload
function fn() {
$("#select-two").val(window.location.hash.replace('#','')).trigger("change");
}
});

Since you're using jQuery you can use the .trigger(eventName) method to start a specific event on an element.
For instance you can both set the value and cause the event to fire like so:
$("#select-two").val(window.location.hash.replace('#','')).trigger("change");

You can use jQuery's change function to detect when the selected value of your select element changes and to execute code when that happens.
https://api.jquery.com/change

Related

Add or remove class in change event handler not working

I have a problem with addClass / removeClass methods in change method event handler.
I've registered my handler like this:
$('.someSelector').change(MyHandler);
and in MyHandler I have
function MyHandler(){
var input = $(this);
input.addClass('something'); //not working
}
after page loading I'm getting once again this input via console, I'm executing the same code and everything works correctly. So what's the problem with change method?
after page loading I'm getting once again this input via console, I'm executing the same code and everything works correctly
So it means that you didn't have DOM ready when you attempted to bind event for the first time. Try this:
$(function() {
$('.someSelector').change(MyHandler);
});
You are very close. Try this:
$(document).ready(function () {
$('.someSelector').change(MyHandler);
});
function MyHandler(){
var input = $(this);
input.addClass('something');
}
.something{background-color:red;}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select class="someSelector">
<option>A</option>
<option>B</option>
<option>C</option>
</select>

on() method with select element not firing

I'm using jQuery 1.9.0 and I'm trying to trigger the on() method whenever an option is changed inside a select. It worked with live() but I think its probably something simple that I'm not seeing.
This is my HTML:
<select class="select_exercise">
<option class="option_exercise">Example 1</option>
<option class="option_exercise">Example 2</option>
</select>
and my Script:
$("option.option_exercise").on("change","option.option_exercise",function()
{
alert("i am changing");
});
Here is the fiddle
The .on() method lets you delegate an event handler higher up the DOM tree. The idea is that you bind an event handler to an ancestor element, but only execute that handler when the event that has reached it originated on a descendant element matching the selector.
In your case, that would be this:
$(".select_exercise").on("change", ".option_exercise", function () {
// ^---- Probably no need to qualify the selectors with a tag name
alert("i am changing");
});
However, given your example code, this will not work since option elements will never fire change events (the select element will though). Assuming the select element is in the DOM from the time it loads, you can bind directly to it:
$(".select_exercise").on("change", function () {
alert("i am changing");
});
And if it's not in the DOM initially, you'll have to delegate higher (I'm using body here as an example. You should try and delegate to the closest possible ancestory that will be in the DOM at load):
$("body").on("change", ".select_exercise", function () {
alert("i am changing");
});
$("option.option_exercise").on("change","option.option_exercise" should be $("select.select_exercise").on("change",function()
Demo: Fiddle
You could try to do the following.
$(".select_exercise").change(function()
{
alert("i am changing");
});
you can use
$('.select_exercise').change(function() {
alert('Handler for .change() called.');
});
Ok
You need to check if the select element has been changed and not one of the option.
In this example i am checking if the select element which has a class called "select_exercise" has been changed.
And i am gessing you want to get the selected option so look at this code
$(".select_exercise").on("change",function()
{
alert($(this).find(":selected").text()); --Get the selected option text
alert("i am changing");
});
Fiddle Example
This works fine:
$("select.select_exercise").on("change", function () {
alert("i am changing");
});
The select is what changes, not the option, because it's the value of the select that changes, not the options.

jQuery UI Multiselect Events

I'm using this Multiselect jquery component. and I can't figure how to trigger and subscribe to the events of this thing. (I'm new to js).
What I've been trying so far is to trigger a collectionChanged event in the _updateCount function of the ui.multiselect.js file:
_updateCount: function() {
this.selectedContainer.find('span.count').text(this.count + " " + $.ui.multiselect.locale.itemsCount);
//How do I subscribe to the event?
$(this).trigger('collectionChanged');
}
Then I'm trying to subscribe to the 'collectionChanged' event from asp.net:
$('#<%= dropDown.ClientID %>').bind('collectionChanged', function ()
{
alert("Changed!");
});
The generated page markup is this:
<select name="ctl06$dropDown" id="ctl06_dropDown" class="multiselect" multiple="multiple" name="countries[]">
<option value="1134">A</option>
<option value="1980">B</option>
<option value="17789">C</option>
<option value="180367">D</option>
<option value="1990673">E</option>
</select>
<script type="text/javascript">
$(function () { $('.multiselect').multiselect(); });
$('#ctl06_dropDown').bind('collectionChanged', function ()
{
//Not working (never triggerd)
alert("Changed!");
});
</script>
Thanks.
The value of this on the _updateCount function is not a DOM element. For what you are trying to do, if I understand you well, you need to trigger your custom event in a DOM element and then listen to that custom event on the same DOM element. So you have two problems on your code: the first one is that you are trying to trigger an event using $(this) and thisis not what you expect, and the second one is that you are listening to an event on a DOM element that never triggers that event. If you do something like:
_updateCount: function() {
this.selectedContainer.find('span.count').text(this.count + " " + $.ui.multiselect.locale.itemsCount);
$("#ctl06_dropDown").trigger("collectionChanged");
}
Then your line $('#ctl06_dropDown').bind('collectionChanged'... should work fine.
the plugin you are using doesnt support events.
use the next version of it.
http://quasipartikel.at/multiselect_next/
if has events explained with sample code at http://quasipartikel.at/multiselect_next/#optionTabs-3
You need to use both the events called "selected" & "deselected".

Preventing select menu from opening

Possibly a silly question, but how do I prevent a select element in a form from showing its drop down menu when it's clicked on? I tried the following:
$('select').click (function (e) {
console.log (e);
return false;
});
and
$('select').click (function (e) {
e.preventDefault ();
console.log (e);
});
But neither worked.
What am I doing wrong?
EDIT: The reason I need to know is for a jquery enhanced select element that needs to degrade gracefully. The idea is the select, when clicked, opens a jquery UI dialog with a nicely maked up list that the user makes their selection from (clicking a list item causes the select's value to update). If JS is disabled then the select should just operate as normally.
The problem is that as well as the dialog opening, the dropdown also appears, which is not what I want. I can't just disable the control, as its value needs to be submitted along with the rest of the form.
This should work:-
$('#select').on('mousedown', function(e) {
e.preventDefault();
this.blur();
window.focus();
});
The problem is that you're using the wrong event.
<select onmousedown="(function(e){ e.preventDefault(); })(event, this)">
<option>Some Option</option>
</select>
JsFiddle
From my experience, if i need to disable something, the easiest way to have another invisible element on it (use absolute positioning). When you want to allow default behavior again, you just hide absolute element.
I believe the best solution would be to replace the select element with something else to click on (a button or a link).
BTW, you may want to look into the CSS 3 property appearance, which theoretically allows you to let that replacement element look like a dropdown. Support is however currently very limited:
http://css-infos.net/property/-webkit-appearance
https://developer.mozilla.org/en/CSS/-moz-appearance
You can, the trick is to cancel the mousedown event, not the click. The event chain is made in such a way that click and mouseup cannot occur if mousedown was cancelled:
function cancelDropDown(ev) {
ev.preventDefault();
}
document.getElementById("selectElement").addEventListener("mousedown", cancelDropDown, false);
Hide the select options on page load (if Javascript enabled). They will not display when the select box is clicked, but the text of the first option ("Select an option", or whatever) will still appear in the select field.
$(document).ready(function() {
$('#idOfSelect option').css('display', 'none');
});
Updated Solution:
$(document).ready(function() {
$('#idOfSelect').focusin(function() {
$(this).css('display', 'none');
$('body').click(function(event) {
$(this).unbind(event);
$('#idOfSelect').css('display', 'block');
});
});
});
I just solved this exact problem, by manipulating the 'size' attribute of select. Not very elegant, but worked. Hope its of some help to you.
<!-- Example select dropdown -->
<select id="select" onclick="tackleDropdown()">
</select>
<!-- The JS function -->
<script>
function tackleDropdown(){
document.getElementById('select').setAttribute('size', 0);
// your code for displaying the jQuery UI dialog (is it colorbox???)
// re-enabling the drop down
document.getElementById('select').setAttribute('size', document.getElementById('select').options.length);
}
</script>
Use disabled
$(this).attr("disabled","disabled");
Some good answers here. But still I had to make some additions.
$(document).on('keydown mousedown touchstart', 'select.disabled', function (e) {
e.preventDefault();
})
A simple solution based on CSS is this small fragment:
select:read-only * {
display: none;
}
This will make the options not available when the select is selected. This action mimics the behavior of the "readonly" attribute of the input.

Very weird Chrome behavior in an open (focused) "select" element

Here's a <select> element:
<select>
<option>Hello</option>
<option>Banana</option>
<option>Balloon</option>
<option>Something</option>
<option>Potato</option>
<option>Cleveland</option>
</select>
Here's a little bit of JavaScript (a jQuery "ready" handler):
$(function() {
function foo() {
var s = $('select').find(':selected');
}
setInterval(foo, 200);
});
Here is the jsfiddle for this question..
The handler sets up an interval timer which, every 200 milliseconds, finds the currently-selected <option> of the <select>, and does nothing at all with it. When I run the fiddle in Chrome (13.0.782.112), and I click on the <select> element, and then try to select an entry, the selection highlight keeps jumping back to the first selected element. I can click on any of the <option> elements shown and that works, of course, and then it does the same thing the next time.
Now, if I change the timer handler so that it doesn't use jQuery to find the currently-selected <option> element, as follows:
$(function() {
function foo() {
var select = $('select')[0];
var s = $(select.options[select.selectedIndex]);
}
setInterval(foo, 200);
});
then I no longer see the effect.
Firefox does not do this. I haven't tried Safari yet.
Personally I think that something's doing something wrong here. Is it Chrome? jQuery?
edit — one more detail - I'm running Chrome on Linux. I'll try Windows in a sec. (edit same in Windows.)
Change the code to:
function foo() {
var s = $('select option:selected');
}
setInterval(foo, 200);
Not sure why exactly it does this, but my guess would be that it's related to the way pseudoselectors work in jQuery. They're implemented as functions which are paired with the name of the selector (In this case "selected"). Consequently they are run against every possible element in the context (not just those which could potentially be selected).
Maybe there some sort of weird ghost element against which the "selected" pseudoselector is being executed when it shouldn't. The solution here is that I restrict the context to options before doing the pseudoselector. Always a good thing to do.

Categories