How can I prevent double binding on JavaScript? - javascript

Here's my situation, I have a table which can add/remove rows dynamically and I need to bind the remove row when the page loads.
Here's my code:
<script type="text/javascript">
$(document).ready(function(){
$(".btnRemoveRow").bind("click", removeRow); });
</script>
But I also need to Bind another removeRow when I add rows here's on my external js
function addRow(){
{--add row code here--}
$(".btnRemoveRow").bind("click", removeRow);
}
so that the newly added rows will also be bind with the removeRow function,
here is my removeRow function:
function removeRow(){
var row = $(this).closest('tr');
var selected = row.find('input.qty,input.price,textarea,select').val();
$.getScript("calculate.js", function(){});
if(selected)
{
var r=confirm("Confirm Remove?");
if (r==true)
{
row.find('input.qty,input.price,textarea,select').attr("disabled", true);
row.find('input.hidden-deleted-id').val("yes");
row.find('.subtotal>center>h3').text("0");
calculate();
row.hide();
return false;
}
else
{
return false;
}
}
else{
row.find('input.qty,input.price,textarea,select').attr("disabled", true);
row.find('input.hidden-deleted-id').val("yes");
row.find('.subtotal>center>h3').text("0");
calculate();
row.hide();
return false;
}
};
Case 1: when I remove row without adding any rows first, it works fine (dialog box only appears once).
Case 2: when I add row first then remove the rows that were already bound on the page ready, dialog box appears twice.
Case 3: when I remove rows that I added, it works fine (dialog appears once).
(PS: still learning JavaScript)
Any idea how may I solve case no.2 please?

Add one event handler that is delegated, that way it will work for existing elements, and future elements
<script type="text/javascript">
$(document).ready(function(){
$(document).on("click", ".btnRemoveRow", removeRow);
});
</script>
replace document with the closest non-dynamic parent element.

Try this:
<script type="text/javascript">
$(function(){
$(".btnRemoveRow").click(function(){removeRow();});
});
</script>

Related

Alert toggles every time when the input is changed

I have input and it toggles a function if it's been changed. I also have table that is created dynamically. And each row in table has an addButton. So, the problem is that this alert toggles so many times so I change the input, but I need to toggle it only once. How to deal with it?
$('.inputsearchform').bind('input', function() {
var addButton = $(".fa.fa-plus");
addButton.click(function() {
alert("test");
});
});
I don't need to add click event to this button, but I need to get onclick() event from it. But this code is only working way, that I found. By the way, I need to get this event only if button is clicked, not every time that I change input.
Question How to check onclick event on button, that appears dynmically, when the input changes?
I tried to add onclick event <i class="fa fa-plus" onclick="addButtonF()">
and in js file: function addButtonF(){
alert("test");
}
but I have an error addButtonF is not defined.
A start would be to define click outside of input handler to prevent multiple click handler calls at each click of addButton
So, the problem is that this alert toggles so many times so I change
the input, but I need to toggle it only once.
Not clear from Question which element needs to be toggled once, or which function should only be called once ?
addButton appears only if I write something in input. I need to use
alert only if I click on this button, not every time that I change
input.
Use event delegation to attach event to dynamically created elements having className .fa.fa-plus
$(".inputsearchform").bind("input", function() {
// create dynamic element
$("<table class='fa fa-plus'>")
.html("<tr><td>"
+ $(".fa.fa-plus").length
+ "</td></tr>"
).appendTo("body");
});
$(document).on("click", ".fa.fa-plus", function() {
alert("test");
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js">
</script>
<input type="text" class="inputsearchform">
Substitute className for class which does not set className of element; use latest version of jQuery
$(".inputsearchform").bind("input", function() {
var div = document.getElementById("div");
var table = document.createElement("table");
div.appendChild(table);
var tr = document.createElement("tr");
table.appendChild(tr);
var td = tr.insertCell(0);
td.innerHTML = "test";
td.className = "try"
});
$(document).on("click", ".try", function() {
alert("test");
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js">
</script>
<input type="text" class="inputsearchform">
<div id="div"></div>
jsfiddle https://jsfiddle.net/1x8ja6qe/2/

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.

onclick function for input checkbox - check on page load and also on click

I have this code:
$('input.ShowResellerAccounts').on('click', function(){
if($(this).is(':checked')){
$('tbody#pages').hide();
} else {
$('tbody#pages').show();
}
});
which hides/shows a table tbody id on click.
how can i make this code run on page load as well as on click?
In the document.ready function you can trigger the click event like
$('input.ShowResellerAccounts').trigger('click');
Separate it into a function and bind in on load as well as on click:
function checkInput(){
if($(this).is(':checked')){
$('tbody#pages').hide();
} else {
$('tbody#pages').show();
}
});
$(document).ready(function() {
$('input.ShowResellerAccounts')
.on('click', checkInput) // bind to click
.each(checkInput); // call now
});
u can use $(document).ready :
$(document).ready(function(){
//put your code here
});

Binding click function to dynamic divs

There will be number of such div created with unique div id,
when i click on click me it should show an alert for that productid,
i am doing it like
<div id="xyz{productid}">
Click Me
</div>
.....
<script type="text/javascript">
var uuid="{productid}"
</script>
<script src="file1.js">
code from file1.js
$(function () {
var d = "#xyz" + uuid;
$(d).click(function () {
alert("Hello" + uuid);
return false;
});
alert(d);
});
So code is also ok,but the basic problem with it is,
since i m doing it on category page where we have number of products,this function is getting bound to last product tile only,
I want it to be bound to that specific div only where it is been called
..............................
got a solution
sorry for late reply,was on weekend holiday, but i solved it by class type of architecture, where we create an object with each tile on page,and at page loading time we initialize all its class vars,so you can get seperate div id and when bind a function to it, can still use the data from its class variables, i m posting my code here so if any one want can use it,
UniqeDiv= new function()
{
var _this = this;
var _divParams = null;
var _uuid=null;
//constructor
new function(){
//$(document).bind("ready", initialize);
//$(window).bind("unload", dispose);
_uuid=pUUID;
initialize();
$('#abcd_'+_uuid).bind("click",showRatingsMe)
dispose();
}
function initialize(){
}
function showRatingsMe(){
alert(_uuid);
}
function dispose(){
_this = _divParams = null
}
}
//In a target file, im including this js file as below
<script type="text/javascript">
var pUUID="${uuid}";
</script>
<script type="text/javascript" src="http://localhost:8080/..../abc.js"></script>
You can use attribute selector with starts with wild card with jQuery on() to bind the click event for dynamically added elements.
$(document).on("click", "[id^=xyz]", function(){
//your code here
alert("Hello"+this.id);
return false;
});
I would add a class to each of your dynamic divs so that they are easier to query. In the following example, I'm using the class dynamic to tag the div's that are added dynamically and should have this click listener applied.
To attach the event, you can use delegated events with jQuery's on() function. Delegated events will fire for current and future elements in the DOM:
$(function() {
var d="#xyz"+uuid;
$(document).on('click', 'div.dynamic', function() {
alert("Hello"+uuid);
return false;
});
});
You can read more about event delegation here.
You can use
$("[id*='divid_']").click(function(){
});
but for this you need to make sure that all div IDs start with "divid_".

window.load document read does not run

I have a simple html5 page that renders a table with several rows. On two of the rows I gave a button that I want to act as a toggle button to show/hide a couple of other rows each.
The table is rendered intitally will all rows then I have a function that hides the 4 columns and sets the buttons to have the correct symbol.
When I run the page all the rows are visible... the window.load function does not run. I even tried document.ready and no joy. The toggle buttons once the inital click hides the rows functions correctly.
My code is...
<script type="text/javascript">
function toggleRetail() {
if ($('#but_RToggle').val()=="+"){
$('#but_RToggle').val("-");
$('#qretail').show("slow");
$('#hretail').show("slow");
} else {
$('#but_RToggle').val("+");
$('#qretail').hide("fast");
$('#hretail').hide("fast");
}
}
function toggleWholesale() {
if ($('#but_WToggle').val() == "+") {
$('#but_WToggle').val("-");
$('#qwholesale').show("slow");
$('#hwholesale').show("slow");
} else {
$('#but_WToggle').val("+");
$('#qwholesale').hide("fast");
$('#hwholesale').hide("fast");
}
}
$(window).bind("load", function () {
$('#but_RToggle').val("+");
$('#qretail').hide();
$('#hretail').hide();
$('#but_WToggle').val("+");
$('#qwholesale').hide();
$('#hwholesale').hide();
});
</script>
Any help appreciated.
Make sure that the jquery script tag is before this script block.
For loading, any of these:
$(document).ready(function(){
//code
});
$(function(){
//code
});
window.addEventListener('load', function(){
//code
},false);

Categories