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

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()]));
}

Related

why my for loop is infinite here

below is the js code for wikipedia search project. I am getting infinite for loop even though it had condition to stop repeating the loop. I am stuck in this problem.
$(document).ready(function() {
$('.enter').click(function() {
var srcv = $('#search').val(); //variable get the input value
//statement to check empty input
if (srcv == "") {
alert("enter something to search");
}
else {
$.getJSON('https://en.wikipedia.org/w/api.php?action=opensearch&search=' + srcv + '&format=json&limit=20&callback=?', function(json) {
$('.content').html("<p> <a href ='" + json[3][0] + "'target='_blank'>" + json[1][0] + "</a><br>" + json[2][0] + "</p>");
/*for loop to display the content of the json object*/
for (i = 1; i < 20; i++) {
$('p').append("<p><a href ='" + json[3][i] + "'target='_blank'>" + json[1][i] + "</a>" + json[2][i] + "</p>");
}
});
}
});
});
You are appending to each and every one of <p> in page.
Since your for loop appends even more <p> (and you possibly have a high number of <p> elements in your page beforehand) you overflow your call stack.
You probably wanted to append to a specific <p>. Try giving an id to your selector.
from what i can see in the url you need to do the following:
loop over the terms found and select the link based on the index of the element, chose a single element .contentto append the data not a set of elements p, this will increase the number of duplicated results
$.getJSON('https://en.wikipedia.org/w/api.php?action=opensearch&search='+srcv+'&format=json&limit=20&callback=?', function(json){
$.each(json[1],function(i,v){
$('.content').append("<p><a href ='"+json[2][i]+"'target='_blank'>"+json[0]+"</a>"+v+"</p>");
});
});
see demo: https://jsfiddle.net/x79zzp5a/
Try this
$(document).ready(function() {
$('.enter').click(function() {
var srcv = $('#search').val(); //variable get the input value
//statement to check empty input
if (srcv == "") {
alert("enter something to search");
}
else {
$.getJSON('https://en.wikipedia.org/w/api.php?action=opensearch&search=' + srcv + '&format=json&limit=20&callback=?', function(json) {
$('.content').html("<p> <a href ='" + json[3][0] + "'target='_blank'>" + json[1][0] + "</a><br>" + json[2][0] + "</p>");
/*for loop to display the content of the json object*/
var i = 1;
for (i; i < 20; i++) {
$('p').append("<p><a href ='" + json[3][i] + "'target='_blank'>" + json[1][i] + "</a>" + json[2][i] + "</p>");
}
});
}
});
});

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++);
});

How to dynamically assign an id to an image

var intFields = 0;
var maxFields = 10;
function addElement() {
"use strict";
var i, intVal, contentID, newTBDiv, message = null;
intVal = document.getElementById('add').value;
contentID = document.getElementById('content');
message = document.getElementById('message');
if (intFields !== 0) {
for (i = 1; i <= intFields; i++) {
contentID.removeChild(document.getElementById('strText' + i));
}
intFields = 0;
}
if (intVal <= maxFields) {
for (i = 1; i <= intVal; i++) {
intFields = i;
newTBDiv = document.createElement('div');
newTBDiv.setAttribute('id', 'strText' + intFields);
newTBDiv.innerHTML = "<input placeholder='recipient" + intFields + "#email.com' type='text' name='" + intFields + "'/><a href='javascript:removeElement();'><img id='strImg + " + intFields + "' src='images/minus.png' alt='Add A Field'/></a><input type='text' value='" + newTBDiv.id + "'/>";
contentID.appendChild(newTBDiv);
message.innerHTML = "Successfully added " + intFields + " fields.";
}
} else {
for (i = 1; i <= maxFields; i++) {
intFields = i;
newTBDiv = document.createElement('div');
newTBDiv.setAttribute('id', 'strText' + intFields);
newTBDiv.innerHTML = "<input placeholder='recipient" + intFields + "#email.com' type='text' name='" + intFields + "'/><a href='javascript:removeElement();'><img id='strImg + " + intFields + "' src='images/minus.png' alt='Add A Field'/></a><input type='text' value='" + newTBDiv.id + "'/>";
contentID.appendChild(newTBDiv);
message.innerHTML = "Unable to create more than 10 receipient fields!";
}
}
}
My script here dynamically adds up to 10 fields where users will be able to enter an email address and to the right of the text box i add an image of a minus sign that calls another script. I'm having trouble working out how to assign and keep track of the minus signs. I need to be able to have the minus sign script's recognize the text box it is by and remove it. I can write the remove script easily enough but I'm unsure of how to tell the image which text box to remove. Any help, suggestions, or comments are greatly appreciated.
Thanks,
Nick S.
You can add a class to the field called minus and then check through like that. I would suggest using jquery for this.
To add the class
$("#element").addClass("minus");
To remove all elements with that class
$("body input").each(function (i) {
if($(this).attr("class") == "minus"){
$(this).remove();
}
});
The two best options, imo, would be 1) DOM-traversal, or 2) manipulating ID fragments.
Under the first way, you would pass a reference to the element where the event takes place (the minus sign) and then navigate the DOM from there to the get the appropriate text box (in jQuery you could use $(this).prev(), for example).
Under the second way, you would assign a prefix or a suffix to the ID of the triggering element (the minus sign), and the same prefix or suffix to the target element (the text box). You can then (again) generate the appropriate ID for your target element by simple string manipulation of the ID from the triggering element.
Is that sufficient to get you started?
Try adding a class to the field and the same class to the minus sign.
So add this right after the setAttribute id,
newTBDiv.setAttribute('class', 'field' + intFields);
then just remove any elements that have that class.

Save multiple selection of dropdown list to variables using Javascript

I have there dropdown lists with values, and one textarea to write those valuse in. When i press button it writes values of all three selected dropdown lists, it do that every time when i press the button (it do it three times). This pice of code writes values of dropodown lists, like this:
Button pressed first time: "Conntent of dropdown lists" undefinedundefined
Button pressed second time: undefined"Conntent of dropdown lists"undefined
Button pressed third time: undefinedundefined"Conntent of dropdown lists"
But i want values of dropdown list not "undefined"
What can you think of?
var i = 0;
function inc(){
i++;
if (i == 1){
var UkupnaPorudzbina1 = VrsteName + ' -> ' + PodvrsteName + ' -> ' + VelicineName + i;
}else if (i == 2){
var UkupnaPorudzbina2 = VrsteName + ' -> ' + PodvrsteName + ' -> ' + VelicineName + i;
}else if (i == 3){
var UkupnaPorudzbina3 = VrsteName + ' -> ' + PodvrsteName + ' -> ' + VelicineName + i;
}
var porudzba = UkupnaPorudzbina1 + UkupnaPorudzbina2 + UkupnaPorudzbina3;
document.frmMain.PorudzbaHolder.value = porudzba ;
}
VrsteName is:
VrsteName = document.frmMain.Vrste.options[document.frmMain.Vrste.selectedIndex].text
PodvrsteName and VelicinaName are same sort
And html part is:
<textarea name="PorudzbaHolder" rows="4"> </textarea>
<input type="button" value="Dodaj porudzbinu" onClick="inc();"/>
Thx in advance...
This is because you are declaring only one of the three variables each time, but then referencing all three later. Try declaring your variables first and initializing them to "":
var UkupnaPorudzbina1 = "";
var UkupnaPorudzbina2 = "";
var UkupnaPorudzbina3 = "";
Then run the rest of your code as written, but leaving the var out before each assignment to UkupnaPorudzbina.

Jquery Scope Problems

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');

Categories