In my code, I am setting a change listener on my checkboxes here
$(".section").change(function() {
if($(this).is(":checked")) {
$("." + this.id).show();
...
Now I am trying to do a "code-driven" click on the checkbox, and I have
$(".secTitle").click(function(e) {
var elem = this;
while(elem) {
if (elem.className && elem.className.indexOf ('DOC_SECTION') != -1) {
var clzes = elem.className.split(" ");
var clzIdx = 1;
if (elem.getAttribute('closeSecClassIdx')) {
clzIdx = parseInt(elem.getAttribute('closeSecClassIdx'));
}
var chk = document.getElementById(clzes[clzIdx]);
chk.checked = false;
alert(chk.onchange);
//chk.changed();
break;
}
else {
elem = elem.parentNode;
}
}
});
I know that I have the right element, as chk.checked = false; is working correctly. After that I'm trying to invoke the change method set earlier but my alert is showing 'undefined'.
You can trigger the change event by calling $(chk).change(). Below I've created a little prototype that shows binding to the change event and invoking it.
jQuery(function($) {
// bind to the change event
$("input").change(function() {
console.log('change triggered!');
});
// now trigger it
$("input").change();
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="checkbox" />
Related
I have a form with one input field for the emailaddress. Now I want to add a class to the <form> when the input has value, but I can't figure out how to do that.
I'm using this code to add a class to the label when the input has value, but I can't make it work for the also:
function checkForInputFooter(element) {
const $label = $(element).siblings('.raven-field-label');
if ($(element).val().length > 0) {
$label.addClass('input-has-value');
} else {
$label.removeClass('input-has-value');
}
}
// The lines below are executed on page load
$('input.raven-field').each(function() {
checkForInputFooter(this);
});
// The lines below (inside) are executed on change & keyup
$('input.raven-field').on('change keyup', function() {
checkForInputFooter(this);
});
Pen: https://codepen.io/mdia/pen/gOrOWMN
This is the solution using jQuery:
function checkForInputFooter(element) {
// element is passed to the function ^
const $label = $(element).siblings('.raven-field-label');
var $element = $(element);
if ($element.val().length > 0) {
$label.addClass('input-has-value');
$element.closest('form').addClass('input-has-value');
} else {
$label.removeClass('input-has-value');
$element.closest('form').removeClass('input-has-value');
}
}
// The lines below are executed on page load
$('input.raven-field').each(function() {
checkForInputFooter(this);
});
// The lines below (inside) are executed on change & keyup
$('input.raven-field').on('change keyup', function() {
checkForInputFooter(this);
});
I've updated your pen here.
Here it is, using javascript vanilla. I selected the label tag ad form tag and added/removed the class accoring to the element value, but first you should add id="myForm" to your form html tag. Good luck.
function checkForInputFooter(element) {
// element is passed to the function ^
let label = element.parentNode.querySelector('.raven-field-label');
let myForm = document.getElementById("myform");
let inputValue = element.value;
if(inputValue != "" && inputValue != null){
label.classList.add('input-has-value');
myForm.classList.add('input-has-value');
}
else{
label.classList.remove('input-has-value');
myForm.classList.remove('input-has-value');
}
}
You can listen to the 'input' event of the input element and use .closest(<selector>) to add or remove the class
$('input').on('input', function () {
if (!this.value) {
$(this).closest('form').removeClass('has-value');
} else {
$(this).closest('form').addClass('has-value');
}
})
Edit: https://codepen.io/KlumperN/pen/xxVxdzy
I have the following JS function:
const bindSwitches = function() {
$(document).on("click", ".lever", function() {
var checkbox = $(this).siblings("input[type=checkbox]");
var hiddenField = $(this).siblings("input[type=hidden]");
if (checkbox.prop("checked") === true) {
checkbox.prop("value", 0);
hiddenField.prop("value", 0);
} else if (checkbox.prop("checked") === false) {
checkbox.prop("value", 1);
hiddenField.prop("value", 1);
}
$(checkbox).trigger("change");
});
};
It interacts with a switch component provided by the Materialize library. I have just added the final line, as there is some behaviour that needs to occur whenever a checkbox is triggered. But that change event never fires. I also have this function in my app:
const bindAllChecks = function() {
$(document).on("change", ".select-all-check", function() {
var checks = $(this).closest(".table, table").find(".multiple-check:visible");
if (this.checked) {
$.each( checks, function( index, checkbox ){
if ($(checkbox).prop("checked") === false) {
$(checkbox).prop("checked", true);
$(checkbox).trigger("change");
}
});
} else {
$.each( checks, function( index, checkbox ){
if ($(checkbox).prop("checked") === true) {
$(checkbox).prop("checked", false);
$(checkbox).trigger("change");
}
});
}
});
};
Notice how I use the exact same $(checkbox).trigger("change"). In this function it works perfectly.
I've tried changing the order in which I bind the events, to make sure the change event is definitely defined beforehand. I've made sure that the rest of the function is being triggered correctly and that there are no issues in that regard. I've also tried different variations of alternative syntax, nothing has worked.
Here is the code it is supposed to trigger:
const bindCheckboxOverride = function() {
$(document).on("change", ".checkbox-collection input[type=checkbox]:not(.select-all-check)", function() {
var hiddenField = $(this).prev();
if(hiddenField.attr("disabled") === "disabled") {
hiddenField.removeAttr("disabled");
} else {
hiddenField.attr("disabled", "disabled");
}
});
};
I still don't have an exact solution to the question I asked, but I have come up with an alternate method. Instead of trying the trigger a change, I have pulled out the functionality I want from the change even into its own function:
const bindCheckboxOverride = function() {
$(document).on("change", ".checkbox-collection input[type=checkbox]:not(.select-all-check)", function() {
handleCheckboxDisable(this);
});
};
const handleCheckboxDisable = function(checkbox) {
var hiddenField = $(checkbox).prev();
if(hiddenField.attr("disabled") === "disabled") {
hiddenField.removeAttr("disabled");
} else {
hiddenField.attr("disabled", "disabled");
}
};
So now I'm able to call this function directly from my other function:
const bindSwitches = function() {
$(document).on("click", ".lever", function() {
var checkbox = $(this).siblings("input[type=checkbox]");
var hiddenField = $(this).siblings("input[type=hidden]");
if (checkbox.prop("checked") === true) {
checkbox.prop("value", 0);
hiddenField.prop("value", 0);
} else if (checkbox.prop("checked") === false) {
checkbox.prop("value", 1);
hiddenField.prop("value", 1);
}
handleCheckboxDisable(checkbox);
});
};
It doesn't answer the question but I thought that may be of help to somebody. Would still like to know why the original code doesn't work if anybody has any insights.
EDIT: here is a much simpler JSFiddle version of the code that illustrates the problem more succinctly:
https://jsfiddle.net/Lfo463d9/2/
I have a bunch of form elements that when updated change the options of the element next in the list. I have that working fine. However, now I am trying to get it so that if the root element is changed then it checks the next element to see if it is part of the new list and if not then makes it blank and then triggers the change event of the next one (so that it will in turn make the next element blank and so on). The change event doesn't seem to be firing.
I am not getting any errors in the console.
Is this because I am trying to fire a change event from within a change event? Is there some sort of blocking going?
(or am I just doing something stupid - I only started javascript a week or so ago)
I've tried calling the change() function on the element in javascript too.
function addChainOptions(anelementID, nextelementID, listToChangeID, firstToSecond, secondFromFirst)
{ var anelement = document.getElementById(anelementID);
anelement.addEventListener("change", function() {
var nextelement = document.getElementById(nextelementID);
var listToChange = document.getElementById(listToChangeID);
console.log(this.id + "has changed");
if(this.value.length == 0)
{
nextelement.value = "";
$("#" + nextelementID).change();
}
nextelement.disabled = true;
google.script.run.withSuccessHandler(function(value) {
htmlOptions = value.map(function(r){return '<option value = "' + r[0] + '">';}).join(" ")
listToChange.innerHTML = htmlOptions;
if(value.length == 1) {
nextelement.value = value[0];
nextelement.change();
}
if(value.includes(nextelement.value) == false && nextelement.value.length > 0)
{
nextelement.value = "";
console.log(nextelement.id + "set to blank - triggering change")
$("#" + nextelementID).change();
}
nextelement.removeAttribute("disabled");
}).subListLookUp(firstToSecond, secondFromFirst, this.value);
});
};
addChainOptions("productTypesInput01", "productsInput01", "productsList01", "ProductTypeMulti", "Products");
addChainOptions("brandsInput01", "productTypesInput01", "productTypesList01", "BrandToProductType", "ProductTypeFromBrand");
addChainOptions("category", "brandsInput01", "brandsList01", "CategoryToBrand", "BrandFromCategory");
At the moment it is setting the next one to blank and trying to trigger the change but nothing happens.
You should try listening to "input" event instead of "change".
const firstinput = document.getElementById("input1");
const secondinput = document.getElementById("input2");
const thirdinput = document.getElementById("input3");
function dispatchEvent(target, eventType) {
var event = new Event( eventType, {
bubbles: true,
cancelable: true,
});
target.dispatchEvent(event);
}
firstinput.addEventListener("input", function() {
secondinput.value = 2;
dispatchEvent(secondinput,"input");
});
secondinput.addEventListener("input", function() {
thirdinput.value = 3;
//dispatchEvent(thirdinput,"input");
});
<input id="input1">
<input id="input2">
<input id="input3">
I have two hidden input fields which are changed when there is onchange event This is filled with dynamic info on load
<input type="hidden" id="setter" name="{{$value['name']}}" value="{{$field['values'][$value['name']]}}">
This one is with empty value and name
<input type="hidden" id="old_setter" name="" value="">
This is my js code
$('.select2').each(function(i, obj) {
if (!$(obj).data("select2")) {
$(obj).select2();
}
}).change(function() {
var oldSet = false;
var setter = $("#setter");
var oldSetter = $("#old_setter");
if (oldSet != true) {
oldSetter.val('');
oldSetter.attr('name', setter.attr('name'));
setter.val(($(this).val()));
setter.attr('name', ($(this).attr('id')));
oldSet = true;
} else {
setter.val(($(this).val()));
setter.attr('name', ($(this).attr('id')));
oldSet = true;
}
});
The issue is when the hidden setter get the input from visible setter is okay but after that when there is another onchange event on the hidden setter gets updated too, but i want only to update on the first onchange event. Thanks in advance
You've to define the oldSet variable outside of the event (in the global scope), else it will return to false on every change the user made and the condition will be always reached:
var oldSet = false;
$('.select2').each(function (i, obj) {
if (!$(obj).data("select2"))
{
$(obj).select2();
}
}).change(function () {
var setter = $("#setter");
var oldSetter = $("#old_setter");
if (oldSet != true) {
oldSetter.val('');
oldSetter.attr('name', setter.attr('name'));
setter.val(($(this).val()));
setter.attr('name', ($(this).attr('id')));
oldSet = true;
}else {
setter.val(($(this).val()));
setter.attr('name', ($(this).attr('id')));
oldSet = true;
}
});
Hope this helps.
Set the on change handler to an empty function after the first event.
$('.select2').change(function(){});
I have a checkbox That I need to show a div when it is clicked. I have 3 different javascripts that i have attempted to get this to work with.
//function showhide() {
// var checkbox = document.getElementById("assist");
// var expanded1 = document.getElementById("expanded");
// var expanded2 = document.getElementById("expanded2");
// expanded1.style.visibility = (expanded1.style.visibility == 'false') ? "true" : "false";
// alert('test');
//}
function(){
var checkbox = document.getElementById("assist");
var expanded1 = document.getElementById("expanded");
var expanded2 = document.getElementById("expanded2");
checkbox.onchange = function () {
expanded1.style.visibility = this.checked ? 'true' : 'false';
alert('test');
}
//function check() {
// $('chk').click(function () {
// if (this.checked) {
// $("#expanded").show();
// $("#expanded2").show();
// }
// else {
// $("#expanded").hide();
// $("#expanded2").hide();
// }
// });
//}
This is the checkbox below.
<input type="checkbox" runat="server" id="assist" onclick="showhide();" /></div>
The divs that need to be shown/hidden are expanded and expanded2.
I cannot get the javascript functions to be hit from the checkbox could someone tell me what is wrong.
Use the window.onload event to assign the change handler and remove the inline onclick from the HTML. Also the visibility CSS should be visible or hidden.
Fiddle
window.onload = function () {
var checkbox = document.getElementById("assist");
var expanded1 = document.getElementById("expanded");
checkbox.onchange = function () {
expanded1.style.visibility = this.checked ? 'visible' : 'hidden';
};
};
For Hiding the DIV using Jquery you can try below code:
instead of this.checked use $(this).is(':checked')
$('.chk').click( function () {
var $this = $(this);
if( $this.is(':checked') == true ) {
$("#div1").show();
} else {
$("#div1").hide();
}
});
html
<input type="checkbox" runat="server" id="assist" onclick="showhide();" />
<div class="required1" id="mycheckboxdiv1" style="display:none" >
your code;
</div>
this will do for u :)
jquery
<script>
$(document).ready(function() {
$('#mycheckboxdiv1').hide();
$('#assist').click(function(){
if($('#assist').is(':checked')){
$('#mycheckboxdiv1').toggle();
}
else
{
$('#mycheckboxdiv1').hide();
}
});
});
</script>
http://jsfiddle.net/maree_chaudhry/QmXCV/ here is fiddle
You're already using jQuery, so you could just use:
$("#assist").change(function(){
$("#expanded, #expanded2").toggle();
});
jsFiddle here