I have a page that has multiple select lists and when ever one of the select list changes using jQuery's .change() function I change the text in a span next to the select list. When the page loads there is already some text in every span (the text different for each span). The problem is that when the page loads the .change() function loops through all of the select lists changing the text in every span. I don't want the text in the span to change until a user selects a different item in the list. I can't just check to see if there is text in the span because if a user does change the selected item it doesn't matter if there is any text or not, I just don't want to to replace the text when the page loads. So, how can I get the .change() function to stop firing when the page is loaded? The code:
JS/jQuery
$(document).ready(function() {
$("select").change(function () {
var txt = $(this).val();
$(this).next('span').text(txt);
}).trigger('change');
});
HTML (repeated many times)
<select name="animal[]">
<option value="dog" selected="selected">dog</option>
<option value="cat">cat</option>
<option value="bird">bird</option>
<option value="snake">snake</option>
</select>
<span class="out">text that shouldn't be replaced until user changes selected item</span>
Thanks for your help!
You just need to remove this call:
.trigger('change')
It's what's invoking the $("select").change(function () { ... }) handler that you just bound. The default behavior is to wait for the change event to occur...a .trigger('change') or .change() (no parameters) will simulate the change event, making that handler go to work.
The "change" is triggering because your code is telling it to! That call to .trigger("change") says, "run the 'change' event handler please". So, take that out.
Now, the thing is, the reason your code was written that way was probably to make sure that the settings of the <select> elements really reflects what the behavior is supposed to be when users manually make the same changes. For example, sometimes there are forms where part of the inputs are supposed to be disabled unless a <select> is set to a certain option. By triggering the "change" event on page load, the code could make sure that those rules are in force. If you just take out that trigger, things may not work right, is what I'm saying. That handler looks pretty simple, so maybe the problem is that this code was cut-and-pasted from somewhere else.
Related
I have a target website where there is the following dropdown menu.
<select class="categories-options" data-level="1" name="level1-option" id="level1-option" required="">
<option value="">default</option>
<option value="p1" data-href="/callback/p1">P1</option>
<option value="p2" data-href="/callback/p2">P2</option>
<option value="p3" data-href="/callback/p3">P3</option>
</select>
When an item is selected from the menu, it triggers a "change" event and a function is called when this event happens. I have debugged the event using Chrome and you can see the debugging output when I selected an item from the dropdown menu. I have taken a screenshot from the debugger.
Now, let me explain what I am trying to do. I use a javascript function to select an item from the dropdown menu using the following code:
var id= document.getElementById('level1-option');
setSelectedValue(id, "p2");
$('#level1-option').trigger("select");
In the last line, I try to trigger the same event that happens originally in the webpage as if I manually selected the item. however, it doesn't trigger anything. |I see in the debug output that the event is triggered by class. I have tried many different things but didn't work. Could anyone shed some light on this issue? How can I trigger the same event that happens in that webpage using jquery or javascript?
Your code:
$('#level1-option').trigger("select");
...will trigger an event called select (which isn't related to the value of a form field change), but the event you stopped on in the debugger is change, not select:
If you want to trigger the change event, trigger the change event:
$('#level1-option').trigger("change");
// Difference is here -------^
Side note: Because you're using jQuery, your code can be simpler, you dont need the getElementById or the setSelectedValue:
$('#level1-option').val("p2").trigger("change");
Try this
$('#level1-option').trigger("change");
I want to populate a drop-list with several items and select a default item:
<select onchange="DoSomething(this)">
<option value="abb">This is the second item</option>
<option value="abc" selected>This is the third item</option>
etc...
</select>
However I don't want the onChange event to fire (or I want the code triggered by onChange to be ignored) until the user selects an item. At the moment the onChange event fires as the page loads and the selected item is chosen by default.
Can I wrap this code in PHP to achieve this - if so how?
?!
Manipulating the HTML DOM directly in JavaScript doesn't fire events. You can even call myForm.submit() and the browser will not fire the form's onsubmit event, therefore bypassing client-side onsubmit validation.
I don't know what you've tried, but this is one way to select for example the first item of the drop-down list:
document.getElementsByTagName('select')[0].getElementsByTagName('option')[0].selected = true;
(http://jsfiddle.net/Jawh6/)
Crude, I know. Usually your forms and fields would be named or otherwise identified so you can address them more excplicitly: e.g. document.myForm.mySelect.options[0].selected = true;
Since your PHP is already setting the 'selected' attribute on the option (or your question isn't very well tagged), this would be the best place to set the default option when the page loads, that requires no JavaScript at all.
If you're interested in how to get PHP to write out the HTML for a select element and correctly assign the selected attribute to the intended option, I reckon you need to write a new question to attract the PHP folk.
Either you have other calls to your DoSomething function, or you've oversimplified your example and you're actually using a framework to bind the event handler to the field and maybe you accidentally called your function instead of assigning it, e.g.:
mySelect.onchange = DoSomething(); // oops, this calls DoSomething right away.
mySelect.onchange = DoSomething; // this sets DoSomething as the event handler.
I have a selectbox on my page, and it works excellently in every browser except IE. I've tested on 8 and 9, and I have the same issue. When I click an option, the .change() event fires, exactly like it should, but the options don't disappear until I either click again (which doesn't fire the click event, strangely), or click outside of the select box. This is no problem for me, since I use chrome, but I decent chunk of my users use IE8.
Here's the .change() function:
$('#configEquipDesc').change(function () {
alert($(this).val());
if ($(this).val() != 'unselected') {
ajaxGetConfig($(this).val());
}
});
Here's the HTML for the select.
<select name="configEquipDesc" id="configEquipDesc" data-native-menu="false" data-inline="true" class="configMenuEquip">
<option value="unselected" data-placeholder="true">Inspection</option>
</select>
More options are added using ajax, and that all works perfectly.
If this is a dynamically created selectbox, which I suspect it is, You need to use delagation. Try changing your jQuery to this:
$('body').on('change','#configEquipDesc', function () {
ajaxGetConfig($('option:selected', this).val());
});
and see if that fixes your problem.
EDIT - it's the selected option that you're trying to get the value of, correct? Not the select statement itself. So, here's a little trick to grabbing only the selected option and sending it to your ajaxGetConfig() function!!
This question has been asked tons of times, however I don't see any answer for the 'multiple' variety:
http://jsfiddle.net/queZ6/107/
When you tab INTO the box, i want to display an alert and capture the focus event. I'm basically wanting to change the highlighting for an element that surrounds each input, that follows along as you fill out the form. It's basically a signal to the user to easily see what field their on.
I can't for the life of me figure out how to capture the focus event though tabbing into the box (or also clicking on it obviously).
I dont see why this is difficult, considering you're typing INTO an input. Cant javascript see the newly created input (that youre typing into) and bind to that? JS is so confusing to me sometimes :S
Because the element is created dynamically, you will need to use event delegation, using jquery's on. This will allow you to attach a handler before the element exists.
$('.chzn-choices').focus(function(e){
would instead be
$("container").on("focus", '.chzn-choices',function(e){
where container is a selector for some static ancestor element which is not dynamically loaded. If no such container exists, document can be used, though this is to be avoided where possible.
Update:
While the old answer stated that you cannot bind into dynamically created elements(and this is still true to a degree), updates to the plugin in question have made this no longer a problem.
While the plugin in question still has a problem of triggering the handler multiple times, in the case of an alert message being used, it is now possible to bind to those dynamically created elements thanks to the updates.
All one must do in order to do this is bind, via .on(), to the chosen:showing_dropdown event on the original targeted select list.
To solve the problem of the continuously created alert boxes, however, I decided to use underscore.js's .debounce() method, so it is only triggered once immediately every 1 second.
The underscore library is by no means required, however you will need to have some sort of debounce function in order to get around that small quirk.
var debouncedAlert = _.debounce(window.alert, 1000, true);
$('#select').chosen();
$('#select').on('chosen:showing_dropdown', function(e){
e.preventDefault();
e.stopPropagation();
debouncedAlert('focused');
});
Working example:
$(document).ready(function() {
var debouncedAlert = _.debounce(window.alert, 1000, true);
$('#select').chosen();
$('#select').on('chosen:showing_dropdown', function(e){
e.preventDefault();
e.stopPropagation();
debouncedAlert('focused');
});
$('button').click(function() {
$('#select').trigger('chosen:open');
});
});
body {
margin: 10px;
}
select {
width: 200px;
}
<link href="https://harvesthq.github.io/chosen/chosen.css" rel="stylesheet"/>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script><script src="https://harvesthq.github.io/chosen/chosen.jquery.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/underscore.js/1.8.3/underscore-min.js"></script>
<input type="text" value="Put your cursor here then Press Tab. Chosen will be focused!" style="width:100%">
<br>
<select id="select" multiple>
<option value="1">abc</option>
<option value="2">def</option>
<option value="3">ghi</option>
</select>
<br>
<button>Press this button. Now chosen <b>will</b> be focused! :)</button>
Old answer:
No, it can't. Jquery's regular method of binding will not work with dynamically-created elements. In order to bind to those types of elements, you need .on().
$('.chzn-choices').focus(function(e){
e.preventDefault();
alert('focused!');
});
Would be changed to:
$('#select_chzn').on('focus', '.chzn-choices', function(e){
e.preventDefault();
alert('focused!');
});
In this case, you are delegating the event to the container elemen, and then pointing it to your specific element.
Working example
Is there a way to detect when the value of a select list is set to empty by a javasscript and not by the user? It seems that the change-event only triggers by mouse or keyboard.
And is there a way to detect when the number of options in a select list changes (added, removed)?
You have to trigger the change event manually, when you are changing the value of a select with javascript. E.g:
$('#myselect').val(10).change();
In this example the value is set to 10 and the change event is triggered. If there is an event handler attached to the select, it will be executed.
Use Jquery's change function
$("#idofselect").change(function(){ });
To answer your first question, not it's not possible to detect what caused the change in the select list in the change event itself.
However, if there is javascript code changing the select list you could add some logic in there to perform the tasks needed in this scenario.