removing function on click jquery - javascript

I have gone through quite a few similar question but none of them fit to my problem.
I am calling a function after onclick event to my anchor tag and after clicking the anchor tag the function adds a row new row to another section within the webpage.
What I am trying to do is to revert the process back when a user clicks on the same anchor tag again. In other words the newly added row should be removed from the view if clicked again.
Here is my code where on click I am calling a function to add new rows
function drawSelections(betTypeId, tableId, selections) {
var whiteLegendTrId = tableId + '_whiteLegendTr';
$.each(selections, function(i, v){
var selectionRowId = tableId + '_' + v.id;
document.getElementById(tableId).appendChild(createTr(selectionRowId,null,"white"));
$('#' + whiteLegendTrId).find('td').each(function() {
var tdId = $(this).attr('id');
if (tdId == "pic") {document.getElementById(selectionRowId).appendChild(createTd(null, null, null, "",null))}
else if (tdId == "no") {document.getElementById(selectionRowId).appendChild(createTd(null, null, null, v.position,null))}
else if (tdId == "horseName" || tdId == "jockey") {document.getElementById(selectionRowId).appendChild(createTd(null, null, null, v.name,null))}
// Horse prices
else {
var priceNotFound = true;
$.each(v.prices, function(index,value) {
if (value.betTypeId == betTypeId && (value.productId == tdId || value.betTypeId == tdId)) {
priceNotFound = false;
var td = createTd(null, null, null, "", null),
a = document.createElement('a');
a.innerHTML = value.value.toFixed(2);
// adding new rows after onclick to anchore tag
(function(i, index){
a.onclick=function() {
var betInfo = createMapForBet(selections[i],index);
$(this).toggleClass("highlight");
increaseBetSlipCount();
addToSingleBetSlip(betInfo);
}
})(i,index)
td.appendChild(a);
document.getElementById(selectionRowId).appendChild(td);
}
});
if (priceNotFound) document.getElementById(selectionRowId).appendChild(createTd(null, null, null, '-',null));
};
});
});
}
Adding new rows
function addToSingleBetSlip(betInfo) {
// Show bet slip
$('.betslip_details.gray').show();
// Make Single tab active
selectSingleBetSlip();
// Create div for the bet
var div = createSingleBetDiv(betInfo);
$("#bets").append(div);
// Increase single bet counter
updateBetSinglesCounter();
}
This is the JS code where I am generating the views for the dynamic rows added after clicking the anchor tag in my first function
function createSingleBetDiv(betInfo) {
var id = betInfo.betType + '_' + betInfo.productId + '_' + betInfo.mpid,
div = createDiv(id + '_div', 'singleBet', 'bet gray2'),
a = createA(null, null, null, 'right orange'),
leftDiv = createDiv(null, null, 'left'),
closeDiv = createDiv(null, null, 'icon_shut_bet'),
singleBetNumber = ++document.getElementsByName('singleBet').length;
// Info abt the bet
$(leftDiv).append('<p class="title"><b><span class="bet_no">' + singleBetNumber + '</span>. ' + betInfo['horseName'] + '</b></p>');
var raceInfo = "";
$("#raceInfo").contents().filter(function () {
if (this.nodeType === 3) raceInfo = $(this).text() + ', ' + betInfo['betTypeName'] + ' (' + betInfo['value'].toFixed(2) + ')';
});
$(leftDiv).append('<p class="title">' + raceInfo + '</p>');
// Closing btn
(function(id) {
a.onclick=function() {
removeSingleBet(id + '_div');
};
})(id);
$(a).append(closeDiv);
// Creating input field
$(leftDiv).append('<p class="supermid"><input id="' + id + '_input\" type="text"></p>');
// Creating WIN / PLACE checkbox selection
$(leftDiv).append('<p><input id="' + id + '_checkbox\" type="checkbox"><b>' + winPlace + '</b></p>');
// Append left part
$(div).append(leftDiv);
// Append right part
$(div).append(a);
// Appending div with data
$.data(div, 'mapForBet', betInfo);
return div;
}
Function to delete the individual rows
function removeSingleBet(id) {
// Remove the div
removeElement(id);
// Decrease the betslip counter
decreaseBetSlipCount();
// Decrease bet singles counter
updateBetSinglesCounter();
}
function removeElement(id) {
var element = document.getElementById(id);
element.parentNode.removeChild(element);
}

It's not the most elegant solution, but it should get you started.
I tried keeping it in the same format as your code where applicable:
http://jsfiddle.net/L5wmz/
ul{
min-height: 100px;
width: 250px;
border: 1px solid lightGrey;
}
<ul id="bets">
<li id="bet_one">one</li>
<li id="bet_two">two</li>
</ul>
$(document).ready(function(){
var bets = $("#bets li");
var slips = $("#slips");
bets.bind("click", function(){
var that = $(this);
try{
that.data("slipData");
}catch(err){
that.data("slipData",null);
}
if(that.data("slipData") == null){
var slip = createSlip({slipdata:"data"+that.attr("id")});
slip.bind("click", function(){
that.data("slipData",null);
$(this).remove()
});
that.data("slipData",slip);
slips.append(slip);
}
else{
slips.find(that.data("slipData")).remove();
that.data("slipData",null);
}
console.log(that.data("slipData"));
});
});
function createSlip(data){
var item = $(document.createElement("li")).append("slip: "+data.slipdata);
return item;
}

Related

I'm not sure why my click event won't work

I'm trying to add a click event to .user that will change the background color of the entire page to green. I'm very new to jQuery, but the code looks right to me. When I click the .users button, nothing happens. Anyone have any ideas?
$(document).ready(function() {
var $body = $('body')
/*$body.html('');*/
// var currentView = "Twittler Feed"
var currentView = $('<p>Twittler Feed</p>');
var refreshTweet = function() {
var index = streams.home.length - 1;
var endInd = index - 10;
while (index >= endInd) {
var tweet = streams.home[index];
var $tweet = $('<div class="tweets"><p class="posted-by"><button class="user">#' +
tweet.user + '</button><p class="message">' + tweet.message +
'</p><p class="time">' + /*$.timeago(tweet.created_at)*/ tweet.created_at + '</p></div>');
currentView.appendTo('#sidebar')
$tweet.appendTo($body);
index -= 1;
}
}
refreshTweet();
$('.refresh').on('click', function() {
if (document.getElementsByClassName('tweets')) {
$('.tweets').remove();
}
var result = refreshTweet();
$body.prepend(result);
})
$('.user').on('click', 'button', function() {
currentView = this.user
$('body').css('background-color', 'green');
});
});

How to append element in the currently clicked table element from popup form?

So I have made a table table elements and functions for the pop up and the form. Appending element on clicking save button also works. However on a new popup the data from the form is appended in every previously clicked table cell no matter if the cell is full or empty.I am somehow trying to populate the cell with currently generated ID . Considering the fact that I me new at JavaScript I am totally missing something Can someone give me idea what is that. The Code
//================ADDs POPUP ON CLICK================/
$(document).ready(function () {
/*Adding the klikanje class to td*/
$('table tbody tr:not(:first) td').addClass('klikanje');
/*removing the klikanje class from the first column*/
$('table tr:first-child, table td:first-child').removeClass('klikanje');
/*removing the klikanje class from the first row*/
$('table tbody tr:first-child td').removeClass('klikanje');
/*Making random id*/
/*appending data atributs to empty td*/
$('.klikanje').click(function(){
var self = $(this);
if ($(this).is(':empty')) {
var idBase = 'clickId-';
function getRandomInt(min, max) {
return Math.floor(Math.random() * (max - min)) + min;
}
var idNumber = getRandomInt(1, 1000000);
var clickID = idBase + idNumber
var callingID = '#' + clickID;
$(this).attr({ 'data-toggle': 'modal', 'data-target': '#popUp', 'id': clickID });
/*save to td */
$('#save').click(function () {
var theName = $('input[name=name]').val();
var theLastName = $('input[name=lastname]').val();
var $fullCell = $('<p>' + theName + '' + theLastName + '</p>');
if((theLastName+theLastName).length > 0){
$(callingID).append($fullCell);
$(callingID).css('background-color', 'yellow');
}
}); /*save to td end */
} else {
alert('Already taken spot. Please pick another one!');
$(this).attr({ 'data-toggle': '', 'data-target': '', 'id': '' });
}
});
});//<---ADDs POPUP ON CLICK END
Full code : JsFiddle
You need to just empty the fields after saving the value because same popup html is used again and again and value once entered in the input elements will stay there until manually cleared.
Use below code.
var callingID = "";
$('.klikanje').click(function(){
var self = $(this);
if ($(this).is(':empty')) {
var idBase = 'clickId-';
function getRandomInt(min, max) {
return Math.floor(Math.random() * (max - min)) + min;
}
var idNumber = getRandomInt(1, 1000000);
var clickID = idBase + idNumber
callingID = '#' + clickID;
$(this).attr({ 'data-toggle': 'modal', 'data-target': '#popUp', 'id': clickID });
updated fiddle : https://jsfiddle.net/9zcj3ab8/27/
I don't know why this is happening but if you remove the attributes for what I think it's a bootstrap modal you get the desired behavior. I think is something related with you are referencing the modal with every cell you have clicked before, but removing the attributes it seems to work properly.
Update this in your code:
$('#save').click(function () {
var theName = $('input[name=name]').val();
var theLastName = $('input[name=lastname]').val();
var $fullCell = $('<p>' + theName + '' + theLastName + '</p>');
if((theLastName+theLastName).length > 0){
$(callingID).append($fullCell);
$(callingID).css('background-color', 'yellow');
$(this).attr({ 'data-toggle': '', 'data-target': '', 'id': '' });
}); /*save to td end */

Clone div if it overflows parent bottom to other div

I'm making an A4-print template for WP, and I want it to dynamically create new pages when content overflows. So my plan is to target each child div that has an offset greater than the parents .top + height();. Note: I use the self.css('color','red'); to check that the function is working.
With this code below I get an error:
copyCon is not defined
function newPage() {
if ($(this).height() > a4Height) {
offObject.each(function() {
var self = $(this);
var offObjectWrap = self.parent().parent().parent('.docWrap');
var wrapBottom = offObjectWrap.offset().top + offObjectWrap.height();
var selfPos = self.offset().top + self.height();
if (selfPos > wrapBottom) {
var copyCon = $(this).clone();
} else {
self.css('color', 'red');
}
});
var copyFooter = $(".offerFooter").clone();
$(this).parent().parent().after('<section id="page4" class="offerPage docWrap pageTwo clearfix"><div class="docPad clearfix"><div class="docCon clearfix">' + copyCon.html() + '</div></div><div class="offerFooter clearfix">' + copyFooter.html() + "</div></section>");
}
}
docCon.each(newPage);

jQuery price calculator function is not working with tabs

I have been trying to get this working from last couple of days without any success. I have this price calculator function developed by a freelancer who is not reachable from last few weeks.
This function works fine without any JavaScript tabs but not quite right with them. I need to have tabs on page because there are tons of options in this calculator.
This is the jQuery function.
$(document).ready(function() {
// For tabs
var tabContents = $(".tab_content").hide(),
tabs = $("ul.nav-tabs li");
tabs.first().addClass("active").show();
tabContents.first().show();
tabs.click(function() {
var $this = $(this),
activeTab = $this.find('a').attr('href');
if (!$this.hasClass('active')) {
$this.addClass('active').siblings().removeClass('active');
tabContents.hide().filter(activeTab).fadeIn();
}
return false;
});
// For Calculator
function Cost_Calculator() {
var Currency = '$';
var messageHTML = 'Please contact us for a price.';
function CostFilter(e) {
return e;
}
//Calculate function
function calculate() {
//Blank!
var CalSaveInfo = [];
$('#cost_calc_custom-data, #cost_calc_breakdown').html('');
//Calculate total
var calCost = 0;
var calculate_class = '.cost_calc_calculate';
$('.cost_calc_active').each(function() {
//Calculation
calCost = calCost + parseFloat($(this).data('value'));
//Add to list
var optionName = $(this).attr('value');
var appendName = '<span class="cost_calc_breakdown_item">' + optionName + '</span>';
var optionCost = $(this).attr('data-value');
var appendCost = '<span class="cost_calc_breakdown_price">' + Currency + optionCost + '</span>';
if (optionCost != "0") {
var appendItem = '<li>' + appendName + appendCost + '</li>';
}
//hidden data
var appendPush = ' d1 ' + optionName + ' d2 d3 ' + optionCost + ' d4 ';
$('#cost_calc_breakdown').append(appendItem);
CalSaveInfo.push(appendPush);
});
//Limit to 2 decimal places
calCost = calCost.toFixed(2);
//Hook on the cost
calCost = CostFilter(calCost);
var CustomData = '#cost_calc_custom-data';
$.each(CalSaveInfo, function(i, v) {
$(CustomData).append(v);
});
//Update price
if (isNaN(calCost)) {
$('#cost_calc_total_cost').html(messageHTML);
$('.addons-box').hide();
} else {
$('#cost_calc_total_cost').html(Currency + calCost);
$('.addons-box').show();
}
}
//Calculate on click
$('.cost_calc_calculate').click(function() {
if ($(this).hasClass('single')) {
//Add cost_calc_active class
var row = $(this).data('row');
//Add class to this only
$('.cost_calc_calculate').filter(function() {
return $(this).data('row') == row;
}).removeClass('cost_calc_active');
$(this).addClass('cost_calc_active');
} else {
// Remove class if clicked
if ($(this).hasClass('cost_calc_active')) {
$(this).removeClass('cost_calc_active');
} else {
$(this).addClass('cost_calc_active');
}
}
//Select item
var selectItem = $(this).data('select');
var currentItem = $('.cost_calc_calculate[data-id="' + selectItem + '"]');
var currentRow = currentItem.data('row');
if (selectItem !== undefined) {
if (!$('.cost_calc_calculate[data-row="' + currentRow + '"]').hasClass('cost_calc_active'))
currentItem.addClass('cost_calc_active');
}
//Bring in totals & information
$('#cost_calc_breakdown_container, #cost_calc_clear_calculation').fadeIn();
$('.cost_calc_hide').hide();
$('.cost_calc_calculate').each(function() {
if ($(this).is(':hidden')) {
$(this).removeClass('cost_calc_active');
}
calculate();
});
return true;
});
$('#cost_calc_clear_calculation').click(function() {
$('.cost_calc_active').removeClass('cost_calc_active');
calculate();
$('#cost_calc_breakdown').html('<p id="empty-breakdown">Nothing selected</p>');
return true;
});
}
//Run cost calculator
Cost_Calculator();
});
You can see this working on jsfiddle without tabs. I can select options from multiple sections and order box will update selected option's price and details dynamically.
But when I add JavaScript tabs, it stop working correctly. See here. Now if I select option from different sections, order box resets previous selection and shows new one only.
I think the problem is with calculator somewhere.
You are removing the active class from hidden elements. This means that when you move to the second tab you disregard what you've done in the first.
line 120 in your fiddle:
if ($(this).is(':hidden')) {
$(this).removeClass('cost_calc_active');
}
I haven't taken the code in depth enough to tell if you can just remove this.

If list item exists do not append but change the fontcolor

I have this script that appends a list item if it's not allready there.
What i want it to do also is that if the list item does allready exist that it's font color(css)is set to another color.
var itemName = userName,
userFound = false;
$('#msgUserlist li').each(function () {
if ($(this).text() === itemName) {
userFound = true;
}
});
if (userFound === true) {
////// at this point i want the fontcolor of the allready existing item be set.///
return;
} else
var newNode = document.createElement('li');
newNode.innerHTML = '<a id="switchtoUser" name="' + userName + '" ' + 'onclick="ajaxChat.getHistory' + '(\'' + userName + '\')"' + ' href="javascript:ajaxChat.sendPrivateMessageWrapper(\'/query ' + userName + '\');">' + userName + '</a>';
document.getElementById('msgUserlist').appendChild(newNode);
},
You can do it while looping through the list when you're searching for the user:
// ...snip
$('#msgUserlist li').each(function () {
if ($(this).text() === itemName) {
userFound = true;
$(this).css({
color: "blue" // or whatever
});
return;
}
});
// ...snip
Why don't you do the moment you find it?
if ($(this).text() === itemName) {
userFound = true;
$(this).css('color', 'red'); // Example: change the color to red
}
I think this would be nicely solved by the Jquery function css()
HTML
<ul id=msgUserlist>
<li>Foo</li>
<li>userName</li>
<li>tball rulez</li>
</ul>
Javascript
var itemName = 'userName';
$( document ).ready(function() {
$("#msgUserlist li").each(function() {
if($(this).text() == itemName )
$(this).css("color", "red");
})
})
See working example (simple, but can be expanded with the logic you outlined in your question!): http://jsfiddle.net/PGfgv/601/

Categories