Perform a action when checkbox is clicked Backbone - javascript

I basically want to know when the user has clicked the checkbox. If checkbox is clicked then I want the div to output a msg and once checkbox is not checked then output another msg but user has to check first. The checkbox gets created dynamically. But somehow I dont know what the value is.
There are 2 problems:
When checkbox is clicked, the check mark does not stay
If checkbox is clicked, a value does not output on the div
Here is a example:
http://jsfiddle.net/8GjdS/103/
Code:
var myView = Backbone.View.extend({
events: {
'click #check': 'checkboxHandler'
},
initialize: function() {
_.bindAll(this, 'checkboxHandler');
},
checkboxHandler: function(e) {
var filter = $('#check').is(':checked');
console.log(filter);
$('#out').append(filter);
return false;
},
});
var v = new myView({el: '#view-goes-here'});
v.render();
$('#view-goes-here').append('<div class=divs" align="right"><input id="check" type="checkbox" value=""><font size="4">check</font></input></div>');

There are a couple of issues.
First: When you return false from an event handler (or trigger event.preventDefault() you stop the event from bubbling up. That means, you handle the event yourself and it will never trigger the usual action -- in this case, it means the checkbox will never change. You should return true instead, in your checkbox handler.
Second: The value is not appended to your out div because you call the append function with a boolean as the argument. The easiest way in this case is probably to "cast" it to a string like so:
$('#out').append('' + filter);
Third: While it's a workable approach to listen for the click event, it could be argued that it's more correct to listen for the change event instead. From MDN:
The change event is fired for <input>, <select>, and <textarea> elements when a change to the element's value is committed by the user.
Here is an updated fiddle: http://jsfiddle.net/jzvzgdp4/

Related

what is the best jsript event handler to use when data is change through other script for select? [duplicate]

The logic in the change() event handler is not being run when the value is set by val(), but it does run when user selects a value with their mouse. Why is this?
<select id="single">
<option>Single</option>
<option>Single2</option>
</select>
<script>
$(function() {
$(":input#single").change(function() {
/* Logic here does not execute when val() is used */
});
});
$("#single").val("Single2");
</script>
Because the change event requires an actual browser event initiated by the user instead of via javascript code.
Do this instead:
$("#single").val("Single2").trigger('change');
or
$("#single").val("Single2").change();
I believe you can manually trigger the change event with trigger():
$("#single").val("Single2").trigger('change');
Though why it doesn't fire automatically, I have no idea.
Adding this piece of code after the val() seems to work:
$(":input#single").trigger('change');
As far as I can read in API's. The event is only fired when the user clicks on an option.
http://api.jquery.com/change/
For select boxes, checkboxes, and
radio buttons, the event is fired
immediately when the user makes a
selection with the mouse, but for the
other element types the event is
deferred until the element loses
focus.
To make it easier, add a custom function and call it whenever you want to change the value and also trigger a change:
$.fn.valAndTrigger = function (element) {
return $(this).val(element).trigger('change');
}
and
$("#sample").valAndTrigger("NewValue");
Or you can override the val() function to always call the change when val() is called:
(function ($) {
var originalVal = $.fn.val;
$.fn.val = function (value) {
this.trigger("change");
return originalVal.call(this, value);
};
})(jQuery);
Sample at http://jsfiddle.net/r60bfkub/
In case you don't want to mix up with default change event you can provide your custom event
$('input.test').on('value_changed', function(e){
console.log('value changed to '+$(this).val());
});
to trigger the event on value set, you can do
$('input.test').val('I am a new value').trigger('value_changed');
If you've just added the select option to a form and you wish to trigger the change event, I've found a setTimeout is required otherwise jQuery doesn't pick up the newly added select box:
window.setTimeout(function() { jQuery('.languagedisplay').change();}, 1);
I ran into the same issue while using CMB2 with Wordpress and wanted to hook into the change event of a file upload metabox.
So in case you're not able to modify the code that invokes the change (in this case the CMB2 script), use the code below.
The trigger is being invoked AFTER the value is set, otherwise your change eventHandler will work, but the value will be the previous one, not the one being set.
Here's the code i use:
(function ($) {
var originalVal = $.fn.val;
$.fn.val = function (value) {
if (arguments.length >= 1) {
// setter invoked, do processing
return originalVal.call(this, value).trigger('change');
}
//getter invoked do processing
return originalVal.call(this);
};
})(jQuery);
$(":input#single").trigger('change');
This worked for my script. I have 3 combos & bind with chainSelect event, I need to pass 3 values by url & default select all drop down. I used this
$('#machineMake').val('<?php echo $_GET['headMake']; ?>').trigger('change');
And the first event worked.
To change the value
$("#single").val("Single2");
Also to trigger a change event
$("#single").val("Single2").change();
this logic is instrumental when multiple select options are on a page.
one changes and other select options have to change but do not trigger a change event.

Why "event.currentTarget.checked" when clicking on checkbox is not correct?

We have a backbone program which will listen on a checkbox. When user clicks on the checkbox, it will trigger a function, but the problem is that the event.currentTarget.checked is not correct.
Say, there is a template contains a checkbox:
<input type="checkbox" id="show_user" />
It binds to a backbone view, and have such events:
events: {
"click #show_user": "toggle"
},
toggle: function(event) {
this.model.set("show_user", event.currentTarget.checked);
}
So if I clicked the checkbox to select it, I hope event.currentTarget.checked is true. But when we run karma test on Chrome(with debugger), we clearly see that it is false!
If we keep running the debugger line by line, it will be true after a while.
Why it has such behavior? Is there any other stable way to get the checked status of a checkbox?
Update:
I think I'm missing some important information. When I say click on the checkbox, I mean in the jasmine test, I write:
$("#show_user").click()
In this case, the event parameter in the method toggle is too early received that the state of the checkbox itself has not been changed yet. If I put it in a setTimeout with very short time, say:
toggle: function(event) {
setTimeout(function() {
this.model.set("show_user", event.currentTarget.checked);
}, 1);
}
The event.currentTarget.checked will be correct.
Now I changed it to change:
events: {
"change #show_user": "toggle"
}
And in my test, I won't use .click(), instead, I write:
var checkbox = $("#show_user");
checkbox.prop("checked", !checkbox.prop("checked"));
checkbox.change();
to change the state of the checkbox and trigger a change event. Now it's working well!

Trigger click event manually in Dojo CheckBox

In my application, I have this code:
postCreate: function(){
// ...
// Change the listWidget's order depending on whether the checkbox is
// ticked or not
self.extraWidget.orderByNameWidget.on( 'click', function( e ){
var orderByNameWidget = this;
field = orderByNameWidget.get('value') ? 'firstName' : 'lastName';
// Make up the collection with the initial filters
var collection = self.store;
if( self.initialFilter ) collection = collection.filter( self.initialFilter );
collection = collection.sort( field );
self.listWidget.set('collection', collection);
});
This code is there so that the user can click on a checkbox (orderByNameWidget), and change the sorting of contacts.
orderByNameWidget is a normal Dojo CheckBox.
Now, I have a global setting of what that value should be to start with. The neater way to deal with it would be setting the value of the checkbox, and then trigger the event:
// Artificially emit the initial click if the default says so
if( ConfigVars.workspacesUsersInfo.orderByNameDefault ){
self.extraWidget.orderByNameWidget.set( 'value', true );
self.extraWidget.orderByNameWidget.emit( 'click', { bubbles: true, cancelable: true });
}
While the first line works (setting the widget), the second one doesn't -- the 'click' event is never actually triggered for the widget.
I tried every single possible combination, emitting this event on the domNode etc. -- but no, it doesn't seem to want to do anything.
In Button.html, the basis for CheckBox, Dojo has:
data-dojo-attach-event="ondijitclick:__onClick"
I wonder if that's the problem. So... what should I write for a full simulation of the checkbox click? Any pointers?
Is there a reason why you can't use the change event instead of click to begin with? That ought to fire on both user clicks and programmatic changes. (And keyboard events, for that matter, which click likely won't fire on.)

knockout js radio button click event reset selection

I have bind "checked" and "click" event on a radio button list. But whenever a radio button is clicked, the selection does not stay. I must be doing something really wrong. Really appreciate if you guys can point me to the right direction.
Please see the Fiddle Here
View model:
var viewModel = {
wantsSpam: ko.observable(true),
spamFlavor: ko.observable('cherry'),
click: function(model){
console.log(model);
}
};
View:
<input type="radio" name="flavorGroup" value="cherry"
data-bind="checked: spamFlavor, click:click" />
From the click event documentation:
By default, Knockout will prevent the click event from taking any default action.
...
However, if you do want to let the default click action proceed, just return truefrom your click handler function.
So your radio button is reset because of your click handler and to fix it you just need to return true at the end:
click: function(){
alert('Hi');
return true;
}
Demo JSFiddle.
Basically, your click handler won't end up catching that you want to retain the value.
What is happening is that it is going back to default after you select an item.
Simply try:
return true;
As the only code in your handler.
Fiddle away: http://jsfiddle.net/SinisterSystems/jhHkD/4/
You just remove the click event or use return true from click event. Because Knockout prevent the click event from taking any default action. This means that if you use the click binding on an a tag (a link), for example, the browser will only call your handler function and will not navigate to the link’s href
var viewModel = {
wantsSpam: ko.observable(true),
spamFlavor: ko.observable('cherry'),
/*click: function(){
alert('Hi');
}*/
};
Or
var viewModel = {
wantsSpam: ko.observable(true),
spamFlavor: ko.observable('cherry'),
click: function(){
alert('Hi');
return true;
}
};

Change event precedence with JQuery

I have the following html code:
<input type="text" id="theInput" value=""/>
Click me
I want to detect when the input changes and perform an operation in this case, but ONLY when the user has not clicked in the link. I have tried this:
$('#theLink').live('click', function(){
alert('click');
});
$('#theInput').live('change', function(){
alert('change');
});
However change is always executed before click when the value in the input changed, due to Javascript event precedence rules, and therefore only "change" message is displayed.
I would like it to display change only if the input value changed and the user exited the input clicking in any other place instead of the link. In that last case I would like to display click.
The example is here.
I use jQuery 1.6.4.
As far as I know, the click event fires after the blur and change events in every browser (have a look at this JSFiddle). The order of blur and change is different across browsers (source: Nicholas Zakas).
To solve your problem, you could listen to click events on the document and compare the event's target with #theLink. Any click event will bubble up to the document (unless it is prevented).
Try this:
var lastValue = '';
$(document).click(function(event) {
var newValue = $('#theInput').val();
if ($(event.target).is('#theLink')) {
// The link was clicked
} else if (newValue !== lastValue) {
// Something else was clicked & input has changed
} else {
// Something else was clicked but input didn't change
}
lastValue = newValue;
});
JSFiddle: http://jsfiddle.net/PPvG/TTwEG/
Both events will fire but in your example the alert in the onchange event handler fired when the onmousedown event occurs will stop the onmouseup event required for the onclick event to fire. Using console.log will show both events firing.
http://jsfiddle.net/hTqNr/4/
Ok, now i got it, you could do
$('#theLink').live('click', function(e){
alert('click');
});
$('#theInput').live('change', function(e){
//Check if the change events is triggerede by the link
if(e.originalEvent.explicitOriginalTarget.data === "Click me"){
//if this is the case trigger the click event of the link
$('#theLink').trigger("click");
}else{
//otherwise do what you would do in the change handler
alert('change');
}
});
Fiddle here http://jsfiddle.net/hTqNr/19/
why you dont pick the value of input box. you have to store initial value of input box on ready function
initialvalue= $('#theInput').val();
then compare the value
$('#theLink').live('click', function(){
var newvalue =$('#theInput').val();
if(newvalue!=initialvalue) {
//do something
}
});

Categories