Retrieve multiple elements with "getElementById"? - javascript

I've tried using the techniques mentioned in these questions, but I haven't had any luck. I'm trying to adjust a JavaScript function to retrieve multiple divs using the getElementById method.
Here is the current line of code within the function which retrieves the div #cat1:
var elem = document.getElementById(cat1);
Moving forward, I need this function to also retrieve the div #cat2.
jQuery can be loaded if there's a better method to accomplish this using their library?
Here is the full function (reference Line 3):
function getCategories(initial) {
var i;
var elem = document.getElementById('cat1');
if (initial == 1) {
jsonGroups = "";
jsonGroups = '{ xml: [], "pin": [] ';
for (i = 0; i < elem.childNodes.length; i++) {
if (elem.childNodes[i].nodeName == "LI") {
jsonGroups = jsonGroups + ', "' + elem.childNodes[i].attributes.getNamedItem("id").value + '": [] ';
}
}
jsonGroups = jsonGroups + "}";
markerGroups = eval('(' + jsonGroups + ')');
for (i = 0; i < elem.childNodes.length; i++) {
if (elem.childNodes[i].nodeName == "LI") {
var elemID = elem.childNodes[i].attributes.getNamedItem("id").value;
if (elemID != "user") {
elem.childNodes[i].innerHTML = "<a onclick='" + 'toggleGroup("' + elemID + '")' + "'>" + elem.childNodes[i].innerHTML + "</a>";
} else {
elem.childNodes[i].innerHTML = '<form id="userPOIForm" action="#" onsubmit="userPOIFind(this.userPOI.value); return false"><input id="userPOITxt" size="20" name="userPOI" value="' + elem.childNodes[i].innerHTML + '" type="text"><input id="userPOIButton" value="Go" type="submit"> </form>';
}
if (hasClass(elem.childNodes[i], "hidden") !== null) {
elem.childNodes[i].setAttribute("caption", "hidden");
} else {
elem.childNodes[i].setAttribute("caption", "");
}
if (elem.childNodes[i].attributes.getNamedItem("caption").value != "hidden") {
classAdder = document.getElementById(elemID);
addClass(classAdder, "visibleLayer");
}
}
}
}
for (i = 0; i < elem.childNodes.length; i++) {
if (elem.childNodes[i].nodeName == "LI") {
var catType = elem.childNodes[i].attributes.getNamedItem("id").value;
result = doSearch(elem.childNodes[i].attributes.getNamedItem("title").value, elem.childNodes[i].attributes.getNamedItem("id").value);
}
}
}

If you are trying to select all elements with an id that starts with cat, you can do this in jQuery like this:
$("[id^=cat]")
jQuery: Attributes Starts With Selector

Just make categoriesList be another parameter, and call the function twice.

Related

Is there a way to have multiple inline configured ckeditors with single toolbar DOM element

An inline configured ckeditor has its toolbar attached to document body. Unless the user didn't focus the editor the toolbar is hidden. If we have multiple inline editors on same page, there will be the same number toolbar DOM elements attached to the body - each one with specific identifier. My question is, if there is a way to have a single toolbar DOM element for multiple inline ckeditors? I know (and I'm using in different context) the shared space plugin which does that, but the drawback is that one should provide an element to which the single toolabar would be attached. That's OK, but it is static and stays at the place where it's placed in the DOM order and I'd like it to be repositioned next to the currently focused editor.
Seems like I either have to use the default inline behavior or to use the shared space plugin and to reposition the single toolbar instance myself.
Any ideas on this issue or something I'm missing?
No, every CKEditor creates its own toolbar. But you can create your own plugin for this which is actually just displaying the toolbar of the active element. I have created one have a look. You do require to configure the your editor config too.
CKEDITOR.plugins.add('grouplabel', {
init : function(editor) {
function getCorrespondingName(no) {
var tempNo = 0;
for (var i = 0; i < editor.config.toolbar.length; i++) {
if (editor.config.toolbar[i].groupName != undefined) {
if (tempNo == no) {
return i;
}
tempNo++;
}
}
}
function toggleGroupDisplay(evt) {
if (evt.data.isMinimized) {
resetAllAbsolute();
$(this).find(".absoluteToolCont").toggleClass("displayNone");
} else {
$('.' + evt.data.grpID).each(function() {
toggleGroupDisplayInd(this)
});
}
}
function resetAllAbsolute() {
$(".absoluteToolCont").addClass("displayNone");
}
function toggleGroupDisplayInd(obj) {
var idM = $("#" + obj.id).parent().attr("id");
$("#" + idM + "> span").toggleClass("displayNone");
$("#" + idM).toggleClass("toggleMargin");
$("#groupLabel_" + idM).toggleClass("toggleMargin");
$("#groupLabelArrowBtn_" + idM).toggleClass("groupLabelArrowDown");
}
var openContainerArray = [ "CHARACTER", "TEXT ALIGN" ];
function createMainGroups() {
for (var j = 0; j < editor.toolbox.toolbars.length; j++) {
var grpId = editor.toolbox.toolbars[j].id;
var conNo = getCorrespondingName(j);
var isGroup = editor.config.toolbar[conNo].groupNR;
if (!isGroup) {
createMainGroup(conNo, grpId);
}
}
}
function createMainGroup(conNo, grpId) {
// console.log(conNo, grpId)
var name = editor.config.toolbar[conNo].groupName[0];
var className = editor.toolbar[conNo].name;
var name = editor.config.toolbar[conNo].groupName[0];
var elementDiv = groupLabelElementDiv(grpId, className);
var textDiv = "<div class='textGroupLabel'></div>";
var arrowDiv = "<div id='groupLabelArrowBtn_" + grpId
+ "' class='groupLabelArrowUp'></div>";
$("#" + grpId).addClass("editorGroup transitionType");
if (editor.config.showIconOnly) {
detachAndMakeAbsolute(grpId);
}
$("#" + grpId).prepend(elementDiv);
$("#groupLabel_" + grpId).append(textDiv);
if (!editor.config.showIconOnly) {
$("#groupLabel_" + grpId).append(arrowDiv);
}
addNameOrIcon(editor, name, grpId);
$(" #groupLabel_" + grpId).unbind("click").bind("click", {
grpID : "groupLabel_" + className,
isMinimized : editor.config.showIconOnly
}, toggleGroupDisplay);
var bool = false;
if (!editor.config.showIconOnly) {
for (var k = 0; k < openContainerArray.length; k++) {
if (name == openContainerArray[k]) {
bool = true;
}
}
}
showGroup(bool, grpId);
}
function detachAndMakeAbsolute(grpId) {
var divId = "absoluteToolCont_" + grpId
var absoluteDiv = "<div class='displayFlexAbsolute"
+ " absoluteToolCont' id='" + divId + "'></div>";
$("#" + grpId).prepend(absoluteDiv);
var detachedDiv = $("#" + grpId + "> span").detach();
// console.log(detachedDiv)
detachedDiv.appendTo("#" + divId);
resetAllAbsolute();
}
function showGroup(bool, grpId) {
if (!bool) {
$("#" + grpId + "> span").toggleClass("displayNone");
$("#" + grpId).toggleClass("toggleMargin");
$("#groupLabel_" + grpId).toggleClass("toggleMargin");
$("#groupLabelArrowBtn_" + grpId).toggleClass(
"groupLabelArrowDown");
}
}
function addNameOrIcon(editor, name, grpId) {
var groupName = $("#groupLabel_" + grpId + ">.textGroupLabel");
var divId = "absoluteToolCont_" + grpId
if (!editor.config.showIconOnly) {
groupName.text(name);
} else {
var clsName = name.replace(/ /g, '');
var detachedDiv = $("#" + divId).detach();
$("#groupLabel_" + grpId).prepend(detachedDiv);
groupName.html("<div class='iconToolbar " + clsName
+ "'></div>");
var overFlowRObj = "#cke_" + editor.name + " .cke_inner "
+ ".cke_top";
$(overFlowRObj).addClass("cke_top_overflow");
}
}
function groupLabelElementDiv(grpId, className) {
var elementDiv = "<div id='groupLabel_" + grpId
+ "' class='groupLabel transitionType groupLabel_"
+ className + "'></div>";
return elementDiv;
}
function createSubGroup() {
var loopVar = 0;
var divEle = '<div class="subGrpLabel textGroupLabel">' + "Font"
+ '</div>';
/*
* for (var k = 0; k < editor.toolbar.length; k++) { if
* (editor.toolbar[k] != "/") { for (var l = 0; l <
* editor.toolbar[k].items.length; l++) { if
* (editor.toolbar[k].items[l].type == "separator") { //
* console.log("sep") // $(editor.toolbar[k].items[l]).text("name"); } } } }
*/
}
editor.on('destroy', function() {
/* alert(this.name) */
var undoName = "undoRedoCont" + editor.name;
$("#" + undoName).remove();
});
editor.on('instanceReady', function() {
// console.log(previewSeen);
$("#universalPreloader").addClass("displayNone");
createMainGroups();
createSubGroup();
focusEvent();
undoRedoButtonSeprator();
});
function undoRedoButtonSeprator() {
var undoRedoContEle = "<div class='urcEle' id='undoRedoCont"
+ editor.name + "'></div>";
$("#undoRedoContSetParent").append(undoRedoContEle);
var ele = $("#" + editor.ui.instances.Undo._.id).detach();
$("#undoRedoCont" + editor.name).append(ele);
$(ele).addClass("cke_button_75px");
ele = $("#" + editor.ui.instances.Redo._.id).detach();
$("#undoRedoCont" + editor.name).append(ele);
$(ele).addClass("cke_button_75px");
$("#undoRedoCont" + editor.name).addClass("displayNone");
}
function focusEvent() {
var editorObj = /* parent. */$("#cke_wordcount_" + editor.name);
editorObj.addClass("displayFlexRelative").addClass("displayNone")
.addClass("vertical-align-middle").addClass(" flexHCenter")
.css("width", "160px");
var undoRedoCont = /* parent. */$("#undoRedoCont" + editor.name);
undoRedoCont.addClass("displayNone");
editor.on('focus', function(e) {
onFoucs(e);
});
editor.on('blur', function(e) {
onBlur(e);
});
}
function onBlur(e) {
var editorObj = /* parent. */$("#cke_wordcount_" + e.editor.name);
editorObj.addClass("displayNone");
$("#undoRedoCont" + editor.name).addClass("displayNone");
$("#dummyUNDOREDO").removeClass("displayNone");
resetAllAbsolute();
/*
* if (e.editor.config.customInline) {
* $("#toolbarEditorInline").addClass("displayNone"); }
*/
}
function onFoucs(e) {
var editorObj = /* parent. */$("#cke_wordcount_" + e.editor.name)
editorObj.removeClass("displayNone");
$("#undoRedoCont" + editor.name).removeClass("displayNone");
$("#dummyUNDOREDO").addClass("displayNone");
/*
* if (e.editor.config.customInline) {
* $("#toolbarEditorInline").removeClass("displayNone"); }
*/
}
CKEDITOR.document.appendStyleSheet(CKEDITOR.plugins
.getPath('grouplabel')
+ 'css/style.css');
}
});

how to create dots in pagination or breadcrumb if they are too much in number

I want to create dots in breadcrumb if they exceeds some specific limit of numbers. I added script, to create breadcrumb but it's not working.
I am stuck where i have to add dots so that when bread crumb item exceeds it hides and create dots
function getBreadCrumb() {
if (window.ActiveTab != 'local') {
$('#fr-h-r-3 .breadcrumb.fr-breadcrumb').html('');
return false
}
/*alert(window.ActiveTab);
if(window.ActiveTab == 'fb'){
$('#fr-h-r-3 .breadcrumb.fr-breadcrumb').html('<li>Facebook-Images</li>');
return false;
}else if(window.ActiveTab == 'ig'){
$('#fr-h-r-3 .breadcrumb.fr-breadcrumb').html('<li>Instagram-Images</li>');
return false
}*/
var currentPath = b.opts.userFolderDefaultPath;
if (b.opts.imageManagerFolders.length > 0) {
currentPath = b.opts.userFolderDefaultPath + b.opts.imageManagerFolders.join('/') + '/';
}
var sArray = currentPath.split('/');
var fArray = currentPath.split('/');
fArray.pop();
fArray.shift();
sArray.shift();
sArray.shift();
sArray.shift();
sArray.pop();
var html = '<li><span class="fa fa-home"></span></li>';
/*console.log('sArray: '+sArray);
console.log('fArray: '+fArray);*/
function getPath(i) {
var hisPath = '';
for (var j = 2; j < (i + 3); j++) {
if (fArray[j] != 'undefined') {
hisPath += fArray[j] + '/';
}
}
return hisPath;
}
if (sArray.length > 6) {
as = 4;
al = (sArray.length - 3)
}
sts = false;
for (var i = 0; i < sArray.length; i++) {
if ((i + 1) != sArray.length) {
if (typeof as != 'undefined' && i == as) {
sts = true;
}
if (typeof al != 'undefined' && i == al) sts = false;
if (sts == false) {
html += '<li><a onClick="$(document).trigger(\'ImageManager.LoadBreadCrumbFolder\',[this]);" href="javascript:void(0);" data-name="' + sArray[i] + '" data-hist="' + getPath(i) + '" data-path="/' + fArray[0] + '/' + fArray[1] + '/' + getPath(i) + '">' + sArray[i] + '</a></li>';
}
} else {
html += '<li class="active">' + sArray[i] + '</li>';
}
//html += '<li class="active">'+sArray[i]+'</li>';
}
$('#fr-h-r-3 .breadcrumb.fr-breadcrumb').html(html);
}
Thank you for your efforts, i was working on this, i solved this by only adding this code into function.
if(typeof as != 'undefined' && i==as) { sts = true; html += '<li>...</li>'; }
where the line is
if (typeof as != 'undefined' && i == as) {
sts = true;
}
this script is generating a pagination you can see in script. and the final output is this.
simple pagination without dots.
checkttttNew-Folder-1New-Folder-1New-Folder-1
when exceeds 6 li then it creates dots. like this.
checkttttNew-Folder-1New-Folder-1...New-Folder-1htesttes2

jQuery use dynamically created ID

I am trying to use dynamically created IDs in javascript function, but it's not working. I thought that prepending # to string id should work, but it's not.
Code:
var IterateCheckedDatesAndUncheckWithSameValue = function (elementNumber) {
idCheckBoxToCompare = "CMP_KD1_tcDE_tctpDNDR_chkDNDRDay" + elementNumber.toString();
if ($("'#" + idCheckBoxToCompare + "'").prop('checked') === false) {
return;
}
textBoxID = "CMP_KD1_tcDE_tctpDNDR_txtDNDRDay" + elementNumber.toString();
textBoxValue = $("'#" + textBoxID + "'").val();
for (i = 1; i < 8; i++) {
if (i !== elementNumber) {
idCheckBox = "CMP_KD1_tcDE_tctpDNDR_chkDNDRDay" + i.toString();
idInputBox = "CMP_KD1_tcDE_tctpDNDR_txtDNDRDay" + i.toString();
inputBoxValue = $("'#" + idInputBox + "'").val();
if ($("'#" + idCheckBox + "'").prop('checked') === true) {
if (inputBoxValue === textBoxValue) {
$("'#" + idCheckBox + "'").prop('checked', false);
}
}
}
}
}
I've tried to build same id as this is:
'#testid'
so usage would be:
$('#testid')
But it's not working. How to use properly dynamically created IDs?
Your code is look complicated with too many " and '. Also Javascript can concat string and number by just use +. No need to convert it to string first. So, I updated it to make it more readable.
Try this
var IterateCheckedDatesAndUncheckWithSameValue = function(elementNumber) {
idCheckBoxToCompare = "CMP_KD1_tcDE_tctpDNDR_chkDNDRDay" + elementNumber;
if ($('#' + idCheckBoxToCompare).prop('checked') === false) {
return;
}
textBoxID = "CMP_KD1_tcDE_tctpDNDR_txtDNDRDay" + elementNumber;
textBoxValue = $('#' + textBoxID).val();
for (i = 1; i < 8; i++) {
if (i !== elementNumber) {
idCheckBox = "CMP_KD1_tcDE_tctpDNDR_chkDNDRDay" + i;
idInputBox = "CMP_KD1_tcDE_tctpDNDR_txtDNDRDay" + i;
inputBoxValue = $('#' + idInputBox).val();
if ($('#' + idCheckBox).prop('checked') === true) {
if (inputBoxValue === textBoxValue) {
$('#' + idCheckBox).prop('checked', false);
}
}
console.log('#' + idCheckBox); //print here just to see the id results
}
}
}
ID in html can be only one element per page. So please make sure that the ID you generate from this method not match with other.
Jquery selector can read String variable.
So you can just do var id = "#test". Then put it like this $(id).
Or
var id = "test"; then $("#"+test).
Use this,
var IterateCheckedDatesAndUncheckWithSameValue = function (elementNumber) {
idCheckBoxToCompare = "CMP_KD1_tcDE_tctpDNDR_chkDNDRDay" + elementNumber.toString();
if ($("#" + idCheckBoxToCompare).prop('checked') === false) {
return;
}
textBoxID = "CMP_KD1_tcDE_tctpDNDR_txtDNDRDay" + elementNumber.toString();
textBoxValue = $("#" + textBoxID).val();
for (i = 1; i < 8; i++) {
if (i !== elementNumber) {
idCheckBox = "CMP_KD1_tcDE_tctpDNDR_chkDNDRDay" + i.toString();
idInputBox = "CMP_KD1_tcDE_tctpDNDR_txtDNDRDay" + i.toString();
inputBoxValue = $("#" + idInputBox).val();
if ($("#" + idCheckBox).prop('checked') === true) {
if (inputBoxValue === textBoxValue) {
$("#" + idCheckBox).prop('checked', false);
}
}
}
}
}
I face the same problem using Jquery .Try $(document).getElementbyId('myid'). Hope help.
Edit
Change :
$("#" + idCheckBoxToCompare) by $(document).getElementbyId(idCheckBoxToCompare)

Functions being exponentially repeated in my js file

I'm running a site using Node, Express and MongoDB. I generate containers after an ajax call to get the data to fill them with, and each of the containers has a button which makes another ajax call specific to a recipe it's getting detailed information on. The first Time I do this it works perfectly, but if i get details for a 2nd one it executes the function 3 times instead of one, and if I do it for a 3rd container it runs it 9 times and so on. I'm fairly new with Jquery and perhaps It's a misunderstanding of how the events work. the problems also occurs with the saveRecipe function.
global.js
$(document).ajaxComplete(function(){
$('.details').popover({"trigger": "manual", "html":"true"});
$('.details').click(get_data_for_popover_and_display);
$('.save-favorite').on('click', saveRecipe );
});
(function ($) {
$('#search').on('click', function (e) {
// remove resultset if this has already been run
$('.recipes').empty();
var recipeName = document.getElementById('recipeName').value;
var recipeNameString = '&q=' + recipeName;
var ingredientHtml = '&allowedIngredient[]=';
var ingredientsArray = document.getElementById('ingredients').value.split(",");
var ingredientsString = '';
if (ingredientsArray[0] !== ""){
for (i = 0; i < ingredientsArray.length; i++){
ingredientsArray[i] = ingredientHtml + ingredientsArray[i].trim();
}
for (i = 0; i < ingredientsArray.length; i++){
ingredientsString += ingredientsArray[i];
}
}
var excludedIngredientHtml = '&excludedIngredient[]=';
var excludedIngredientsArray = document.getElementById('ingredientsExclude').value.split(",");
var excludedIngredientsString = '';
if (excludedIngredientsArray[0] !== ""){
for (i = 0; i < excludedIngredientsArray.length; i++){
excludedIngredientsArray[i] = excludedIngredientHtml + excludedIngredientsArray[i].trim();
}
for (i = 0; i < excludedIngredientsArray.length; i++){
excludedIngredientsString += excludedIngredientsArray[i];
}
}
var dietHtml = '';
if(document.getElementById('lacto-veg').checked){
dietHtml += '&allowedDiet[]=388^Lacto vegetarian';
}
if(document.getElementById('ovo-veg').checked){
dietHtml += '&allowedDiet[]=389^Ovo vegetarian';
}
if(document.getElementById('paleo').checked){
dietHtml += '&allowedDiet[]=403^Paleo';
}
if(document.getElementById('pescetarian').checked){
dietHtml += '&allowedDiet[]=390^Pescetarian';
}
if(document.getElementById('vegan').checked){
dietHtml += '&allowedDiet[]=386^vegan';
}
if(document.getElementById('vegetarian').checked){
dietHtml += '&allowedDiet[]=387^Lacto-ovo vegetarian';
}
var allergyHtml = '';
if(document.getElementById('dairy-free').checked){
allergyHtml += '&allowedAllergy[]=396^Dairy-Free';
}
if(document.getElementById('egg-free').checked){
allergyHtml += '&allowedAllergy[]=397^Egg-Free';
}
if(document.getElementById('gluten-free').checked){
allergyHtml += '&allowedAllergy[]=393^gluten-Free';
}
if(document.getElementById('peanut-free').checked){
allergyHtml += '&allowedAllergy[]=394^Peanut-Free';
}
if(document.getElementById('seafood-free').checked){
allergyHtml += '&allowedAllergy[]=398^Seafood-Free';
}
if(document.getElementById('seseme-free').checked){
allergyHtml += '&allowedAllergy[]=399^Seseme-Free';
}
if(document.getElementById('sulfite-free').checked){
allergyHtml += '&allowedAllergy[]=401^Sulfite-Free';
}
if(document.getElementById('tree-nut-free').checked){
allergyHtml += '&allowedAllergy[]=395^Tree Nut-Free';
}
if(document.getElementById('wheat-free').checked){
allergyHtml += '&allowedAllergy[]=392^Wheat-Free';
}
var apiHtml = 'http://api.yummly.com/v1/api/recipes?_app_id=&_app_key=' +recipeNameString;
if (ingredientsString){
apiHtml += ingredientsString;
}
if (excludedIngredientsString){
apiHtml += excludedIngredientsString;
}
if (dietHtml){
apiHtml += dietHtml;
}
if (allergyHtml){
apiHtml += allergyHtml;
}
apiHtml += '&requirePictures=true';
apiHtml = apiHtml.replace(' ', '%20');
$.getJSON(apiHtml, function (json) {
var recipes = [],
$recipes;
$.each(json, function (key, val) {
if (key === "matches"){
for (i = 0; i < val.length ; i++) {
if (i%3 === 0){
recipes.push('<div class="row">');
}
recipes.push('<div class="col-sm-6 col-md-4">');
recipes.push('<div class="thumbnail">' + '<img src="'+ val[i].imageUrlsBySize[90] + '" alt="' + val[i].recipeName + '" data-holder-rendered="true" style="height: 300px; width: 100%; display: block;"/>');
recipes.push('<div class="caption">' + '<h3 class="caption-text">' + val[i].recipeName + '</h3>');
recipes.push('<p class="caption-text">' + val[i].sourceDisplayName + '</p>');
recipes.push('<p><button type="button" class="btn btn-primary details" data-toggle="popover" title="' + val[i].recipeName + '" value="' + val[i].id + '"> Details </button> ');
recipes.push('<button type="button" class="btn btn-primary save-favorite" method="post" action="saveFavorite" value="' + val[i].id + '"> Favorite </button></p>');
recipes.push('</div></div></div>');
if ((i+1)%3 === 0){
recipes.push('</div>');
}
}
}
});
if (recipes.length < 1) {
recipes.push('<p>No results for parameters, try again!</p>');
}
$recipes = $('<div />').appendTo('.recipes');
$recipes.append(recipes.join(''));
});
e.preventDefault();
});
}(jQuery));
get_data_for_popover_and_display = function() {
var el = $(this);
if(el.hasClass('recipe-loaded')){
}
else {
var _data = $(this).attr('alt');
var recipeUrl = 'http://api.yummly.com/v1/api/recipe/' + this.value + '?_app_id=&_app_key=';
var recipeHtml = '';
var ingredientsHtml = '';
var nutritionHtml = '';
var ratingHtml = '';
var servingsHtml = '';
var sourceHtml = '';
$.getJSON(recipeUrl, function (json) {
$.each(json, function (key, val) {
if (key === "ingredientLines"){
ingredientsHtml = '<h4>Ingredients:</h4><ul>';
for (i = 0; i < val.length ; i++){
ingredientsHtml += ('<li>' + val[i] + '</li>');
}
ingredientsHtml += '</ul>';
}
if (key === "nutritionEstimates"){
if(val.length > 0){
nutritionHtml = 'Cal. per Serving: ' + val[0].value + '<br>';
}
}
if (key === "rating"){
ratingHtml += 'Rating: ' + val + '</p>';
}
if (key === "numberOfServings"){
servingsHtml += '<p>Servings: ' + val + '<br>';
}
if (key === "source"){
sourceHtml += '<p><a type="button" class="btn btn-primary details" href="'+ val.sourceRecipeUrl +'" >Source</a>';
}
})
recipeHtml += ingredientsHtml;
recipeHtml += servingsHtml;
recipeHtml += nutritionHtml;
recipeHtml += ratingHtml;
recipeHtml += sourceHtml;
el.attr('data-content', recipeHtml).success(el.popover('toggle'));
el.addClass('recipe-loaded');
});
}
};
function saveRecipe(){
var recipeUrl = 'http://api.yummly.com/v1/api/recipe/' + this.value + '?_app_id=3e5b7dbe&_app_key=1d681685a57dac07e6df0b1c0df38de6';
var json = $.getJSON(recipeUrl, function (data){
console.log(JSON.stringify(data));
$.ajax({
type: 'POST',
data: data,
url: '/saverecipe',
dataType: 'JSON'
});
});
};
This line:
$('.details').click(get_data_for_popover_and_display);
hooks up a new event handler on all .detail elements that will call get_data_for_popover_and_display, even if that element already has an event handler calling get_data_for_popover_and_display. Same with:
$('.save-favorite').on('click', saveRecipe );
So since get_data_for_popover_and_display (at least) does another ajax call, which will add another handler, you'll get increasing numbers of handlers over time.
It's exactly like this:
function clickHandler() {
console.log(+new Date(), "Clicked");
clickComplete();
}
function clickComplete() {
$("#btn").on("click", clickHandler);
}
clickComplete();
<input type="button" id="btn" value="Click Me">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
So: Only add a handler if you haven't already done so. Perhaps keep track in jQuery's data store:
function clickHandler() {
console.log(+new Date(), "Clicked");
clickComplete();
}
function clickComplete() {
$("#btn").filter(function() {
return !$(this).data("hasClick");
})
.on("click", clickHandler)
.data("hasClick", true);
}
clickComplete();
<input type="button" id="btn" value="Click Me">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

Get text and id from an li element on click with pure JS

I've been stuck with this for several days and I can't solve it.
I've done it with jQuery with no problem, but I need it in pure JS.
This is how my list is generated.
function get_friends(items){
if(items != undefined){
if (items.length != 0){
var html_friends_list = "";
for(var count = 0; count < items.length; count++){
if(items[count].subscription == "both"){
var display_name = Strophe.getNodeFromJid(items[count].jid);
html_friends_list = html_friends_list + "<li style='font-size:19px' id='open_chat-" + items[count].jid + "'>" + "<a href='chat-js/index.html'>" + display_name + "<span class='block-list-label' id='" + items[count].jid + "_unread_messages" + "'>0</span><span class='block-list-label' id='" + items[count].jid + "_change_status" + "'></span></a></li>";
}
}
document.getElementById("friends-list").innerHTML = html_friends_list;
As a said I want to save the value of the text and the id of any li element clicked.
Regards
you haven't specified whether this is for a specific list or just any li on your page. The below will log the id and innerHTML components of any li on the page. Perhaps you may need to update the querySelector for your particular use case.
var list = document.querySelectorAll('li');
Array.prototype.slice.call(list).forEach(function(listItem){
listItem.addEventListener('click', function(e){
console.log(this.id);
console.log(this.innerHTML);
});
});
Here's a JSFiddle which I think demonstrates what you are trying to achieve.
Jsfiddle
Combination of james' answer and working example.
function get_friends(items) {
if (items != undefined) {
if (items.length != 0) {
var html_friends_list = "<ul>";
for (var count = 0; count < items.length; count++) {
if (items[count].subscription == "both") {
html_friends_list = html_friends_list + "<li id='open_chat-" + items[count].jid + "'>"+ items[count].display_name +"</li>";
}
}
html_friends_list = html_friends_list + '</ul>'
document.getElementById("friends-list").innerHTML = html_friends_list;
}
}
}
Note: you should trigger prototype after your dom element created.

Categories

Resources