Jquery Scope Problems - javascript

function drawLabel(labelsIndex) {
// Check not deleted Label data:(DBID, text, styling, x, y, isDeleted)
if (!labelData[labelsIndex][5]) {
// Create
var newLabel = $('<div id="label' + labelsIndex + '" style="font-size:' + (labelData[labelsIndex][6] * currentScale) + 'px;z-index:9999;position:absolute;left:' + labelData[labelsIndex][3] + 'px;top:' + labelData[labelsIndex][4] + 'px;' + labelData[labelsIndex][2] + '">' + labelData[labelsIndex][1] + '</div>');
$('#thePage').append(newLabel);
// Click edit
$('#label' + labelsIndex).dblclick(function() {
if (!isDraggingMedia) {
var labelText = $('#label' + labelsIndex).html();
$('#label' + labelsIndex).html('<input type="text" id="labelTxtBox' + labelsIndex + '" value="' + labelText + '" />');
document.getElementById('#label' + labelsIndex).blur = (function(index) {
return function() {
var labelText = $('#labelTxtBox' + index).val();
$('#label' + index).html(labelText);
};
})(labelsIndex);
}
});
The code is meant to replace a div's text with a textbox, then when focus is lost, the textbox dissapears and the divs html becomes the textbox value.
Uncaught TypeError: Cannot set property 'blur' of null
$.draggable.start.isDraggingMediaresources.js:27
c.event.handlejquery1.4.4.js:63
I think I'm getting a tad confused with the scope, if anyone could give me some points I'd appreciate it. It would also be good if someone could show me how to remove the blur function after it has been executed (unbind?)

document.getElementById('#label' + labelsIndex).blur is a javascript function and less jquery :) therefore the # hash there is just irrelevant.
$('#label'+labelsIndex).bind('blur',function (){
//labelText value goes here //
});
EDIT
to be honest ur over complicating it :)
<div id="txt1">I am div</div>
<textarea id="txt2">I am text</textarea>
$('#edit_button').click(function (){
var val = $('#txt1').hide().html();// hide the div,then get value,
$('#txt2').show().val(val);//show txtarea then put value of div into it
});
Do the opposite for $('#save_button');

Related

Textarea not generating from jQuery

I'm trying to make a website using jquery-1.11.1 where I want a <textarea> to be spawned whenever I click on the link which only shows on mouseenter on a div. But I'm getting an error in my console,
Uncaught ReferenceError: inputdivEditor is not defined (Please ignore JSFiddle errors)
I've absolutely no idea why I'm getting this. Here are my codes,
$(document).ready(function () {
$("[id^=divEditor-]").each(function () {
var content = $(this).html();
var targetID = $(this).attr('id');
var txtID = 'input' + targetID;
$('<textarea id="input' + targetID + '" name="' + txtID + '" >' + content + '</textarea>').insertBefore(this).css('display', 'none');
var button = "<a onclick='activateDivEditor(this, " + txtID + ")' class='custom-edit-button editDiv' id='active" + targetID + "'>Embed Code</a>";
$(this).on('mouseenter', function () {
$(this).prepend($(button));
$(this).css('position', 'relative');
});
$(this).on('mouseleave', function () {
$('.editDiv').remove();
});
});
});
function activateDivEditor(btn, txtId) {
var targetID = $(btn).parent().get(0).id;
var update = "<a onclick='deactivateDivEditor(this, " + txtId + ")' class='custom-edit-button updatediv' id='deactive" + targetID + "'>Update</a>";
var cancel = "<a onclick='cancelactivateDivEditor(this)' class='custom-edit-button cancel' id='cancelactive" + targetID + "'>Cancel</a>";
var targetClass = $('#' + targetID).attr('class');
var targetWidth = $('#' + targetID).width();
$('#' + targetID).css('display', 'none');
$('#input' + targetID).css('display', 'block').css('width', targetWidth - 2).css('height', '125px');
$('#input' + targetID).parent().css('position', 'relative');
$(update).prependTo($('#input' + targetID).parent());
$(cancel).prependTo($('#input' + targetID).parent());
}
JSFiddle Demo
How can I generate a textarea whenever I click on the button link? Need this help badly. Thanks.

modifying value of input text box after clicking on a check box

I have a function where I read the the text input value and update a counter which is displayed in another div. In some cases I show a check box along with text input field. At the moment when user select the check box the amount which is entered in the text input field is doubled and the result is showing in the counter correctly.
What am I trying to achieve id when the user select the check box the input field should be doubled along with the counter.
The text input in the betslip is added dynamically. So there might be more individual betlsips with check boxes in the view.
Here is my code (HTML view is generated dynamically through JS)
BetSlip.prototype.createSingleBetDiv = function(divId, Bet, winPlaceEnabled) {
document.betSlip.setSingleCount($('[name=singleBet]').length);
var id = divId.replace('_div','');
// If such bet already exists
if (!document.betSlip.singleDivExists(divId) && document.betSlip.getSingleCount() < maxNumberInBetslipRacing) {
var singleBetPosition = (Bet.position == null) ? '' : Bet.position;
var raceInfo = Bet.categoryName + ', ' + raceFullName + ' ' + Bet.name + ', ' + Bet.betTypeName + ' (' + Bet.value.toFixed(2) + ')';
var div = $('<div name="singleBet" class="bet gray2" id="' + divId + '"/>')
// Appending div with data
.data('Bet', Bet)
// Appending error element
$(div).append($('<p id="' + divId + '_error" style="display:none;"/>')
.addClass('alert alert-danger alert-dismissable'))
// Appending info element
$(div).append($('<p id="' + divId + '_info" style="display:none;"/>')
.addClass('alert alert-success alert-dismissable'))
var bgDiv = $('<div id="bgDiv"/>').appendTo(div)
// Append left part
var productName = (Bet.productName != null) ? getBrandBetName(Bet.productName) : Bet.betTypeName;
var leftDiv = $('<div class="left"/>')
.appendTo(div)
// Info abt the bet
.append($('<p class="title"><b>' + singleBetPosition + ' ' + Bet.horseName + '</b><span style="float:right">' + productName + '</span></p>'))
.append($('<p class="title">' + raceInfo + '</p>'))
.append($('<p/>')
.addClass('supermid')
// Creating input field
.append($('<input type="text" id="' + id + '_input"/>')
.keypress(function(event) {validateInputs(event, 'decimal')})
.keyup(function() {document.betSlip.updateSinglesTotalPrice()})))
// Creating WIN / PLACE checkbox selection
if (winPlaceEnabled) {
$(leftDiv).append($('<p><input name="winPlaceCheckBox" id="' + id + '_checkbox\" type="checkbox"><b>' + winPlace + '</b></p>')
.click(function() {document.betSlip.updateSinglesTotalPrice()}))
}
// Append Done and Reuse btns
$(leftDiv).append($('<a id="reuseBtn" class="button confirm gray reuse" style="display: none;"/>').html(reuse).click(function() {document.betSlip.reuseBet(divId)}))
$(leftDiv).append($('<a id="doneBtn" class="button confirm red donebtn" style="display: none"/>').html(done)
.click(function(){$('#' + divId).find('a.right.orange').click()}))
// Append right part
$(div).append($('<a class="right orange"/>')
.click(function() {
document.betSlip.removeSingleBetDiv(divId);
})
// Closing btn
.append($('<div class="icon_shut_bet"/>')))
// Add div to the bet slip map
document.betSlip.addSingleDiv(divId, div);
return div;
}
else {
if(this.getSingleCount() < maxNumberInBetslipRacing){
$("#betSlipError").show();
$("#betSlipError").html(sameBet);
return null;
}
else{
$("#betSlipError").show();
$("#betSlipError").html(maxBet);
return null;
}
}
}
In the win/place check box I am calling a function which take cares of updating the final price in the counter (Total bet). I would like to update the same in the input text field as well (double up the input value). In case check box is deselected the input amount should be half (both in input field as well as in the counter).
Function which updated the total bet value
BetSlip.prototype.updateSinglesTotalPrice = function() {
var totalBet = 0;
$('[name=singleBet]').each(function() {
var inputValue = $(this).find('input:text').val();
// Win / Place
if (document.betSlip.checkWinPlace(this)) totalBet += Number(inputValue * 2);
// Win or Place
else totalBet += Number(inputValue);
});
$("#betSinglesTotalBet").html(replaceParams(totBetPrice, [totalBet.toFixed(2), document.betSlip.getCurrency()]));
}

how can I modify my jQuery function to update the number counter

I am showing number counter in one of my section. When I add new betslips to the container the numbers are displaying correctly. However, when I delete any of the row the counter is not getting updated. For example if there are 3 rows numbered 1, 2 and 3 and if I delete row number 2 the updated values are 1 and 3. Infact the counter should reset to 1 and 2.
Here is my JS code
Adding the betslip rows
function createSingleBetDiv(betInfo) {
var id = betInfo['betType'] + '_' + betInfo['productId'] + '_' + betInfo['mpid'],
div = createDiv(id + '_div', 'singleBet', 'bet gray2'),
a = createA(null, 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>' + singleBetNumber + '. ' + betInfo['horseName'] + '</b></p>');
var raceInfo = "";
$("#raceInfo").contents().filter(function () {
if (this.nodeType === 3) raceInfo = $(this).text() + ', ' + betInfo['betTypeName'] + ' (' + betInfo['value'] + ')';
});
$(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 remove betslip
function removeSingleBet(id) {
// Remove the div
removeElement(id);
// Decrease the betslip counter
decreaseBetSlipCount();
// Decrease bet singles counter
updateBetSinglesCounter();
}
function decreaseBetSlipCount() {
var length = $("#racingBetSlipCount").text().length,
count = $("#racingBetSlipCount").text().substring(1, length-1),
text;
count = parseInt(count);
if (!isNaN(count)) count--;
if (count == 0) text = noSelections;
else text = count;
$("#racingBetSlipCount").text('(' + text + ')');
}
This could be done using only CSS, e.g:
DEMO jsFiddle
HTML:
<div id="bets">
<div class="bet"> some content</div>
<div class="bet"> some content</div>
<div class="bet"> some content</div>
</div>
CSS:
#bets {
counter-reset: rowNumber;
}
#bets .bet {
counter-increment: rowNumber;
}
#bets .bet::before {
content: counter(rowNumber);
min-width: 1em;
margin-right: 0.5em;
}
All row number will be updated automatically when adding/removing any row.
You can manage to do that with following steps;
Enclose bet no with span,
$(leftDiv).append('<p class="title"><b><span class="bet_no">' + singleBetNumber + '<span>. ' + betInfo['horseName'] + '</b></p>');
and I assume you have aouter div called "your_div"
Call below function after every increase and decrease event
function updateBetNo() {
var counter = 1;
$("#your_div .bet_no").each(function(i, val) {
$(this).text(counter);
counter++;
});
}
Make the betNumber findable:
$(leftDiv).append('<p class="title"><b><span class="singleBetNumber">' + singleBetNumber + '</span>. ' + betInfo['horseName'] + '</b></p>');
After an insert or delete renumber:
$('.singleBedNumber').each(function(idx, el) {
$(el).html('' + (idx + 1));
});
The first problem I see is that $("#racingBetSlipCount") is likely not selecting what you think it is. Since #racingBetSlipCount is an id selector it will only select one item.
To me you need to wrap the betnumber in something accessible so you can update it without having to parse through the title.
So first you would update the creation of the betTitle:
$(leftDiv).append('<p class="title"><b><span class=\'betNum\'>' + singleBetNumber + '</span>. ' + betInfo['horseName'] + '</b></p>');
Then you can loop through each and update the number appropriately.
var count = 1;
$.each($(".betNum"), function(){
$(this).html(count++);
});

jQuery adding pages

I have made an really ugly code, but i was going to fix it when i was done with it.. But i didn't come that far >_<
i post my code here and some information under it.
$(document).on('click', '.cogwheel', function() {
var link = $(this).data('pageid');
$(".pages").not(".page" + link).hide();
$(".links").not("#link-" + link).show();
$("#link-" + link).toggle();
$(".page" + link).toggle();
});
$(document).on('click', '.deletecross', function() {
$(".deleteClass" + $(this).data('pageid')).remove();
var total = parseFloat($(".hiddenCounter").val()) - 1;
$(".hiddenCounter").val(total);
var this_val = $(".pagae" + $(this).data('pageid')).val();
this_val.replace($(".pagae" + $(this).data('pageid')).val(), "");
$(".pagae" + total).val(this_val);
});
$(document).on('keyup', '.pages', function() {
var pageID = $(this).data('pageid');
var pages = $(".pagae").val();
$(".pagae" + pageID).val($(this).val());
$(".pagetest" + pageID).html($(this).val());
$(".pagae").val(pages + $(this).val());
$("#link-" + pageID).html($(this).val());
});
message = new Array();
jQuery.fn.update_textarea = function(test) {
//for (i=0;i<test;++i) {
if (message[test]) { $(".MenuLinks").append('<tr><td width="150">Sida ' + test + '</td><td align="right"><span class="glyphicon glyphicon-cog"></span></td></tr>');$("#articles_textarea").append('<h2>askda</h2><textarea id="editor-1"></textarea>'); }
else {
message[test] = '';
var TDRow1 = '<tr class="deleteClass' + test + '"><td width="150">Sida ' + test + '<input type="text" name="pages[]" value="Sida ' + test + '" class="pages page' + test + '" data-pageid="' + test + '"></td>';
var TDRow2 = '<td align="right" width="20"><span class="glyphicon glyphicon-cog cogwheel" data-pageid="' + test + '" style="cursor:pointer;" title="Redigera"></span></td></tr>';
var TDRowRemove = '<td align="right" width="10"><span class="glyphicon glyphicon-remove deletecross" data-pageid="' + test + '" style="cursor:pointer;color: #ff0000;" title="Radera"></span></td>';
var TDFake = '<td></td>';
if (test != 1) {
var TRRow = TDRow1 + TDRowRemove + TDRow2;
}
else {
var TRRow = TDRow1 + TDFake + TDRow2;
}
$(".MenuLinks").append(TRRow); $("#articles_textarea").append('<div id="Sida' + test + '" class="tab-pane"><input type="hidden" class="pagae' + test + '" name="pagae[]" value="Sida ' + test + '"> <h2 class="pagetest' + test + '">Sida ' + test + '</h2><textarea name="editor[]" id="editor-' + test + '" class="editor" data-pageid="' + test + '"></textarea></div>');
$("#editor-" + test).wysibb({lang: "en"});
}
//}
}
/* If no textareas available add a new one */
if (message.length == 0) {
$(this).update_textarea(1);
$("#Sida1").addClass("active");
}
});
This code you can add a page with, delete a page and write a new name for the page, and im using bootstrap so they all got there own "tab"
I was going to use this script to make an article system, and when you post it should insert pages into an own table like pages. And content to another.
But my problem here is, when im trying to remove a "link/page" it removes the page from the menu and everything.
But i dont have a freaking clue how to change the hidden input that has all the names of the pages in it.. So when i post the hidden input i got all pages i have on the page and those i removed..
I know this is some slabby code and i know you could make it better then me..
If you got any ideas or any thing that i can make smaller let me know..

jQuery "Unexpected token ILLEGAL"

I have two functions, that are for showing and hiding elements by class:
if (typeof showClass != 'function') {
function showClass(trClass, buttonId, hideMessage, showMessage) {
var button = '#' + buttonId;
var value = hideMessage;
$(button).attr("value", value);
$(button).attr("onclick", "hideClass('" + trClass + "', '" + buttonId + "', '" + showMessage + "', '" + hideMessage + ");");
var classToShow = '.' + trClass;
$(classToShow).css('visibility', 'visible');
}
}
if (typeof hideClass != 'function') {
function hideClass(trClass, buttonId, showMessage, hideMessage) {
var button = '#' + buttonId;
var value = showMessage;
$(button).attr("value", value);
$(button).attr("onclick", "showClass('" + trClass + "', '" + buttonId + "', '" + hideMessage + "', '" + showMessage + ");");
var classToHide = '.' + trClass;
$(classToHide).css('visibility', 'hidden');
}
}
showClass works as excepted, but hideClass causes error "Unexpected token ILLEGAL" in Chrome. With FireFox I don't get any errors, but the function doesn't work with either of the browsers. I tried with different editors to find some illegal characters etc., but no luck. What could be the cause for this?
You're apparently trying to set up a toggling button, but it's the most convoluted mess of jQuery and inline event handlers I've ever seen.
Try this:
function setupToggle(trigger, target, hideMessage, showMessage) {
var state = false; // true means button says "show", target is hidden
var $el = $(trigger);
function update() {
$el.attr('value', state ? showMessage : hideMessage);
$(target).css('visibility', state ? 'hidden' : 'visible');
}
update(); // set initial state
$el.on('click', function() {
state = !state; // on click, flick state and refresh
update();
});
}
usage:
setupToggle('#mybutton', '.mytr', 'Hide it', 'Show it');
The code above may require minor tweaks depending on whether the default state is "hidden" or "shown".

Categories