Unable to fire javascript event OnClick of checkbox - javascript

So I have a checkbox control that I cannot get to fire an OnClick event. I've tried a number of different ways: Binding the event onload and adding the event as a parameter in the <input type="checkbox"> tag.
Here is my most recent iteration of code. I'm trying to fire an Alert just to confirm that it changed.
<section class="border-bottom">
<div id="approx" class="content">
<h3>This is my approximate location</h3>
<div class="form-control-group">
<div class="form-control form-control-toggle" data-on-label="yes" data-off-label="no">
<input type="checkbox" />
</div>
</div>
</div>
</section>
JavaScript:
$('input[type="checkbox"]').bind('click', function() {
alert("OK");
})
I also wouldn't mind being able to run it via the following input:
<input type="checkbox" onclick="runMyFunction(); return false;" />

You should use one of the following methods:
.click(function() { ... })
.change(function() { ... })
.on('click', function() { ... })
HTML:
<div section class="border-bottom">
<div id="approx" class="content">
<h3>This is my approximate location</h3>
<div class="form-control-group">
<div class="form-control form-control-toggle" data-on-label="yes" data-off-label="no">
<input type="checkbox" id="checkbox" />
</div>
</div>
</div>
</section>
JavaScript:
$('#checkbox').change(function() {
alert("OK");
});

Some of the plugins require:
$("#checkbox").on('change', function() {
// content
});
or look for the manual of your plugin (sometimes you need to use: pluginName.change exchange for change)

First use your jquery function inside $(document).ready function to make sure the dom is ready like :
$(document).ready(function () {
$('input[type="checkbox"]').bind('click', function () {
alert("OK");
})
});
https://jsfiddle.net/4fmL1zfr/8/

Related

why this eventListner callback function is running twice

const addons = document.querySelectorAll('.addon');
const toggleAddon = (e, addon) => {
console.log(addon);
console.log(addon.querySelector('input').checked);
if (addon.querySelector('input').checked)
addon.classList.remove('selected-plan');
else addon.classList.add('selected-plan');
};
addons.forEach((addon) => {
addon.addEventListener('click', (e) => toggleAddon(e, addon));
});
<label>
<div class="addon addon-2 selected-addon">
<input type="checkbox" name="addon-2" class="addon-chkbox" id="larger-storage">
<div class="addon-info">
<h3 class="addon-name">Larger Storage</h3>
<p class="addon-features">Extra 1TB of cloud save</p>
</div>
<div class="addon-pricing-box">
<h3 class="addon-pricing">$2/mo</h3>
</div>
</div>
</label>
Why when I click on this element, the function toggleAddon() runs twice and in first run console.log(addon.querySelector('input').checked) comes false and on second it comes true.
Thanks for the help.
This is another simplified example that will better show what I'm pointing out:
let counter = 0;
document.querySelector('.addon')
.addEventListener('click', event =>{
console.log(`[${++counter}]`);
console.log(event.target);
});
<label>
<div class="addon">
<input type="checkbox">
<div class="addon-info">
<h3 class="addon-name">Click here</h3>
</div>
</div>
</label>
The problem is with the <label> element, when it is clicked, it trigger another click event on the input element within.
I suggest using change event instead.
check it in codesandbox.
The whole label is for the input? so why not listen to the input click event only which will automatically be handled by the label? like:
let counter = 0;
document.querySelector('.addon-input')
.addEventListener('click', event =>{
console.log(`[${++counter}]`);
console.log(event.target);
});
<label>
<div class="addon">
<input class="addon-input" type="checkbox">
<div class="addon-info">
<h3 class="addon-name">Click here</h3>
</div>
</div>
</label>

JQuery not working for external html [duplicate]

This question already has answers here:
How do I attach events to dynamic HTML elements with jQuery? [duplicate]
(8 answers)
Closed 6 years ago.
I need to create few div elements after click the button. So I decide to make something like template in external file and append in head div tag using jquery.
$('.socket-element').on('click', function (e) {
$.ajax({
url: '/my-site/tags/socket-box.php',
success: function (data) { $('#room-place').append(data); },
dataType: 'html'
});
});
And my external html file:
<div class="socket-box room-box-element col-xs-2 ui-draggable ui-draggable-handle">
<div class="row">
<div class="row">
<div class="box-header col-xs-12">
<div class="row">
<div class="col-xs-2">
<img class="down-arrow" src="https://cdn4.iconfinder.com/data/icons/ionicons/512/icon-arrow-right-b-128.png" width="14" height="18" />
</div>
<div class="col-xs-8">
<h6>Temperature</h6>
</div>
<div class="col-xs-2">
<img class="settings" src="https://cdn2.iconfinder.com/data/icons/flat-ui-icons-24-px/24/settings-24-128.png" width="18" height="18" />
</div>
</div>
</div>
</div>
</div>
<div class="row">
<div class="row">
<div class="box-content col-xs-12">
<div class="row">
Test
</div>
</div>
</div>
</div>
So this code is working fine is add the external html on the original html file but when I need to use click event on appended html is not working.
So I need to use few events like click, draggable from jquery ui etc.
But when I need to use: this click event then for appended html is not working
$('.down-arrow').click(function (e) {
alert('Test');
});
How can I solve this problem.
Try this :
$('.socket-element').on('click', function (e) {
$.ajax({
url: '/my-site/tags/socket-box.php',
success: function (data) {
$('#room-place').append(data);
$('#room-place').ready(function(){
$('.down-arrow').click(function (e) {
alert('Test');
});
});
},
dataType: 'html'
});
});
Hope this will help:)
For dynamic events do write using event delegation like:
$(document).on("click",".down-arrow",function(){
//write your code here
})
Please Try to use the events inside the on ready function .. Trust me it will work properly.
$(document).ready(function(){
$('.down-arrow').click(function (e) {
alert('Test');
});
});
Please try this way.
Use event delegation
$(document).on('click', '.down-arrow',function(e){
});

onBlur() not working properly

I want the <div> with class .shell-pop to be closed if they click out of the element area. It appears not to fire though, and none of the logs or alerts go off either. I've looked around and everything appears right?
jQuery
$('document').ready(function () {
updateCart();
$(".shell").click(function (e) {
e.preventDefault();
$(".shell-pop").fadeIn(300, function () { $(this).focus(); });
});
$(".shell-pop").on('blur', function () {
$(this).fadeOut(300);
window.alert("work");
console.log("works");
});
});
HTML
<div class="options-area">
<div class="options-popup shell-pop">
<div class="swatches">
<div class="colors-shell colors" id="green">
<p class="prices-for-swatch">$14.23</p>
</div>
<div class="colors-shell colors" id="pink">
<p class="prices-for-swatch">$7.23</p>
</div>
<div class="colors-shell colors" id="blue">
<p class="prices-for-swatch">$11.25</p>
</div>
<div class="colors-shell colors" id="orange">
<p class="prices-for-swatch">$10.23</p>
</div>
<div class="colors-shell colors" id="default-shell">
<p class="prices-for-swatch">FREE</p>
</div>
<div class="colors-shell colors" id="exit">
<img src="img/Silhouette-x.png" class="x-logo" alt="exit" />
<p class="closeit">CLOSE</p>
</div>
<div class="shell square">
<img src="img/controllers.png" class="item-icon" alt="controller-piece">
<p class="name-of-item">Shell</p>
<p id="shell_Price1" class="items-price">0.00</p>
</div>
Give your <div> a tabindex.
The tabindex global attribute is an integer indicating if the element
can take input focus (is focusable), if it should participate to
sequential keyboard navigation, and if so, at what position.
Observe the following...
<div tabindex="-1"></div>
$('div').on('blur', function() {
console.log('blurrr');
});
JSFiddle Link - simple demo
Blur will only fire on form elements. You should consider a different approach. For example, you could watch for click events on .shell-pop and determine it's current state.
Like
$(document).on('click', function(e){
if ($(e.target).is('.shell-pop')) {
alert('focused');
} else {
alert('blured');
}
});

showing hiding div not working

Hi all I have the following html code
<div id="orderlist">
<div class="panel" id="1">
<div class="p_header">Order No: 1
<input class="ordview" type="button" value="View Details"/>
<input class="select" type="button" value="Add"/>
</div>
<div class="p-content" style="display:none;">
<table>
<tr><td>Contact Person:</td><td></td></tr>
<tr><td>Telephone:</td><td></td></tr>
<tr><td>E-Mail:</td><td></td></tr>
<tr><td>Address:</td><td></td></tr>
<tr><td></td><td></td></tr>
<tr><td>Code</td><td></td></tr>
<tr><td>City</td><td></td></tr>
</table>
</div>
</div>
</div>
with the following jquery to toggle it but it is not working, cannot figure out why though
$("body").on('click',".ordview",function(){
$(this).closest('div.p-content').css('display','block');
alert('view button clicked');
});
.closest() goes up the DOM and p.content isn't an ancestor, but div.panel is. Use:
$("body").on('click', ".ordview", function () {
$(this).closest('div.panel').find('div.p-content').toggle();
});
jsFiddle example
Try this code to show/hide details
$(".ordview").bind('click', function () {
$(this).parent().next().toggle();
});
I personally would use the toggle() command. Below funciton works and can check jsFiddle
$("body").on('click',".ordview",function(){
$(this).closest('div.panel').children('div.p-content').toggle();
});
jsFiddle Example

jQuery Click event not attaching to Knockout template

I have a block of code that is attached to a jQuery click event. Here's the element:
<!-- Profiles -->
<div class="profiles">
<h1>Profiles</h1>
<div class="profile">
<div class="name">
<input type="text" maxlength="14" value="Default" />
<span class="rename">q</span>
</div>
<div class="controls">
<span class="edit">EDIT</span>
<span class="duplicate">COPY</span>
<span class="delete default">J</span>
<div class="alert-box">
<p>Are you sure you want to delete this profile?</p>
<div>Y</div>
<div>N</div>
</div>
</div>
<div class="saved">
<span class="cancel-button">Cancel</span><span class="save-button">Save</span>
</div>
</div>
</div>
When the item is selected, it becomes available for editing. Here's the event listener:
$('.rename').click(function () {
$('.selected .rename').fadeIn(80);
$(this).fadeOut(80);
$(this).parent().addClass('selected');
});
There's another event that listens for a click anywhere else on the page to deselect the item being edited:
$(document).click(function () {
$(".selected .rename").fadeIn(80);
$('.name').removeClass('selected');
});
When it is clicked on, it should be selected to allow for editing. When I move the code from the profile into a knockout template, it doesn't listen to the click event anymore. When I inspect the Event Listeners in Chrome's tools, the listener is nowhere to be found. Here is what my template looks like:
<div class="profiles">
<h1>Profiles</h1>
<div data-bind="template: { name: 'profilestempl', foreach: $root.profiles }"></div>
</div>
<script type="text/html" id="profilestempl">
<div class="profile">
<div class="name">
<input type="text" maxlength="14" data-bind="value: name" />
<span class="rename">q</span>
</div>
<div class="controls">
<span class="edit">EDIT</span>
<span class="duplicate">COPY</span>
<span class="delete">J</span>
<div class="alert-box">
<p>Are you sure you want to delete this profile?</p>
<div>N</div><div>Y</div>
</div>
</div>
<div class="saved">
<span class="cancel-button">Cancel</span><span class="save-button">Save</span>
</div>
</div>
</script>
Can someone explain to me why the event listener no longer works on the dynamically added elements? I would also like help in solving this problem. Thanks!
You have to add click event listener on the outer element which is always visible (since it doesn't work on hidden elements). And then add other selector for template code (which is hidden)
Sample code would be:
function addClickEventToCloseButton(){
$("#outerAlwaysVisible").on('click','#templateHiddenInitially',function(){
alert('works')
});
}
If you want the handler to work on elements that will be created in the future you should use on : http://api.jquery.com/on/

Categories

Resources