I have some issue understanding the jQuery().change() behavior.
The HTML is basically a lot of input elements - checkboxes ( each with ID of id^='o99-post-visible-XXX' - and they are pure CSS images as Checkboxes, but this is irrelevant ) and I have another checkbox ("#o99-check-all") to "check all" and a text input field ('#o99-post-visible-ids') that receives the IDs of the selected boxes.
The jQuery code is as follows:
jQuery(document).ready(function() {
jQuery("#o99-check-all").change(function () {
jQuery("input:checkbox[id^='o99-post-visible-']").prop('checked', jQuery(this).prop("checked")).trigger('change');
});
var checkboxes = jQuery("input.o99-cbvu-posts-checkbox:checkbox");
checkboxes.on('change', function() {
// get IDS from all selected checkboxes and make a comma separated string
var ids = checkboxes.filter(':checked').map(function() {
return this.value;
}).get().join(',');
// put IDS inside a text input field
jQuery('#o99-post-visible-ids').val(ids);
// console.log(ids);
});
});
Now, more or less everything works now, but that is not the issue.
at first , the first chunk of code was:
jQuery("#o99-check-all").change(function () {
// without .trigger('change') chained
jQuery("input:checkbox[id^='o99-post-visible-']").prop('checked', jQuery(this).prop("checked"));
});
and it did not work ( why?? ) - meaning the boxes were selected as expected but the '#o99-post-visible-ids' input field was not receiving the IDs - until I chained a .trigger('change') event - when suddenly it works well.
my confusion is with the following ( which perhaps for my little understanding of jQuery internal works is counter-intuitive )
after chain adding .trigger('change') - isn't it somehow an endless loop where a chain() event is trigger inside a listener of change() ? and if not why?
Why is the code functioning now and did not function correctly before? because again, for my understanding, there was a change, even if not triggered by direct user click. Why would I need to trigger it manually?
I'm not sure I understand what you mean. What is happening now, is that whenever you change the all checkbox, the other checkboxes will be checked/unchecked the same as all, and then the change event is triggered.
Because you added a listener for change, that function will then fire. I.e. this function will run:
function() {
// get IDS from all selected checkboxes and make a comma separated string
var ids = checkboxes.filter(':checked').map(function() {
return this.value;
}).get().join(',');
// put IDS inside a text input field
jQuery('#o99-post-visible-ids').val(ids);
// console.log(ids);
}
Without your .trigger("change") (or .change() in short), you only change a property of the inputs. So the object changes, indeed, but that does not mean the change event is triggered. It does sound counter-intuitive, but events are only triggered by user actions or if you call the event explicitly - in no other way do events get triggered.
its because you have written jQuery('#o99-post-visible-ids').val(ids); inside a function which happens only when the change event done on the inputs, assigning prop directly through .prop does not trigger the change event and so the result handler wont run
Now if I understand you correctly...
...because you're giving every check box the same ID? If you wish to apply it to more than a single element, it is best practice to use a class selector instead.
jQuery(".o99-check-all").change(function () {
// without .trigger('change') chained
jQuery(".o99-check-all").prop('checked', jQuery(this).prop("checked"));
});
See link
https://api.jquery.com/change/
Related
I use an input field to submit 2 pieces of data to an event handler: the displayed value and a property value.
When I populate the data, I do this:
xInput.val('ARC'+opts[0].arc);
xInput.prop('data-sine',opts[0].sine);
// Now, trigger submit-handler
xInput.show();
xInput.trigger('change');
When I stop in the debugger, I can see that the property data-sine exists on the jQuery object and has the correct data.
Now, in the change event, I want to move the data from the "element" onto the event so the astrosearch API invocation can pick it up using a generic event handler, which also handles input from a <SELECT> tag in cases where there is more than one arc to choose from. So, I do this:
xInput.on('change', function (e) {
e.sine = $(this).attr('data-sine');
astrofinder.findAstro(e, true);
astrofinder.ui.countdown.start(function () { xInput.trigger('find'); });
});
When I stop at the first line here, this is NOT the xInput jQuery object, it's the raw HTML element - BUT the element DOES NOT HAVE a data-sine property! Somehow, it didn't make it out of jQuery into the DOM?
Why? Do I need to use a timer to get into the next event loop?
Hey I've got a problem with fireing a change-event manually.
So I have a selectOneMenu (i'ts like a dropdown in jsf) with different values.
If I choose a value of this dropdown-list, a datatable should be updated. This works correctly, if i choose this value manually.
Now there is a case, where I need to insert a new value to the selectOneMenu. This new value gets selected automatically, but the change-event to update the datatable doesn't get fired...
So basically I have this button to save a new value to the selectOneMenu which then gets selected correctly, but the datatable doesn't get updated, which is why I tried to write the function fireChange() and gave that to the oncomplete of the button:
<p:commandButton ajax="true" id="seatingPlanSave" actionListener="#{EventAssistentController.createSeatingPlan}" value="#{msg.save}" update=":createEvent:EventSeatingPlan, :createEvent:ticketTypePrices" oncomplete="fireChange()"/>
For the fireChange()-function, i tried a few different things:
function fireChange() {
var element = document.getElementById("createEvent:EventSeatingPlan_input");
element.change();
}
function fireChange() {
var element = document.getElementById("createEvent:EventSeatingPlan_input");
$(element).trigger("change");
}
function fireChange() {
if ("fireEvent" in element)
element.fireEvent("onchange");
else {
var evt = document.createEvent("HTMLEvents");
evt.initEvent("change", false, true);
element.dispatchEvent(evt);
}
}
But none of these work :(
Can you please tell me how I can achieve this?
Thanks, Xera
You didn't tell anything about the HTML representation of createEvent:EventSeatingPlan_input while that's mandatory for us (and you!) in order to know how to let JS intercept on that. You didn't tell either if you were using <h:selectOneMenu> or <p:selectOneMenu>, so we can't take a look ourselves in the generated HTML representation. The former generates a <select><option> while the latter generates an <div><ul><li> which interacts with a hidden <select><option>. Both representations of dropdown menus require a different approach in JS. Also, information about how you're registering the change event handler function is mandatory. Is it by hardocing the onchange attribute, or by embedding a <f:ajax> or <p:ajax>?
In any way, based on the information provided so far, I'll guess that you've a
<h:selectOneMenu ...>
<f:ajax render="dataTableId" />
</h:selectOneMenu>
which will generate a <select onchange="..."><option>.
As per your first attempt:
function fireChange() {
var element = document.getElementById("createEvent:EventSeatingPlan_input");
element.change();
}
This will fail on <h:selectOneMenu> because HTMLSelectElement interface doesn't have a change property nor method. Instead, it is onchange property which returns a event handler which can directly be invoked by appending ().
The following will work on <h:selectOneMenu>:
function fireChange() {
var element = document.getElementById("createEvent:EventSeatingPlan_input");
element.onchange();
}
However this will in turn fail in <p:selectOneMenu>, because it returns a HTMLDivElement instead of HtmlSelectElement. The HTMLDivElement doesn't have a onchange property which returns an event handler. As said, the <p:selectOneMenu> generates a <div><ul><li> widget which interacts with a hidden <select><option>. You should be registering this widget in JS context and then use its special triggerChange() method.
So, given a
<p:selectOneMenu widgetVar="w_menu" ...>
<p:ajax update="dateTableId" />
</p:selectOneMenu>
this should do
function fireChange() {
w_menu.triggerChange();
}
I have a dropdown box that has a list of institutions in it. Now if I manually select an option, it works and I am able to grab the correct value.
However, I have a select rates button which uses JavaScript to pull up a rate sheet. You select a rate from that sheet and it will select an option from the dropdown for you (one that corresponds with the rate from the rate sheet). If I use this method, it doesn't trigger a .change() therefor I can't get a value for the selected option.
$('#id_financial_institution').change(function () {
var value = $("#id_financial_institution option:selected").text()
$("fi").text(value);
});
Any suggestions? I have tried .change() and .click() but nothing.
Once you are in the change function you don't have to do another search or selector because you already have the object you just have to find the selected option from it. So you can try this:
$('#id_financial_institution').change(function () {
var value = $(this).find("option:selected").text();
$("fi").text(value);
});
If the code still doesn't return you answer start to add alerts at each point to see where you are and what values you have and work your way from there?
Rather than .text() use .val()
$(function() {
$('#id_financial_institution').change(function () {
var value = $("#id_financial_institution option:selected").val()
alert(value);
});
})
Here is a sample demo, without your html. I am just alerting the value.
DEMO
You're going about this all wrong. You already have the select element in this, all you need is the value of that select element.
$('#id_financial_institution').change(function () {
var value = $(this).val();
$('#fi').text(value); //i assume `fi` is an [id]
//do more stuff
});
I went inside my AJAX call and got the value of the fields I needed there. For some reason, when using the AJAX call, it wouldn't fire the .change() on that particular field.
Thanks for all your input everyone.
I am trying to fetch the changed input filed value using jquery which is getting changed javascript event of drop down select.
I simply am not getting where exactly the things are getting wrong. It is something related to dom tree refresh (.live)? Any help/suggestions would be great. Thanks.
/* adding the value to user_val input field id in javascript onload function based on drop down select event*/
document.getElementById('user_val').Value = "abcd";
/* then trying to get value which changed */
$(document).ready(function() {
$("#submits").click(function() {
alert($("#user_val").val());
});
You haven't closed your click event handler function. Change it to this:
$(document).ready(function() {
$("#submits").click(function() {
alert($("#user_val").val());
});
});
And change Value to value (note the lowercase "v"), and then it should work fine.
Two errors you got there:
You should use document.getElementById('user_val').value = "abcd"; and not document.getElementById('user_val').Value = "abcd"; (lower case value, not Value).
You should also close the ready event after your click event.
Here is the complete working solution:
/* adding the value to user_val input field id in javascript onload function based on drop down select event*/
document.getElementById('user_val').value = "abcd";
/* then trying to get value which changed */
$(document).ready(function() {
$("#submits").click(function() {
alert($("#user_val").val());
});
});
I have a dropdown select list on my page of class="TypeFilter".
I have a jQuery event that fires when a value in that list is selected.
$(".TypeFilter").change(function()
{
// Extract value from TypeFilter and update page accordingly
));
I now have to add another list to the page, and I want to implement functionality which will prevent the .change(function() from running unless both are selected.
In both lists the first option in the list is some text instructing the user to select one of the items, so I was thinking of just writing some logic to test that both lists have a selected index greater than 0.
I think this is a touch unclean though, especially considering that other pages that have a TypeFilter use the same logic.
Is there any nifty functionality in jQuery that can do this?
edit I should specify that the user needs to be able to update the page by selecting either dropdown, so I can't put the onchange on the second element and test that the first element has a selected value, as suggested in one of the answers
If you bind the same event to all dropdowns, you can get a collection of all the dropdowns and check that all of them are selected. Example:
$('.Dropdown').change(function(){
var elements = $('.Dropdown');
if (
elements.filter(function(){
return this.selectedIndex > 0;
}).length == elements.length
) {
// all dropdowns are selected
}
});
As you partly mention, put the onchange on the second element and test that the first element has a selected value before you fire off any logic.
Use bind instead, and as the eventdata, send a function that checks that either that both are selected or that the other is selected. Untested code:
function checker() {
// test your conditions
}
$(".TypeFilter").bind('change', {test: checker}, function(event)
{
if (event.data.test && event.data.test()) {
// Extract value from TypeFilter and update page accordingly
}
));
This way the other pages that use the same function will not notice any changes.