I have an event handler attached to checkboxes. I am using bootstrap switch http://www.bootstrap-switch.org/
I am trying to get the state value which is either true or false into a variable so I can set it to the session value.
I can get the true or false value when the state changes (as seen in the rendered code). However, I would like to get this value within events. Please check my x variable.
client.js
Template.myTemplate.rendered = function () {
$('input[name="questions"]').bootstrapSwitch('state', true, true);
$('input[name="questions"]').on('switchChange.bootstrapSwitch', function(event, state) {
console.log(state); // true | false
});
html:
<template name="myTemplate">
<div class="row">
<input type="checkbox" name="questions" unchecked> Hobby?
</div>
<div class="row">
<input type="checkbox" name="questions" unchecked> Writer?
</div>
I am trying to get the value which is printed out in console.log(state) within the rendered code into a variable within my event so I can set the session to value to either true or false.
Template.myTemplate.events({
'click input': function(event) {
var x = $(this).is(":checked").val();
Session.set("statevalue", x);
console.log(Session.get("statevalue")); // this is not printing out anything
}
});
I think I have got a lot better sollution and not directly using JQuery:
Template.myTemplate.events({
'change input': function(event) {
var x = event.target.checked;
Session.set("statevalue", x);
console.log(Session.get("statevalue"));
}
});
Take care to see that I suggest you to use change instead of click in event.
If you define id for your checkboxes, you could use
event.target.checkboxID.checked
with in Template-event.
this will return true or false if checked or not.
You should use template instance:
Template.myTemplate.events({
'click input': function(event, template) {
var x = template.$('input').is(":checked").val();
Session.set("statevalue", x);
console.log(Session.get("statevalue"));
}
});
or maybe with 'target':
Template.myTemplate.events({
'click input': function(event) {
var x = $(event.target).is(":checked").val();
Session.set("statevalue", x);
console.log(Session.get("statevalue"));
}
});
Template.myTemplate.rendered = function () {
$('input[name="questions"]').bootstrapSwitch('state', true, true);
$('input[name="questions"]').on('switchChange.bootstrapSwitch', function(event, state) {
var x = $(event.target).is(":checked");
Session.set("statevalue", x);
console.log(Session.get("statevalue"));
});
}
'click .task_checkbox'(event){
const target = event.target;
var isChecked = $("#"+event.target.id).is(":checked").val();
console.log(isChecked);
},
The event object already has all the information needed.
Template.myTemplate.events({
'click input': function(event) {
if (event.target.name === 'questions') {
Session.set("statevalue", event.target.checked);
console.log(Session.get("statevalue"));
}
}
});
Related
I have a group of buttons with different values but same name (says "save"). When one of this button is clicked, a jquery event is triggered and sends the value of that exact button with an ajax call to the server. When the server responds with a success, I would like the value of that same clicked button to change into "saved". I have written a little function that does that, but the problem is that when you click on one of those buttons that say "save" and it's a success, all the values of the other buttons change into "saved". How can I change only the value of the clicked button and instead of all the buttons with the same name?
Here's my html:
<button class="homemade" name="saveArticle" value="v1">Save</button>
<button class="homemade" name="saveArticle" value="v2">Save</button>
Here's my Jquery function:
$(function() {
$('[name="saveArticle"]').bind('click', function() {
$.getJSON('/articles/save', {
article_id: this.value,
}, function(data) {
$("[name='saveArticle']").text(data.message);
});
return false;
});
});
use arrow functions then you can just use this to refer to the clicked button.
$(function() {
$('[name="saveArticle"]').bind('click', function() {
$.getJSON('/articles/save', {
article_id: this.value,
}, (data)=>{
$(this).text(data.message);
});
return false;
});
});
alternatively you could use the event target.
$(function() {
$('[name="saveArticle"]').bind('click', function(event) {
$.getJSON('/articles/save', {
article_id: this.value,
}, function(data) {
$(event.target).text(data.message);
});
return false;
});
});
Shouldn’t that do the trick to give you access to the element that was clicked?
$(function() {
$('[name="saveArticle"]').bind('click', function() {
// here `this` points to element on which event fired
$(this) // <-- creates jQuery object of it
});
});
I'm using selectize.js something like this:
$( 'select' ).selectize( {
onChange: function( value ) {
// how to get original element here?
}
} );
There's several select elements on the page.
I want to get select on which the event occurred inside of onChange.
How can I do it?
you can use $(this)[0] inside the onChange. Once this is the selectize object by itself
$( 'select' ).selectize( {
onChange: function( value ) {
var obj = $(this)[0];
alert(obj.$input["0"].id);
}
} );
Here's a Fiddle
you can get all user events from onInitialize :
$('select').selectize({
onInitialize: function (selectize) {
selectize.on('change', function (value) {
var elem = this.$input[0];
console.log('on "change" event fired > ' + elem.id);
});
selectize.on('focus', function () {
console.log('on "focus" event fired');
});
selectize.on('dropdown_open', function () {
console.log('on "dropdown_open" event fired');
});
}
}
I am trying to do something like Hijack the jQuery events of some elements, do a judgement, and then trigger the default handler if necessary.
Say I have a page with some inputs and buttons, and each of them are already bind with event handlers(click, focu key events, etc.) to do their jobs.
What I want to achieve is: whenever these elements' events are fired, I'd like to trigger my function first, this function will gather some data, and judge whether the execution should continue.
If no the corresponding handler should not be called like nothing happened.
If yes the original handler should be triggered with the original event data.
I don't want to change the default handlers to achieve this, so, is there a good way to do something like this?
Thanks
You could use the internal method _data()
/* add some event handlers */
$("button").on("click", function() {
console.log("Button clicked");
});
$("button").on("click", function() {
console.log("Button clicked 2");
});
/* hijack them */
var button = $("button"),
boundEvents = $._data(button.get(0)).events;
$.each(boundEvents, function(key, eventHandlers) {
// save the handlers from being "destroyed" by .off()
eventHandlers = eventHandlers.map(function(eh) {
return eh.handler;
});
// remove the event handlers
button.off(key);
// add the hijacked version
$.each(eventHandlers, function(idx, handler) {
button.on(key, function(e) {
if ($("#cb").prop("checked")) {
handler(e);
} else {
console.log("nothing to do...");
}
});
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<input type="checkbox" id="cb" />
<br />
<button>Click me</button>
Try defining function at .data() of each that has events attached which is called at if condition within handler. If function returns true , do stuff , if function returns false do not do stuff
$("div").on("click", function() {
// if `check` returns `true`, do stuff
if ($(this).data().check()) {
console.log(this.tagName)
}
});
$("input").on("focus", function() {
// if `check` returns `true`, do stuff
if ($(this).data().check()) {
console.log(this.tagName)
}
});
var elems = $("*").filter(function(i,el) {
return $._data(el).events !== undefined
})
elems.each(function(i, el) {
$(el).data().check = function() {
// define condition here
// if element has `css` `color` property set to `"blue"`
// return `true`, else return `false`
if ($(el).css("color") === "rgb(0, 0, 255)") return true
else return false
}
});
div {
color:blue;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js">
</script>
<div>click</div>
<input type="text" />
<span>text</span>
i am trying to create jQuery plugin which needs to trigger on keyup of input tag.
But, somehow its not working :(
I've tried it so far:
JS:
$.fn.search_panel = function() {
if($(this).prop("tagName").toLowerCase() == 'input'){
var input_str = $.trim($(this).val());
console.log($(this));
onkeyup = function(){
console.log(input_str);
}
}
};
Plugin Initialization
$(document).ready(function(){
$('input').search_panel();
});
HTML:
<input type="text" />
From the above code, it only console when page loads for the first time, but after entering anything in input box it doesn't console.
You're inadvertantly binding to the window's onkeyup event. You should use $(this).on instead to bind to the individual keyup event on each input:
$.fn.search_panel = function() {
// Iterate all elements the selector applies to
this.each(function() {
var $input = $(this);
// Can probably make this more obvious by using "is"
if($input.is("input")){
// Now bind to the keyup event of this individual input
$input.on("keyup", function(){
// Make sure to read the value in here, so you get the
// updated value each time
var input_str = $.trim($input.val());
console.log(input_str);
});
}
});
};
$('input').search_panel();
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input><input><input><input>
Add keyup event inside plugin and bind it to current input,
$.fn.search_panel = function () {
if ($(this).prop("tagName").toLowerCase() == 'input') {
$(this).keyup(function () {
var input_str = $.trim($(this).val());
console.log($(this));
console.log(input_str);
});
}
};
Demo
I am trying to remotely activate a checkbox in Meteor from another point on the page. For some reason, the checkbox does not trigger the click. Other jQuery events such as remove() are working. Below is the code:
'click .selectPill': function(e, template) {
var name = $(e.target).attr('for');
var input = $(template.find('input[name='+name+']')).trigger('click');
$(e.target).toggleClass('pillChecked');
}
Is there something in Meteor that is preventing this from working...or am I doing this wrong?
Change event will do the trick
Template.templateName.events({
'click .selectPill': function(e) {
var name = $(e.target).attr('for');
if ($("input[name='+name+']").attr('checked') == 'checked'){
$("input[name='+name+']").trigger('change').removeAttr('checked');
}
else{
$("input[name='+name+']").trigger('change').attr('checked', 'checked');
}
},
'change #input':function(e){
alert("value changed");
}
})