Click function on dynamic button, live / on not working - javascript

I am trying to run a function when a dynamically generated button is clicked. It does for some reason not seem to work, whatever method I try using.
JavaScript
//Generating the button
$('<div><h3>Back<h3></div>')
.attr('class', 'rtext btn arrowback').attr('role', 'button').attr('id', '2')
.appendTo($(".row1")).hide().delay(800).fadeIn(1000);
//function when button is clicked
$(".row1").on("click", ".arrowback", function(){
var userID = this.id;
alert(userID);
});
I have tried using .on as above, I have tried using .live as:
$(".arrowback").live("click", function(){
var userID = this.id;
alert(userID);
});
Yet nothing seem to work. Is my syntax incorrect?

Ah, I have now solved it, if both parent and child are dynamically generated, the below will function:
$(document.body).on("click", ".arrowback", function(){
var userID = this.id;
alert(userID);
});

Generating elements dynamically also allow to bind event to the recent element created.
Look at this codepen: http://codepen.io/andtankian/pen/dXpZPR
$('div').append("<div></div>");
$('div>div').addClass("row1");
//Generating the button
$('<div><h3>Back<h3></div>')
.attr('class', 'rtext btn arrowback').attr('role', 'button').attr('id', '2')
.appendTo($(".row1")).hide().delay(800).fadeIn(1000);
//function when button is clicked
$(".row1").on("click", ".arrowback", function(){
var userID = this.id;
alert(userID);
});
I simulated your environment and everything works fine.

Related

How to add a div tag at the same place after it is removed

I want to remove the headers befor i expor the data into excel, hide doesnt work because the data is still there, so i was using remove. but once removed, after the exporting to excel is completed i wanted to undo the removed headers for display.
<script type="text/javascript">
$("#btnExport").click(function(e) {
alert("");
$head=$('tr.header');
$div=$('#dvData')
$div.remove('tr.header');
alert();
window.open('data:application/vnd.ms-excel,' +encodeURIComponent($div.html()));
e.preventDefault();
});
</script>
i was trying to save the div object in a variable process on that variable div and send it, bt the div sent shows no changes!!
Just make a clone, remove whatever you want, and get the HTML
$("#btnExport").click(function(e) {
e.preventDefault();
var div = $('#dvData'),
clone = div.clone();
clone.find('tr.header').remove();
window.open('data:application/vnd.ms-excel,' + encodeURIComponent( clone.html() ));
});
append saved variable to parent of the deleted div.
Add it before the target element...remove it post that...
$(function() {
$('#add').click(function(){
var div = $('div.toRemove');
var newDiv = $('<div/>').addClass('added').html('hello world');
//newDiv.prependTo(div);
div.before(newDiv);
this.disabled = true;
div.remove();
});
$('#reset').click(function(){
$('div').remove();
$(document.body).append($('<div/>').addClass('toRemove').html('toremove'));
$('#add').removeAttr('disabled');
});
});
Fiddle: http://jsfiddle.net/deostroll/wnu9pv9y/
First of all, You must use var for each variable such as $head and $div
You can use clone to achieve the desired result.
$("#btnExport").click(function(e) {
var $clonedDiv = $('#dvData').clone(true);
$clonedDiv.find("tr.header");
window.open('data:application/vnd.ms-excel,' +encodeURIComponent($clonedDiv.html()));
e.preventDefault();
});
</script>
use clone(true) to retain the events
As per understanding you first want to remove the header before export and then want to add to the table as it is. if i am properly understanding your requirement try the following
$("#btnExport").click(function (e) {
alert("");
$div = $('#dvData')
$divToRemain = $div.find('#TableId thead')
$div.find('#TableId thead').remove();
window.open('data:application/vnd.ms-excel,' + encodeURIComponent($div.html()));
$divToRemain.appendTo('#tblHoliday');
e.preventDefault();
});
Here i save the removed header in the variable and after export i appended it to the table.
Hope this will help.

how to get id of button which user know only few characters on other button click?

I created a button dynamically whose id is started from "abc" .can we get whole button id on any other button click ?
I found this $('[id^=abc]') some thing but not work for me..?
$('#get_id').click(function(){
alert($('[id^=abc]').attr('id'));
});
Here is a simple jsfiddle
May be you want something like this:
$('#otherBTN').on("click", function(){
alert($('[id^="abc"]').attr('id')); // alerts the full id of it
});
if you want to make array out of it:
$('#otherBTN').on("click", function(){
var ids = $('[id^="abc"]').map(function(){
return this.id;
}).get();
console.log(ids); // this logs every id started with abc
});
This is a sample button set.
<button id='abc1'>B1</button>
<button id='abc2'>B2</button>
<button id='abc3'>B3</button>
<button id='abc4'>B4</button>
<button id='abc5'>B5</button>
And Jquery click function for each buttons
$(document).ready(function(){
$('[id^=abc]').click(function(){
alert($(this).attr('id'));
});
});
Demo here. I think this will help you
Your dynamic button id = 'abc'
and in case if you want get id of this on click of another button with id 'xyz'
$("#xyz").on('click', function(){
var BtnIdVal = $("input[type='button'] [id*='abc']").attr("id"); //
});
Note - considering only one dynamic button with id='abc'
or
$("#xyz").on('click', function(){
var BtnIdVal = $("input[type='button'] [id^='abc']").attr("id"); //
});
$('#anybuttonid').on("click",function(){
alert($("[id^='abc']").attr("id"));// by jQuery
});

identify link id's clicked and pass it to javascript function

my js file has
$('#opt_no').click(function() {
$('#sample6').append('<br>Employee Number:').append($("#dynamic").val());
});
$('# opt_yes').click(function() {
$('#sample7').append('<br>Employee Number:' ).append($("#dynamic").val());
});
opt_no and opt_yes are links on my html page.
when user click on submit button, i want to identify on which link he has clicked and pass this link id to onClick function of submit button
Hard to say without the rest of the code. Do you want something like this?
$('#opt_no').click(function() {
$('#sample6').append('<br>Employee Number:').append($("#dynamic").val());
$("#submitlink").attr("href", $(this).attr('id'));
});
Assuming only one link can be clicked, or that the most recent clicked link is the only one you care about, then you can store the id values in a global variable. This can then be accessed from within any other function, such as your submit click event.
var linkId;
$('#opt_no').click(function() {
linkId = $(this).attr('id');
$('#sample6').append('<br>Employee Number:').append($("#dynamic").val());
});
$('# opt_yes').click(function() {
linkId = $(this).attr('id');
$('#sample7').append('<br>Employee Number:' ).append($("#dynamic").val());
});
$('#submitButton').click(function() {
//do something with linkId
});
you ca n get id using this code
$(this).attr('id');

Why is jQuery .click() is skipped over?

I have a small script of javascript which iterates over a set of checkboxes which grabs the name attribute and value and then convert it to json. Then I use that value to set the href of an element and then try to trigger a click.
For some reason everything seems to function properly except for the click. I successfully change the href, I console.log() a value before the .click() and after. Everything hits except for the click. The url in the href is value as I clicked it manually.
I have my script included just before the closing body tag and have it wrapped in $(document).ready(). and I do not have duplicate ID's (I viewed the rendered source to check)
Can anyone offer some insight on this?
Here is the javascript
$(document).ready(function() {
$("#multiExport" ).on('click', function(e){
e.preventDefault();
var i = 0;
var list = new Array();
$('.appSelect:checked').each(function(){
var name = $(this).attr('name');
var id = $(this).val();
list[i] = new Array(name, id);
i++;
});
var serList = JSON.stringify(list);
console.log(serList);
var webRoot = $("#webRoot").text();
$("#exportLink").attr('href', webRoot+"/admin/admin_export_multiExport.php?emailList="+serList); //hits
console.log('1'); //hits
$("#exportLink").click(); //this line never executes
console.log('2'); //hits
});
});
$(selector).click() won't actually follow the link the way clicking on it with your mouse will. If that's what you want, you should unwrap the jquery object from the element.
$(selector)[0].click();
Otherwise, all you're doing is triggering event handlers that may or may not exist.
I may guess you need
$(document).on('click', '#multiExport', function(e){
(you can replace document by a nearest element, if you got one).
if you need dynamic click event binding.
EDIT
I would try something like that :
$(document).ready(function() {
$("#exportLink").click(function() {
window.location = $(this).attr('href');
});
$("#multiExport" ).on('click', function(e){
//whatever you want
$('#exportLink').attr('href', 'something').trigger('click');
});
});
$("#exportLink").click(); // this would launch the event.
I must admit I am very surprised that the .click() does not work.
If the idea is to load the page, then the alternative is
$(function() {
$("#multiExport" ).on('click', function(e){
e.preventDefault();
var list = [];
$('.appSelect:checked').each(function(){
var name = $(this).attr('name');
var val = $(this).val();
list.push([name, val]);
});
var serList = JSON.stringify(list);
var webRoot = $("#webRoot").text();
location=webRoot+"/admin/admin_export_multiExport.php?emailList="+serList;
});
});

Dynamically added select change events not registering

In my site I have some code as follows: -
$(function() {
$(document).on('change', 'select', function() {
var formID = $(this).attr("id");
if((formID.indexOf("forms[")>-1)){
var newFormID= $(this).val();
var scenarioID = ${testScenarioInstance?.id}
getFormInformation(newFormID, "forms", $(this), scenarioID);
}
});
});
In another part of the page the user can add additional selects via a simple little post and append. The trouble is for any newly added selects this piece of code doesn't trigger, but it works fine for any select that is there when the page loads. Any ideas why this is?
It should work well as you have it now, here I made little example with your same code for the event:
http://jsfiddle.net/2KCY9/
$(document).on('change', 'select', function () {
alert("Works well");
});

Categories