I've created a JSfiddle here:
basically I have a form that will allow users to input additional sections... but when I have added more than 2 units and then proceed to click on the 'plus' (+) icon I get more than 1 element created in that section... its probably something elementary, but any info will help.
Move your Click functions out of the click function
//add unit input box and increment click counter by one.
addUnit.click(function () {
unitCounter += 1;
unitElementCount = jQuery(".unit-element").length;
if (unitCounter <= 4) {
error.hide();
container.append('<table id="unit-' + unitCounter + '-div" class="create-course-table-element unit-element"><tr><td><label class="unit-label">Unit ' + unitCounter + '</label></td><td><input class="create-course-input-element unit-input" id="unit-id-' + unitCounter + '" name="unit-' + unitCounter + '" /><div id="delete-unit-' + unitCounter + '" class="ui-icon ui-icon-circle-close del-unit" title="Delete unit"></div></td></tr><tr><td align="center">Sections</td><td><div id="add-section-icon-' + unitCounter + '" class="ui-icon ui-icon-plus add-section-icon"></div></td></tr></table><div id="section-id-' + unitCounter + '-div" class="this-section"></div>');
} else if (unitElementCount == 4) {
unitCounter = 5;
error.html("");
error.fadeIn(1500);
error.append("<p class='error-message'>Note: You are only able to add 4 units to a given course. Each unit allows you to add 10 separate sections of content; therefore you may add a total of 40 different sections to a given course. If the material requires more units, you should consider dividing the course into 2 parts.</p>");
}
});
//This part has been slightly modified and moved out of the addUnit.click() function
var counterSecTwo = 0;
var counterSecThree = 0;
var counterSecFour = 0;
jQuery(document).on("click", "#add-section-icon-2",function () {
counterSecTwo += 1;
var container = jQuery("#section-id-2-div");
container.append("<p>test "+counterSecTwo+"</p>");
});
jQuery(document).on("click", "#add-section-icon-3",function () {
counterSecThree += 1;
var container = jQuery("#section-id-3-div");
container.append("<p>test "+counterSecThree+"</p>");
});
jQuery(document).on("click", "#add-section-icon-4",function () {
counterSecFour += 1;
var container = jQuery("#section-id-4-div");
container.append("<p>test "+counterSecFour+"</p>");
});
});
Here I am binding the click handlers to Document as the elements do not exist yet: you could also add the event listener when you create the actual element.
Modified fiddle: http://jsfiddle.net/vewP7/
Related
I am trying to create pagination with the below code and I am facing the problem to access page number ($clickedPageLink.dataset.page) when I click Prev and Next links. However, I am able to successfully get the page number when I click page number 1 to 5. Please find the plunker for reference Pagination. When click Prev and Next, console.log($clickedPageLink.dataset.page) is giving undefined. Can any one help to get the values for Prev and Next also as given in html?
let prevVal = 2;
let nextVal = 3;
let str = ['<nav class="pagination">'];
str.push('<ul class="pagination__pages">');
str.push('<li class="pagination__page pagination--previous">');
str.push('<a class="pagination__link" data-page="' + (prevVal - 1) + '" href="#">');
str.push('<span><i class="fas fa-angle-left"></i> Prev</span>');
str.push('</a></li>');
for (let plengthMn = 1; plengthMn <= 5; plengthMn++) {
str.push('<li class="pagination__page">');
str.push('<a class="pagination__link" data-page="' + plengthMn + '" href="#">' + plengthMn + '</a>');
str.push('</li>');
}
str.push('<li class="pagination__page pagination--next">');
str.push('<a class="pagination__link" data-page="' + (nextVal + 1) + '" href="#">');
str.push('<span>Next <i class="fas fa-angle-right"></i></span>');
str.push('</a></li>');
const $paginationList = document.getElementById('products-item_pagination');
$paginationList.innerHTML = str.join('');
const $paginationLinkMn = document.querySelectorAll('.pagination__link');
function attachEventToElementList(elmList, event, eventHandler) {
if(!elmList) {
return;
}
elmList.forEach(function(elm) {
elm.addEventListener(event, eventHandler);
});
}
attachEventToElementList($paginationLinkMn, 'click', goToPageMn);
function goToPageMn(event) {
const $clickedPageLink = event.target;
console.log($clickedPageLink.dataset.page)
}
And in my html, I have,
<div id="products-item_pagination" class="product-pagination"></div>
The problem with the above code is, the event is never firing up for anchor tag which is the parent of prev icon. Below css hack has solved the problem.
a > * {
pointer-events: none;
}
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>");
}
});
}
});
});
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()]));
}
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++);
});
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.