jQuery trigger change event function - javascript

I have a change function in javascript who permit me to do an action when the user click on a chekbox who's name is "nameCheckbox" so i have this script.
$("input[name='nameCheckbox']").each(function()
{
var object = creatObject($(this).val());
$(this).change(function()
{
if($(this).is(':checked'))
{
var object = creatObject($(this).val());
}
else
{
object.remove();
}
});
});
But i want to have another checkbox who permit to check or uncheck all the checkbox who's name is "nameCheckbox" and pass by the function change of all the element. So i have this code.
$("[name='allCheck']").change(function()
{
var selectAll = false;
if($(this).is(":checked"))
{
selectAll = true;
}
$("input[name='nameCheckbox']").each(function()
{
if(selectAll)
{
$(this).prop('checked',true);
}
else
{
$(this).prop('checked',false);
}
//And here i want to do something like $(this).change();
});
});
Thank you

$(this).change() should work, according to change()
Description: Bind an event handler to the "change" JavaScript event,
or trigger that event on an element.
This is effectively the same as using trigger()
$(this).trigger('change');

Related

Onlick event not triggering which contains blur function

I have a form and on click on an input, I'm adding classes to that input's wrapped div.
To do this, I've made use of blur and executing my function on click. However, on some cases (very rarely) it will work (and add the class). But majority of the time, it doesn't perform the click action (because the console.log("click") doesn't appear).
My thinking is that maybe the browser is conflicting between the blur and click. I have also tried changing click to focus, but still the same results.
Demo:
$(function() {
var input_field = $("form .input-wrapper input");
$("form .input-wrapper").addClass("noData");
function checkInputHasValue() {
$(input_field).on('blur', function(e) {
var value = $(this).val();
if (value) {
$(this).parent().closest(".input-wrapper").removeClass("hasData noData").addClass("hasData");
} else {
$(this).parent().closest(".input-wrapper").removeClass("hasData noData").addClass("noData");
}
});
}
$(input_field).click(function() {
checkInputHasValue();
console.log("click");
});
});
i've done some modification in your code .
function checkInputHasValue(e) {
var value = $(e).val()
if (value) {
$(e).parent().closest(".input-wrapper").removeClass("hasData noData").addClass("hasData");
} else {
$(e).parent().closest(".input-wrapper").removeClass("hasData noData").addClass("noData");
}
}
$(document).on('blur',input_field, function(e) {
checkInputHasValue($(this));
});
$(document).on("click",input_field,function() {
checkInputHasValue($(this));
console.log("click");
});
In order to avoid conflits between events, you would separate the events and your value check. In your code, the blur event may occur multiple times.
The following code seems ok, as far as I can tell ^^
$(function() {
var input_field = $("form .input-wrapper input");
$("form .input-wrapper").addClass("noData");
function checkInputHasValue(el) {
let target = $(el).closest(".input-wrapper");
var value = $(el).val();
$(target).removeClass("hasData noData");
$(target).addClass(value.length == 0 ? "noData" : "hasData");
console.log("hasData ?", $(target).hasClass("hasData"));
}
$(input_field).on("click", function() {
console.log("click");
checkInputHasValue(this);
});
$(input_field).on("blur", function() {
checkInputHasValue(this);
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<form>
<div class="input-wrapper">
<input>
</div>
</form>

How can I change the value of an a html value which has the same name as a group of others?

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
});
});

How to fire change event in jQuery

I have a UserControl placed in aspx page in asp.net. In this UserControl, I have a RadioButtonList and on change of RadioButtonList item, I want to execute the below jQuery function.
$('#rdlUser').change(function (e) {
alert("change function");
var radioBtnId = this.id;
var $this = $(this);
radconfirm('Are you sure you want to take leave?', function(arg){
if (arg == true) {
alert("User wants to take leave");
}
else {
alert("User doesn't want to take leave");
}
});
});
For execute an event you can use trigger("eventname") function with JQuery.
Example
$("#id").keypress(function(){
console.log("input keypress");
});
$("#btn").click(function(){
$("#id").trigger("keypress");
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" id="id"> <button id="btn">Trigger keypress event</button>
UPDATE
With generated HTML you can't trigger event by using $("#generatedid") because element is not in the DOM at the first load.
You can use :
$(document).on("change",".your-radio-button-class",function(){
//Make a test on the value of the select radio
if($(this).val() == "connected")
{
}
else
{
}
});
Simply you can do like this:
$(document).ready(function () {
$('#rdlUser input').change(function () {
alert($(this).val());
});
});

How to call a function using checkbox in jQuery?

I have a checkbox and want to call a function when I check the checkbox and also disable that function when I uncheck the checkbox. How do I do it?
Note: By disable I mean, it should revert the process done by that function.
Update:
Is there any way to directly disable the function that I called? Since it contains many other click events inside it. So I don't wanna turn those off individually. I just wanna disable that function so that those click events automatically goes off.
$('#checkbox').change(function() {
if($(this).is(":checked")) {
// do something if checked
}
else{
// do something if not checked
}
});
Listen to the change event.
$('input#your-input-id').change(function() {
if(this.checked) {
// call the function
}
else {
// call "undo" function
}
});
$('input[type="checkbox"]').on('change', function() {
if(this.checked) {
// process if checked
} else {
// revert process here
}
// example to set variable:
var myvar = this.checked ? "It is checked" : "not checked";
});

Prevent click after focus event

When user clicks on input field, two consecutive events are being executed: focus and click.
focus always gets executed first and shows the notice. But click which runs immediately after focus hides the notice. I only have this problem when input field is not focused and both events get executed consecutively.
I'm looking for the clean solution which can help me to implement such functionality (without any timeouts or weird hacks).
HTML:
<label for="example">Example input: </label>
<input type="text" id="example" name="example" />
<p id="notice" class="hide">This text could show when focus, hide when blur and toggle show/hide when click.</p>
JavaScript:
$('#example').on('focus', _onFocus)
.on('blur', _onBlur)
.on('click', _onClick);
function _onFocus(e) {
console.log('focus');
e.preventDefault();
e.stopPropagation();
e.stopImmediatePropagation();
$('#notice').removeClass('hide');
}
function _onClick(e) {
console.log('click');
$('#notice').toggleClass('hide');
}
function _onBlur(e) {
console.log('blur');
$('#notice').addClass('hide');
}
UPDATED Fiddle is here:
I think you jumbled up the toggles. No need to prevent propagation and all that. Just check if the notice is already visible when click fires.
Demo: http://jsfiddle.net/3Bev4/13/
Code:
var $notice = $('#notice'); // cache the notice
function _onFocus(e) {
console.log('focus');
$notice.removeClass('hide'); // on focus show it
}
function _onClick(e) {
console.log('click');
if ($notice.is('hidden')) { // on click check if already visible
$notice.removeClass('hide'); // if not then show it
}
}
function _onBlur(e) {
console.log('blur');
$notice.addClass('hide'); // on blur hide it
}
Hope that helps.
Update: based on OP's clarification on click toggling:
Just cache the focus event in a state variable and then based on the state either show the notice or toggle the class.
Demo 2: http://jsfiddle.net/3Bev4/19/
Updated code:
var $notice = $('#notice'), isfocus = false;
function _onFocus(e) {
isFocus = true; // cache the state of focus
$notice.removeClass('hide');
}
function _onClick(e) {
if (isFocus) { // if focus was fired, show/hide based on visibility
if ($notice.is('hidden')) { $notice.removeClass('hide'); }
isFocus = false; // reset the cached state for future
} else {
$notice.toggleClass('hide'); // toggle if there is only click while focussed
}
}
Update 2: based on OP's observation on first click after tab focus:
On second thought, can you just bind the mousedown or mouseup instead of click? That will not fire the focus.
Demo 3: http://jsfiddle.net/3Bev4/24/
Updated code:
$('#example').on('focus', _onFocus)
.on('blur', _onBlur)
.on('mousedown', _onClick);
var $notice = $('#notice');
function _onFocus(e) { $notice.removeClass('hide'); }
function _onClick(e) { $notice.toggleClass('hide'); }
function _onBlur(e) { $notice.addClass('hide'); }
Does that work for you?
Setting a variable for "focus" seems to do the trick : http://jsfiddle.net/3Bev4/9/
Javascript:
$('#example').on('focus', _onFocus)
.on('click', _onClick)
.on('blur', _onBlur);
focus = false;
function _onFocus(e) {
console.log('focus');
$('#notice').removeClass('hide');
e.preventDefault();
e.stopPropagation();
e.stopImmediatePropagation();
focus = true;
}
function _onClick(e) {
console.log('click');
if (!focus) {
$('#notice').toggleClass('hide');
} else {
focus = false;
}
}
function _onBlur(e) {
console.log('blur');
$('#notice').addClass('hide');
}
If you want to hide the notice onBlur, surely it needs to be:
function _onBlur(e) {
console.log('blur');
$('#notice').addClass('hide'); // Add the hidden class, not remove it
}
When doing this in the fiddle, it seemed to fix it.
The code you have written is correct, except that you have to replae $('#notice').removeClass('hide'); with $('#notice').addClass('hide');
Because onBlur you want to hide so add hide class, instead you are removing the "hide" calss.
I hope this is what the mistake you have done.
Correct if I am wrong, Because I don't know JQuery much, I just know JavaScript.
you can use many jQuery methods rather than add or move class:
Update: add a params to deal with the click function
http://jsfiddle.net/3Bev4/23/
var showNotice = false;
$('#example').focus(function(){
$('#notice').show();
showNotice = true;
}).click(function(){
if(showNotice){
$('#notice').show();
showNotice = false;
}else{
showNotice = true;
$('#notice').hide();
}
}).blur(function(){
$('#notice').hide();
});

Categories