How to pass a HTML control to another javascript function - javascript

I want to pass HTML control to another function inside JavaScript. I am calling a modal popup which has a input control and a save button.
The function in which i am calling the modal popup has entire GridView row as a parameter. I want to pass this to another javascript function which will be called on the button click inside of modal dialog.
I tried as below but it passes a string variable.
function ShowDialogPeoplePicker(id, requestType, cntrl) {
var row = cntrl.parentNode.parentNode;
var rowIndex = row.rowIndex - 1;
var Approvers = row.cells[1].getElementsByTagName("span")[0];
if (requestType == "AddApprovers") {
$('#btnAddApprover').removeAttr('onclick');
$('#btnAddApprover').attr('onClick', 'if (!setApprovers(\'' +cntrl + '\')) return false;');
}
}
The below function will be called on a button click and will set the values inside GridView row.
function setApprovers(cntrl)
{
var usernames= $("#hdnApproversName_CTO").val();
var row = cntrl.parentNode.parentNode;
var rowIndex = row.rowIndex - 1;
row.cells[1].getElementsByTagName("span")[0].innerHTML = usernames;
$("#overlayTasks").hide();
$("#dialogTasks").hide();
return false;
}

Instead of attaching your click handler like this:
$('#btnAddApprover').attr('onClick', 'if (!setApprovers(\'' +cntrl + '\')) return false;');
Try this instead:
$('#btnAddApprover').on('click', function() {
setApprovers(cntrl);
});
If you need to remove previously added event listeners, you can do that with:
$('#btnAddApprover').off('click');
Or if you want to attach the listener to listen just one time in the first place, you can use:
$('#btnAddApprover').one('click', function() {
setApprovers(cntrl);
});
(with one instead of on). Hope this helps!

Instead of
$('#btnAddApprover').attr('onClick', 'if (!setApprovers(\'' +cntrl + '\')) return false;');
use
$('#btnAddApprover').click(function() {
return setApprovers(cntrl);
}

Related

jquery function not firing when I use datatable.fnAddData to append the HTML string

jquery function not firing when I use dataTable.fnAddData to append the HTML string.
So I have a function populateDataTable(), there are two columns I needed to render an icon instead of data from JSON.
Hence, I tried to like appending the HTML string including classes for the element in fnAddData(). But somehow it's not firing the click event on the icon.
function populateDataTable(data) {
$("#customerTable").DataTable().clear();
var length = Object.keys(data).length;
for(var i = 1; i < length+1; i++) {
var index = i - 1;
var name = data[index].name;
var queue = data[index].queue;
var expire = data[index].expire;
$('#customerTable').dataTable().fnAddData( [
i,
name,
queue,
'<td id="tb-manage-key" class="tb-manage-key"><div class="tb-btn manage-key-btn switch-view" data-hide="manageCustomers" data-title="#Resources.ManageKeys" data-target="manageKeys"><span></span></div></td>',
'<td class="tb-manage-subs"><div class="tb-btn manage-subs-btn switch-view" data-hide="manageCustomers" data-title="#Resources.ManageSubscriptions" data-target="manageSubscriptions"><span></span></div></td>',
expire,
name
]);
}}
$('.tb-btn.switch-view').on('click', function(e) {
e.preventDefault();
switchView(this);
console.log('Testing'); //not firing
});
Icon is showing, but not firing click event as it supposed to be. Attached below shows that we can see it appends the div as expected.
Solutions
Adding the click event within the populateDataTable() works.
$('#customerTable tbody').on('click', '.tb-btn.switch-view', function() {
switchView(this);
});
You can try a different syntax to listen to the click event...
$('td').on('click', '.tb-btn.switch-view', function(e) {
e.preventDefault();
switchView(this);
console.log('Testing'); //not firing
});

on.click not working after first click on dynamically created table

I dynamically create a table full of links of 'actors', which allows to pull the actors information into a form to delete or update the row. The delete button only pops up when you select an actor.
I'm able to click a row, pull the information into the forms, and delete it on first try. However when I attempt to add a new 'Actor' and then delete it, or just delete an existing 2nd row, the button 'Delete Actor' doesn't work. It's only after the first successful delete does the button no longer work.
var addActor = function() {
// Creates a table of links for each added actor with an id based from # of actors
$("#actorsTable").append("<tr><td><a href='' onclick='deleteActor(this)' class='update' data-idx='" + actors.length + "'>" + newActor.fName + " " + newActor.lName + "</a></td></tr> ");
$(".update").off("click");
$(".update").on("click", selectActor);
};
var deleteActor = function(e) {
$("#deleteActor").on('click', function(event) {
event.preventDefault();
var row = e.parentNode.parentNode;
row.parentNode.removeChild(row);
clearForm(actorForm);
actorState("new");
});
};
I'm new to jQuery/javascript, and I'm pretty sure its due to the change in DOM, but I just don't know what to change to make it work.
Here is an Example of it in action
Try
var deleteActor = function(e) {
$("#deleteActor").unbind();
$("#deleteActor").on('click', function(event) {
event.preventDefault();
var row = e.parentNode.parentNode;
row.parentNode.removeChild(row);
clearForm(actorForm);
actorState("new");
});
};
Here is the link for unbind.
http://api.jquery.com/unbind/
The problem is because you're adding another click handler (in jQuery) within the click handler function run from the onclick attribute. You should use one method or the other, not both. To solve the problem in the simplest way, just remove the jQuery code from the deleteActor() function:
var deleteActor = function(e) {
var row = e.parentNode.parentNode;
row.parentNode.removeChild(row);
clearForm(actorForm);
actorState("new");
};
when you add html dynamically you need to attach the event to the parent static element like so:
$("#actorsTable").on("click","a.update", function() {
$(this).closest("tr").remove();
});

Click toggle with jquery/javascript

I want to click a table element and to have it do x the first click and if clicked again perform Y
<td class='p' id='e1' onclick="myFunction2()"><img src='person2.png'/></td>
Thats what I have for my HTML for one click just now, but I wish to change that so that an item can be selected, then if clicked again for a deselect it would then trigger a different function.
I'm going to assume (you didn't say) that you want the function to be called to alternate with every click:
$('#e1').on('click', function() {
// retrieve current state, initially undefined
var state = $(this).data('state');
// toggle the state - first click will make this "true"
state = !state;
// do your stuff
if (state) {
// do this (1st click, 3rd click, etc)
} else {
// do that
}
// put the state back
$(this).data('state', state);
});
This uses jQuery's .data feature to store the button's click state in the button element itself.
Alternatively, you could use an external variable, but you should enclose the callback in a closure (in this case an immediately invoked function expression) to prevent the variable from becoming a global variable:
(function() {
var state;
$('#e1').on('click', function() {
state = !state;
if (state) {
// do this (1st click, 3rd click, etc)
} else {
// do that
}
});
})();
If the .on call and the state variable declaration are inside a jQuery document.ready handler that would have the same effect.
Pretty basic, let me know if this is close to what you want.
http://jsfiddle.net/WNJ75/6/
<div id="e1">Click Me</div>
.
(function() {
var click_track = 1;
$("#e1").click(function() {
if (click_track == 1)
alert("do something");
else if (click_track == 2) {
alert("do something else and reset click");
click_track = 0;
}
click_track++;
});
})();
demo: http://jsfiddle.net/HJwJf/
Link the toggle method with;
$("button").toggle(function(){
$("body").css("background-color","green");},
function(){
$("body").css("background-color","red");},
function(){
$("body").css("background-color","yellow");}
);
You could create a new atribute on the HTML element named, for example, "clickCount", and use it inside your event handler as a counter.
Let's say you have a button like this one:
<button data-click-count='0' onclick="myFunction(this)">My Button</button>
And you have a function like this:
function myFunction(elt) {
// Gets the clicks count
var count = $(elt).data("click-count");
// Adds one to the click counter
$(elt).data("click-count", ++count);
if (count == 1)
doSomething();
else if (count == 2)
doSomethingElse();
}
Every time you click the button, you'll see an alert with the number of clicks you've made.
You can use the same method and apply it to your case.
Using a state variable. The state variable will swap between the values 0 and 1 on each click. Making use of state we can execute the corresponding function in fn array.
<td class='p' id='e1'><img src='person2.png'/></td>
$("td#e1.p").each(function(){
var state = 1, fn = [myFunction1, myFunction2];
$(this).click(function(){
return fn[state = 1 - state].apply(this, arguments);
});
});
Also, it's preferably to use proper event binding than inline JavaScript.

Jquery creating checkboxs dynamically, and finding checked boxes

I have information that comes out of a database and gets put into a list with a checkbox by each element. This is how it is currently done:
function subjects(){
$.ajax({
url: "lib/search/search.subject.php",
async: "false",
success: function(response){
alert(response);
var responseArray = response.split(',');
for(var x=0;x<responseArray.length;x++){
$("#subjects").append("<br />");
$("#subjects").append(responseArray[x]);
$("#subjects").append("<input type='checkbox' />");
}
}
});
}
it works fine, but I need a way to pick up on if a checkbox is clicked, and if it is clicked then display which one was clicked, or if multiple ones are clicked.
I can't seem to find a way to pick up on the checkboxs at all.
the response variable is "math,science,technology,engineering"
Because you are populating the Checkboxes Dynamically you need to Delegate the event
$("#subjects").on("click", "input[type='checkbox']", function() {
if( $(this).is(":checked") ) {
alert('Checkbox checked')
}
});
To better capture the data it is better if you encase the corresponding data into a span , so that it can be easier to search..
$("#subjects").append('<span>'+responseArray[x] + '</span>');
$("#subjects").on("click", "input[type='checkbox']", function() {
var $this = $(this);
if( $this.is(":checked") ) {
var data = $this.prev('span').html();
alert('Current checkbox is : '+ data )
}
});
It would be best to give your dynamically injected checkboxes a class to target them better, but based on your code try:
$("#subjects").on("click", "input", function() {
if( $(this).is(":checked") ) {
// do something
}
});
Since your input elements are added dynamically, you need to use jQuery's .on() function to bind the click event to them. In your case you need to use .on() to bind to an element that exist in the DOM when the script is loaded. In your case, the element with the ID #subjects.
This note from the docs is mainly for machineghost who downvoted my answer for no apparent reason:
Event handlers are bound only to the currently selected elements; they
must exist on the page at the time your code makes the call to .on().
To ensure the elements are present and can be selected, perform event
binding inside a document ready handler for elements that are in the
HTML markup on the page. If new HTML is being injected into the page,
select the elements and attach event handlers after the new HTML is
placed into the page.
$('#subjects input[type=checkbox]').on('click',function(){
alert($(this).prop('checked'));
});
or the change event: in case someone uses a keyboard
$('#subjects input[type=checkbox]').on('change',function(){
alert($(this).prop('checked'));
});
simple fiddle example:http://jsfiddle.net/Dr8k8/
to get the array example use the index of the inputs
alert($(this).prop('checked') +'is'+ $(this).parent().find('input[type=checkbox]').index(this)+ responseArray[$(this).parent().find('input[type=checkbox]').index(this) ]);
simplified example: http://jsfiddle.net/Dr8k8/1/
EDIT: Just for an example, you could put the results in an array of all checked boxes and do somthing with that:
$('#subjects>input[type=checkbox]').on('change', function() {
var checklist = [];
$(this).parent().find('input[type=checkbox]').each(function() {
$(this).css('background-color', "lime");
var myindex = $(this).parent().find('input[type=checkbox]').index(this);
if ($(this).prop('checked') == true) {
checklist[myindex] = responseArray[myindex];
}
});
$('#currentlyChecked').text(checklist);
});
EDIT2:
I thought about this a bit and you can improve it by using .data() and query that or store it based on an event (my button called out by its id of "whatschecked")
var responseArray = ['math', 'science', 'technology', 'engineering'];// just for an example
var myList = '#subjects>input[type=checkbox]';//to reuse
for (var x = 0; x < responseArray.length; x++) {
// here we insert it all so we do not hit the DOM so many times
var iam = "<br />" + responseArray[x] + "<input type='checkbox' />";
$("#subjects").append(iam);
$(myList).last().data('subject', responseArray[x]);// add the data
}
var checklist = [];// holds most recent list set by change event
$(myList).on('change', function() {
checklist = [];
$(myList).each(function() {
var myindex = $(this).parent().find('input[type=checkbox]').index(this);
if ($(this).prop('checked') == true) {
checklist.push($(this).data('subject'));
alert('This one is checked:' + $(this).data('subject'));
}
});
});
// query the list we stored, but could query the checked list data() as well, see the .each() in the event handler for that example
$("#whatschecked").click(function() {
var numberChecked = checklist.length;
var x = 0;
for (x = 0; x < numberChecked; x++) {
alert("Number " + x + " is " + checklist[x] + " of " + numberChecked);
}
});
live example of last one: http://jsfiddle.net/Dr8k8/5/
The general pattern to do something when a checkbox input is clicked is:
$('input[type=checkbox]').click(function() {
// Do something
})
The general pattern to check whether a checkbox input is checked or not is:
var isItChecked = $('input[type=checkbox]').is(':checked');
In your particular case you'd probably want to do something like:
$('#subjects input[type=checkbox]').click(function() {
to limit the checkboxes involved to the ones inside your #subjects element.

Why alert popup a few times after a click event?

On a page there are couple of Add buttons (li .plus).
When you click on a Add button and assume json.success is false, it will then popup via $.colorbox plugin
The popup pull the data from href:"/Handle/Postcode/?val" + Val
There is a submit button (#submitButton) from the popup, when I click on the submit button, it keep popup alert box a few times, I dont understand why that happen? how to fix it?
$("li .plus").click(function(event) {
event.preventDefault();
var Val;
Val = $('#id').val()
$.getJSON(Address +"/Handle/Add", {
Val:Val
}, function(json) {
if (json.success == "false" && json.error == "NoArea") {
$.colorbox({
width:"450px",
transition:"none",
opacity:"0.4",
href:"/Handle/Postcode/?val" + Val
});
$("#submitButton").live('click', function() {
var PostCodeArea = $("#deliveryAreaPostcode").val();
alert(PostCodeArea);
//Why does it popup a few times?
});
}
if (json.success == "true") {
Backet();
}
});
});
Thats an easy one, because you are using the .live() function to bind your click handler. If that code gets executed more than one time your binding happens more than one time.
You can either try to track the state of the binding and only apply it if it doesn't exist, or you can call your click function in the html with the onClick attr.
Edit: Just to clarify I meant something along the lines of -
HTML
<button id='submitButton' onclick="displayAreaCode();">Submit</button>
JS
function displayAreaCode(){
var PostCodeArea = $("#deliveryAreaPostcode").val();
alert(PostCodeArea);
}

Categories

Resources