jQuery UI Multiselect Events - javascript

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

Related

Simulate human selection of option item in select menu

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

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>

Why the jQuery classes are not working for the HTML elements generated from AJAX response?

I'm using PHP, jQuery, Smarty, etc. for my website. I'm having a HTML form. In this form there is a select control and couple of calendar controls. Some classes are added to these controls to achieve some javascript functionality. When the form loads for the first time the classes applied to these controls work but when I append the same controls with the same classes applied to them, the javascript functionality doesn't work. Why this is happening and how to resolve this issue? For your reference I'm putting below the small snippets of codes:
HTML Code:
<input class="form-control date_control" placeholder="yyyy-mm-dd" type="date" name="rebate_start_date[1]" id="rebate_start_date_1" value="{$data.rebate_start_date}">
<input class="form-control date_control" placeholder="yyyy-mm-dd" type="date" name="rebate_expiry_date[1]" id="rebate_expiry_date_1" value="{$data.rebate_expiry_date}">
<select class="states" multiple="multiple" name="applicable_states[1]" id="applicable_states_1">
<option value="1">Alabama</option>
<option value="2">Alaska</option>
<option value="3">Arizona</option>
<option value="4">Arkansas</option>
<option value="5">California</option>
</select>
The AJAX response from PHP file is as follows:
$rebate_no = $_POST['rebate_no'];
$states = '';
foreach ($state_list as $key => $value) {
$states .= "<option value=".$value['id'].">".$value['state_name']."</option>";
}
<input class='form-control date_control' placeholder='yyyy-mm-dd' type='date' name='rebate_start_date[$rebate_no]' id='rebate_start_date_$rebate_no' value=''>
<input class='form-control date_control' placeholder='yyyy-mm-dd' type='date' name='rebate_expiry_date[$rebate_no]' id='rebate_expiry_date_$rebate_no' value=''>
<select class='states' multiple='multiple' name='applicable_states[$reabate_no]' id='applicable_states_$reabate_no'>
$states
</select>
The actual code is very large. I've put in only small and necessary part of my code. Would you please help me in this regard please? Thanks in advance.
The jQUery AJAX function code is below:
$(function() {
$(".add_new_rebate").on("click", function(event) {
event.preventDefault();
var manufacturer_id = $("#company_id").val();
/*if($.active > 0) { //or $.active
request_inprogress();
} else {*/
var next_rebate_no = $('.rebate_block').length + 1;
var rebate_no = $('.rebate_block').length + 1;
if ($('.rebate_block').length>0) {
rebate_no = rebate_no+1;
}
$('.add_new_rebate').attr('disabled','disabled');
//}
$.ajax({
type: "POST",
url: "add_rebate_by_product.php",
data: {'request_type':'ajax', 'op':'create_rebate', 'next_rebate_no':next_rebate_no, 'rebate_no':rebate_no, 'manufacturer_id':manufacturer_id},
beforeSend: function() {
$('.table-responsive').after("<img src='http://localhost/smart-rebate-web/web/img/ajax-loader.gif' class='load' alt='Loading...'>");
},
success: function(data) {
if(jQuery.trim(data)=="session_time_out") {
window.location.href = site_url+'admin/login.php?timeout=1';
} else {
$('.rebate_block').append(data);
$('.add_new_rebate').removeAttr('disabled');
}
$('.load').remove();
}
});
});
});
because jQuery parses only loaded DOM, it doesn't work with something, that was added to DOM after jQuery processed it. look at "on" function in jQuery API
Like others have mentioned, when you have jquery handlers on present elements they work fine, but the new elements are not binded to those handlers and that's the reason we need to use the .on() method.
So for the newly created elements, we are going to attach a click event handler or any event for that matter as:
.states:
$(document).on('change','.states',function(){
//on change of select
});
.date_control:
$(document).on('click','.date_control',function(){
//on click of input .date_control
});
DEMO
You Have to add .on
if jquery > 1.7
$('#parent-selector').on('click', 'child-selector', funcion(){})
Child selector is a selector that is just added.
You need to add add event in this style for new elements added dynamically on the page
Till jquery 1.7 you can you .live('click')
I had this problem too, but I found the answer.
Just like I Can Has Kittenz said. You .on() function will do the trick.
On the jQuery website here
Event handlers are bound only to the currently selected elements; they must exist on the page at the time your code makes the call to .on(). To ensure the elements are present and can be selected, perform event binding inside a document ready handler for elements that are in the HTML markup on the page. If new HTML is being injected into the page, select the elements and attach event handlers after the new HTML is placed into the page. Or, use delegated events to attach an event handler, as described next.
Which means that if you are calling ajax code (event handlers that weren't there when the code was loaded) you need to bind it to an element that was there.
Here is an example:
$( "body" ).on( "click", "p", function() {
alert( $( this ).text() );
});
You can see that on the link above too. There it shows how it works.

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.

How do I make the html select options work in Meteor?

I am having trouble getting an HTML Select Options to work the way I think it should work in Meteor.
Here is an example of how it would work with buttons for a collection called Countries.
Template
{{#each get_countries}}
<button class="btn btnCountryTest">{{iso3}} - {{name}} </button><br />
{{/each}}
Client event handler
'click .btnCountryTest': function(event){
console.log('clicked .btnCountryTest this._id: ' + this._id);
}
Produces the correct output such as.
clicked .btnCountryTest this._id: 39cd432c-66fa-48de-908b-93a874323e2e
Now, what I want to be able to do is trigger other on page activity when an item is selected from an HTML Select Options drop down. I know I could put the ID in the options value and then use Jquery etc... I thought it would "just work" with Meteor but I can't figure out how to do it.
Here is what I am trying and it is not working.
Template
<select class="input-xlarge country" id="country" name="country">
{{#each get_countries}}
<option value="{{iso3}}">{{name}}</option>
{{/each}}
</select>
Handler
'click #country': function (event) {
console.log('Template.users_insert.events click .country this._id: ' + this._id);
}
Which produces
Template.users_insert.events click .country this._id: undefined
Clearly not what I had expected. Any ideas anyone before I resort to Jquery form processing?
Thanks
Steeve
In Meteor, each helper calls Meteor.ui.listChunk (please take a look at packages/templating/deftemplate.js), which treats the current variable as this context.
In other words, it's the global context in click #country, and you can only access this._id under each block, like in the click #country option event.
I think you can put the data in HTML data attribute, and access it using jQuery. Just like this -
Template
<select class="input-xlarge country" id="country" name="country">
{{#each get_countries}}
<option value="{{iso3}}" data-id={{_id}}>{{name}}</option>
{{/each}}
</select>
Handle
'click #country': function (event) {
console.log('Template.users_insert.events click .country this._id: ' + $(event.currentTarget).find(':selected').data("id"));
}
If you're trying to get to the data context, you need to give your event handler access to the template argument, and use it's data object. That is the top level data context.
'click #country': function (event, template) {
console.log('Template.users_insert.events click .country _id: ' + template.data._id);
}
should work. Here's the best documentation I can find on this: http://docs.meteor.com/#template_data
#StevenCannon, I had a similar issue and found a solution here - http://www.tutorialspoint.com/meteor/meteor_forms.htm. #DenisBrat is correct, listen for the change event instead of the click event.
Here's the solution modified for you:
'change select'(event) {
// Prevent default browser form submit
event.preventDefault();
var selectedCountry = event.target.value;
console.log('Template.users_insert.events change select iso3: ' + selectedCountry);
}
You're listening for the 'click' event of the select. You'd really like to subscribe to the 'change' event. 'Click' occurs when you click on a html element. On the other hand, 'change' event gets triggered after you select a value from the list.
Maybe you can also take a look at 'packages/liveui/liveui.js'. There is a findEventData function, which give the callback this object.

Categories