Dynamically created buttons won't fire when clicked - javascript

I'm creating buttons based on what a user enters into an input box. However, the function i have linked to the dynamically created buttons won't fire when pressed.
function btnCreate() {
num++;
userBtn = $("<button>")
userBtn
.addClass("btn search-term-btn dynamicElement")
.appendTo($(".btn-holder"))
.text(topics)
.attr("data-name", topics);
usedTopics.push(topics + num);
topics = [];
console.log(num);
};
$(".search-term-btn").on("click", ".dynamicElement", function () {
// takes the name of the button
searchValue = $(".search-term").attr("data-name");
console.log(searchValue);
})
The class is correct, ive checked with the inspector. I just can't seem to figure out why it's unresponsive

Create the click event on DOM.
$(document).on("click", ".search-term-btn .dynamicElement", function () {
console.log(this)
});

while you are creating the buttons, you can add the onclick function there..
like userBtn = $("<button onlcikc="somefunction(this)">")
OR
you can use on function which is
$('body').on( "click",".dynamicElement", function() {
//your code
});

Related

How to add an event handler to an element which is rendered on a button click?

I have two links on a page. When I click on the second link, it displays certain fields. I want to write a onkeyup() event handler for one of the fields. I have written the code like this and I'm missing something. Please help.
var inputBox;
$().ready(function() {
//cc_sec is the id of the second link in my page.
$('#cc_sec').click(function(){
inputBox = document.getElementById("{!$Component.pg.pb.cardForm.cardnumber}");
alert(inputBox.id);
//This alert is giving me the ID of the element correctly.
});
//This is not working. inputBox is declared as global variable.
inputBox.onkeyup = function(){
alert(inputBox.value);
document.getElementById('printCardNo').innerHTML = inputBox.value;
}
});
Please point out my mistake. TIA :)
UPDATE:
I can get the element by ID only after clicking the cc_sec link. So I cannot do inputBox = document.getElementById("{!$Component.pg.pb.cardForm.cardnumber}"); in the beginning of the ready function.
use jQuery .on to add eventhandler to dynamically created elements.
$('body').on("keyup","{!$Component.pg.pb.cardForm.cardnumber}",function(){
alert($(this).val());
document.getElementById('printCardNo').innerHTML = $(this).val();
});
You have two options
call document.getElementById in document ready:
var inputBox;
$().ready(function() {
inputBox = document.getElementById("{!$Component.pg.pb.cardForm.cardnumber}");
//cc_sec is the id of the second link in my page.
$('#cc_sec').click(function() {
alert(inputBox.id);
//This alert is giving me the ID of the element correctly.
});
inputBox.onkeyup = function() {
alert(inputBox.value);
document.getElementById('printCardNo').innerHTML = inputBox.value;
};
});
or set onkeyup in click event:
var inputBox;
$().ready(function() {
//cc_sec is the id of the second link in my page.
$('#cc_sec').click(function() {
inputBox = document.getElementById("{!$Component.pg.pb.cardForm.cardnumber}");
alert(inputBox.id);
//This alert is giving me the ID of the element correctly.
inputBox.onkeyup = function() {
alert(inputBox.value);
document.getElementById('printCardNo').innerHTML = inputBox.value;
};
});
});

Call back from styled radio buttons

I am using the jQuery plugin radiosToSlider (http://rubentd.com/radios-to-slider/) and need to make sure that all radio button groups are checked and to give an alert when they are
I can do this if they are just radio buttons by checking the length but because the plugin changes the input buttons I am having difficulties
My fiddle is
http://jsfiddle.net/yFaAj/270/
$(document).ready(function () {
$(".radios").radiosToSlider();
});
$(":radio").change(function () {
var names = {};
$(':radio').each(function () {
names[$(this).attr('name')] = true;
});
var count = 0;
$.each(names, function () {
count++;
});
if ($(':radio:checked').length === count) {
alert("all answered");
}
}).change();
thanks
The problem isn't that the plugin changes your structure (although it does add some ins elements, which I don't agree with), it's that the plugin doesn't fire a change event for the converted radio controls, and setting the checked property interactively doesn't appear to do so either.
Since the plugin author doesn't publish an API for this use case, it's hard to know whether this is by design or oversight, but the source code definitely doesn't fire the event when the slider is clicked:
this.bearer.find('.slider-level').click( function(){
var radioId = $(this).attr('data-radio');
slider.bearer.find('#' + radioId).prop('checked', true);
slider.setSlider();
});
Your options, as I see them:
Contact the API author and ask for a bug fix, or the intended way to support this case
Downside: Time: dependent on the author to respond
Attach your "check" function to the click event of the .slider-level class, as the API does.
Downside: Brittle: future versions of the plugin may attach the behavior to different selectors
Attach your function to the click event of your radio group, and catch click events on the bubble
Downside: Inefficient: It will check for every click in the radio control
Here's a sample implementation of option 3. DEMO.
$(document).ready(function () {
$(".radios").radiosToSlider();
});
var makeIsRadioGroupChecked = function(selector) {
var $radioGroup = $(selector);
return function isRadioGroupChecked() {
return $radioGroup.find(':checked').length > 0;
};
};
var isOptionsChecked = makeIsRadioGroupChecked('#optionsRadioGroup');
var isSizeChecked = makeIsRadioGroupChecked('#sizeRadioGroup');
var areAllGroupsChecked = function() {
return isOptionsChecked() && isSizeChecked();
};
var alertIfAllGroupsChecked = function() {
if (areAllGroupsChecked()) {
alert("all answered");
}
};
$('.radios').on('click', alertIfAllGroupsChecked);

Onclick toggle DIV class

So I have a button that is a div class, lets call it "login-button-arrow".
I want to set up a javascript method, so when this div gets clicked on, a little javascript box can pop up.
How do I go about doing this?
I have tried something like this:
login-button-arrow.onclick{alert('xyz')}
but I guess it does not work like that.
// Get #popup element:
const popup = document.querySelector("#popup");
// Function to toggle popup (toggles .active)
const togglePopup = () => {
console.log( "xyz" );
popup.classList.toggle("active");
};
// Get buttons elements from DOM
const buttons = document.querySelectorAll('.login-button-arrow');
// Assign event listener with callback to every button:
buttons.forEach((btn) => {
btn.addEventListener("click", togglePopup);
});
$('.login-button-arrow').on('click', function() { alert('xyz'); });
var login-button-arrows = document.getElementsByClassName('login-button-arrow');
login-button-arrows.forEach(function(obj){
obj.addEventListener('click', function(){
alert('xyz');
});
});
using Jquery :
$('#login-button-arrow').on('click', function(){ alert('xyz'); });

swapped radio overlaying each other after swapping

Something wrong with the event handler, as on mouse leave the div opens and closes 3 times.
also the radio that is swapped get over layed or offset.
I have tried everything, i think it has something to do with the way i am using the event.preventDefault();
UPDATE__
Menu opening 3x fixed, but the swapped radio in the div still overlaps any ideas?
http://www.apecharmony.co.uk
// RADIO BUTTON
$("input[name='domain_ext']").each(function () {
$("#domaindropradio1").attr('checked', 'checked');
var lbl = $(this).parent("label").text();
if ($(this).prop('checked')) {
$(this).hide();
$(this).after("<div class='radioButtonOn'>" + lbl + "</div>");
} else {
$(this).hide();
$(this).after("<div class='radioButtonOff'>" + lbl + "</div>");
}
});
$("input[type=radio]").change(function () {
$(this).siblings('.radioButtonOff').add('.radioButtonOn').toggleClass('radioButtonOff radioButtonOn');
});
// RIBBON RADIO DROPBOX
$('div.ribbonBoxarrow').click(function () {
$('.ribbonBoxarrow li').show('medium');
});
$('.ribbonBoxarrow li').mouseleave(function () {
$(this).hide('slow');
});
$("input[name='domain_ext']").parent('label').click(function () {
$('.ribbonBoxarrow li').hide('slow');
event.preventDefault();
});
//SWAP SECECTED RADIO
$("div.radiogroup2").on("click", ":radio", function () {
var l = $(this).closest('label');
var r = $('#radioselected');
r.removeAttr('id');
l.before(r.closest('label'));
$(this).attr('id', 'radioselected');
l.prependTo('.radiogroup1');
});
In response to:
the div opens and closes 3 times.
Your animations are triggering more events than you'd like. Also, your preventDefault() isn't preventing other click events from firing.
For your $("input[name='domain_ext']").parent('label') click event, try this:
$("input[name='domain_ext']").parent('label').click(function () {
$('.ribbonBoxarrow li').mouseleave();
event.stopImmediatePropagation();
});
For your second issue:
also the radio that is swapped get over layed or offset.
It looks like you're prepending radio buttons to an element with the radiogroup1 class, but you may want your radio buttons to be within the nested table element.
Solved, using tables to hold elements is what was causing the problem. If it is required then you would have to target the cell for swap.

jquery how to combine two selectors to second function of single toggle event

If I have a regular toggle function bound to a click event
$('#work-content a').toggle(
function() {
// first click stuff
}, function() {
// second click stuff
}
);
But, I also need to bind $(document).click event to the second function somehow. My logic is probably off so I'm sure a new solution is necessary.
Functionality is 1) do something when link is clicked then 2) do the opposite when the link is clicked again or if the outside of the #work-content div is clicked.
Just extract the anonymous function and give it a name:
var thatFunction = function () {
...
}
$('#work-content a').toggle(
function() {
// first click stuff
},
thatFunction);
$(document).click(thatFunction);
the toggle function is used to hide/show your div and should not be used to maintain state of an event. just use another local variable for this and also define two functions perform your two different actions and pass the function pointer as callback to your event listener.
thus:
var linkClicked=false;
function fun1(){}
function fun2(){}
$('#work-content a').click(
function() {
if(!linkClicked)
fun1();
else
fun2();
});
$("body").click(function(){
if($(event.target).closest("#work-content")===null) //to make sure clicking inside your div does not trigger its close
{
fun2();
}
});
linkClicked = false;
$('#work-content .pic a').click(function(event) {
event.preventDefault();
var c = $(this);
if (!linkClicked) {
values = workOpen($(this));
} else {
workClose(c, values);
}
$('body').one('click',function() {
workClose(c, values);
});
});
This solution was exactly what I needed for what it's worth.

Categories

Resources