selection error in jquery with dynamic elements - javascript

First of all thanks for reading. I have a problem with jQuery. I am trying to get some data with AJAX and put the result on page with dynamically created div. This works perfect. The problem occurs when I try to select the created div and do something with it
$('.myNewDiv').css('border', '2px solid #000080');
It gives me error in jQuery library
In Chrome debugger it is "Uncaught TypeError: Cannot read property 'slice' of undefined" on line 2234
And in Firebug under firefox "Array.prototype is undefined Line 3324"
I have no idea what is the problem so i'd be grateful for any information
The whole function code:
function AddNextDiv(number) {
var url2 = '<%= ResolveUrl("~/Translate/GetLineDetails") %>';
$.getJSON(url2, { textLineID: LinesIDs[number], TranslatedSubsID: '<%= Html.Encode(Model.OutputSubs.SubsID) %>' }, function (result) {
if (result == "Already in Database") return false;
var myObject1 = JSON.parse(result);
$("#MainField").append("<div class=\"TextLineDiv\">This is line number " + myObject1.LineNumber + " of 423<br/>" + myObject1.TextValue + "<br/><input id=\"TranslationBox" + myObject1.LineNumber + "\" class=\"translationTextBox\" type=\"text\" size=\"20\" /><br/><div id=\"CheckBoxDiv" + myObject1.LineNumber + "\"><input name=\"" + myObject1.LineNumber + "\" class=\"addCheckBox\" onchange=\"HideDiv(this)\" type=\"checkbox\" /><br/><div class=\"NumberDiv\" title=\"" + myObject1.LineNumber + "\" onmouseover=\"CallRefresh(this)\" > This line was translated <div id=\"Translated" + myObject1.LineNumber + "\">" + myObject1.TimesTranslated + "</div> times.</div><br/><br/></div></div>");
$("div#MainField div.TextLineDiv").css('border', '2px solid #000080');
return true;
});
}
`

You can't select things that aren't added to the document yet. If you can restructure your code so that the div can be caught into a variable it would be easy. Otherwise you need to do something like add it to a hidden element then select it. (yuk!)
I suggest using jQuery's DOM tools rather than building everything as a big string of html.

Related

HTML Element not being inserted

I'm working on a .NET Core project for my company where work orders are loaded from our SQL database using Entity Framework, filtered and then displayed as markers on a map through Google Maps API for our installers.
We have two types of filters: one that gets included in an Ajax POST, and one that filters locally to decrease load times and performance issues. What I'm trying to do is load the local filter items (lists that are included in the response when calling the initial Ajax POST). If the list of filter items exceeds 5 items, I want them to collapse to only 5 items and insert an anchor which expands (utilizes jQuery's toggle()) showing the rest of the items in that list.
This is the excerpt from the JavaScript function which takes care of that:
filterItems
.forEach((filterItem, i) => {
var localItem = '<label class="' + selectorContainerClass
+ ' selectorContainer" id="' + selectorContainerIdPrefix + filterItem.key
+ '"><input id="' + convertValToEng(filterItem.value)
+ '" type = "checkbox" class="filled-in navy" name="' + inputName
+ '" value="' + filterItem.key
+ '" onchange="localFilter(this, this.value)" /><span class="selector-value">'
+ filterItem.value
+ '</span> <span id="' + paramName + 'Cnt__' + filterItem.key
+ '" class="selector-count"></span></label ><br />';
document.querySelector("#" + colId).insertAdjacentHTML('beforeend', localItem);
if (i >= 5) {
$("#" + colId + " #" + selectorContainerIdPrefix + filterItem.key).addClass("collapse");
$("#" + colId + " #" + selectorContainerIdPrefix + filterItem.key).toggle(100);
$("#" + colId + " #" + selectorContainerIdPrefix + filterItem.key + " + br").toggle(100);
}
});
if (filterItems.length > 5) {
//TODO: Fix the bug here; the .filter-collapse element is not being inserted under local installers.
var newEl = '<a class="filter-collapse" onclick="toggleFilterExpand(false, this)";><i class="material-icons">expand_more</i></a>';
document.getElementById(colId).insertAdjacentHTML('beforeend', newEl);
}
I should be getting a newEl inserted under the "Installer" column (8 installers, 3 of them not being displayed), but I'm not. I've tried jQuery's after() and insertAfter() methods, but neither of those worked. newEl is being generated for the "Area" column, as it should, but for the "Installer" column it's not.
I've also tried inserting the element manually through the console window with the exact same code and it works.
Would appreciate some help with this as I feel lost regarding this issue.
Thanks.
It turned out to be a stupid mistake on my end where I was removing the element newEl from the all the other filter lists before inserting a new one to the currently iterated one.

How do I Get Text from Dynamically created element in JavaScript

I am dynamically creating Div Text in JS and was wondering how I access the various text upon click.
Here is what I have tried so far;
My Dynamically created div
function Message(Side, message) {
var divChat = '<div class="direct-chat-msg ' + Side + '">' +
'<div id="myDiv" class="direct-chat-text">' + message + '</div>' +
'<div id="accountMenu">' +
'<li onclick = "getMessage(' + message + ')" id="replyDiv">Reply</li>' +
'<li>Preferences</li>' +
'</ul>' +
'</div></div>';
$('#divChatWindow').append(divChat);
}
JS when the li is clicked on.
function getMessage(str) {
alert(str);
}
The error I am getting is:
Uncaught ReferenceError: *whaeverthemessageis* is not defined
at HTMLLIElement.onclick
What is the best solution to solve this problem?
Thanks =)
You have malformed html using single and double quotes. The message is being treated as a variable, not a string, hence the undefined error.
replace:
'<li onclick = "getMessage(' + message + ')" id="replyDiv">Reply</li>' +
with this:
'<li onclick = "getMessage(\'' + message + '\')" id="replyDiv">Reply</li>' +
I'm not exactly sure what the problem is, but here is a working Playcode

Jquery Javascript best way to check elements done appending

I have a list of elements that are dynamically appended after an Ajax call. I am using a plugin that creates a lightbox click event for the anchors dynamically appended. It works fine except sometimes it says that the title is undefined. I realize this is because the plugin gets initiated before the title attribute is completely done appending to the DOM. I know of several ways to do this, but what is the BEST way to check that all these elements are completely appended?
Ajax call is already made and data parsed with this function (colorbox title is the one that evaluates to 'undefined' for only some):
function pageImages(images,_q){
for(var i = 0; i < images.count; i++){
$('#pageImages').append('<div class="pageImageItem"><a href="' + images.data[i]._clickurl + '" title= "' + images.data[i]._title + '">\
<img src="' + images.data[i]._thumbnailUrl + '" alt= "' + images.data[i]._title + '"/>\
</a><div class="hoverInfo"><h2>' + images.data[i]._title + '</h2><p>' + limitCharacters(images.data[i]._clickurl,40) + '</p></div></div>');
}
$(".pageImageItem a").colorbox({maxWidth:'95%', maxHeight:'95%', title: function(){
var url = $(this).attr('href'),
title = $(this).attr('title');
console.log(title);
return '<h2>' + title + '</h2>' + limitCharacters(url,40) + '';
}});
}
And here is a picture of what is happening (anchor highlighted is the element that clearly has a title attribute but is showing undefined in lightbox):
You can wrap the jQuery element find block in a timeout without timevalue. The timeout will wait for all javascript to be finished with all processes. Example:
window.setTimeout(function() {
$(".pageImageItem a").colorbox({maxWidth:'95%', maxHeight:'95%', title: function(){
var url = $(this).attr('href'),
title = $(this).attr('title');
console.log(title);
return '<h2>' + title + '</h2>' + limitCharacters(url,40) + '';
}});
});

attempting to split string dynamically keep getting error?

I'm attempting to split a string I'm passing into
$("#groupUL").append("<li>" + "<h2>About Item:</h2> " + response.data[i].message + "<br /> " + "<h2>Posted By:</h2> <a href='#' onclick='splitName('" + response.data[i].from.name + "');'>" + response.data[i].from.name + "</a>" + "<br />");
Seems to be passing me the error
SyntaxError: syntax error
splitName(
Not sure how that's wrong...Here is the splitname function if that helps
function splitName(txt){
var myString = txt;
var mySplitResult = myString.split(" ");
console.log("The first element is " + mySplitResult[0]);
console.log("<br /> The second element is " + mySplitResult[1]);
console.log("<br /> The third element is " + mySplitResult[2]);
};
It's too hard to get it right when you put quotes in quotes in quotes and you try to escape it right. You got it wrong.
A solution is to make it in small parts :
var action = "splitName('" + response.data[i].from.name + "');";
$("#groupUL").append("<li>" + "<h2>About ... onclick=\""+action+"\">...");
But the best solution would be to follow best practice, that is not inline the javascript but use jQuery's binding function :
$("#groupUL").append("... <a id=myid ...");
$("#myid").click(function(){ splitName(response.data[i].from.name) });
I think the only problem with your code is with your readability issue. So I would suggest please improve it. Lets have a look at it. My code example # JSbin.
Here is the code :- (which i think is better)
var response = {
data : {
message: 'Cleaning code',
from: {
name: 'Clean Code works'
}
}
};
var li = $('<li>'); //Create empty li (Not Appending to DOM now due to performance issues)
$('<h2>').html('About Item:' + response.data.message + '<br />').appendTo(li);
$('<h2>').html('Posted By:').appendTo(li);
$('<a>').attr('href', '#')
.html(response.data.from.name)
.appendTo(li)
.click(function() {
splitName(response.data.from.name);
});
$('<br>').appendTo(li);
// Append li to ul (Final operation to DOM)
li.appendTo('#groupUL');
function splitName(txt){
var myString = txt;
var mySplitResult = myString.split(" ");
console.log("The first element is " + mySplitResult[0]);
console.log("The second element is " + mySplitResult[1]);
console.log("The third element is " + mySplitResult[2]);
}

Jquery append() isn't working

I have this <ul>
<ul id="select_opts" class="bullet-list" style="margin-left:15px;"></ul>
This javascript code which is meant to go throug a JSON object and add the options
to the UL:
$.each(q.opts, function(i,o)
{
var str='';
str+="<li id='li_" + i + "'><input type='text' id='opt_" + i + "' value='" + o.option + "'>";
str+=" (<a href='javascript:delOpt(" + i + ");'>Delete</a>) </li>";
$("#select_opts").append(str);
});
If I do console.log() I can see that the looping is working. If I do:
console.log($("#select_opts").html());
It shows the HTML being updated as expected. However in the browser window, it shows the
UL as empty!
What am I doing wrong?
$("select_opts").append(str);
should be
$("#select_opts").append(str);
you're referring to object by id so you missed #
$.each(q.opts, function(i,o)
{
var str='';
str+="<li id='li_" + i + "'><input type='text' id='opt_" + i + "' value='" + o.option + "'>";
str+=" (<a href='javascript:delOpt(" + i + ");'>Delete</a>) </li>";
$("#select_opts").append(str);
// ^
}
I can't really see what's wrong, but try this instead, just to see if it works...
$(str).appendTo("#select_opts");
Both should work.
Is this a typo?:
$("select_opts").append(str);
Did you mean?:
$("#select_opts").append(str);
UPDATED:
Try this:
$.each(q.opts, function(i, o) {
var li = $('<li>').attr('id', 'li_' + i);
var in = $('<input>').attr('type', 'text').attr('id', 'opt_' + i).val(o.option);
var aa = $('<a>').attr('href', 'javascript:delOpt(' + i + ');').text('Delete');
li.append(in).append(aa)
$("#select_opts").append(li);
});
The tag Input should be closed - if don't, when using not valid html in append() on Internet Explorer, the div is not put into DOM tree, so you cannot access it with jQuery later.
I'd imagine input needs to be properly self-closed.
I found the bug, another part of the code was emptying the <ul> when i clicked a certain button.

Categories

Resources