Jquery append() isn't working - javascript

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.

Related

Why jQuery append() removes words after first blank space in string

I'm trying to dynamically generate a form after an ajax request. Below is the relevant code sample :
for (var i in response.responseJSON[0].fields) {
var field = response.responseJSON[0].fields[i];
$('#properties_form').append('<label for=' + i + '>' + i + '</label>' +
'<input id=' + i + ' value=' + field + '>');
}
My problem is that, when var i and var field are strings with blank spaces like "Hello world", my label and inputs will be like <label id="Hello" world=""> and <input value="Hello" world="">. However, the label text will be displayed correctly i.e. <label>Hello world</label>.
I've no idea what kind of sorcery that is, but I'll be very grateful for any help. Thanks in advance.
There's a much more robust way of doing this.
for (var i in response.responseJSON[0].fields) {
var field = response.responseJSON[0].fields[i];
$('#properties_form')
.append($('<label>').attr('for', i).text(i))
.append($('<input>').attr('id', i).val(field));
}
You won't have to worry about the content of the strings as jQuery and the DOM will handle it for you. Not to mention this is much easier to read.
Use " to enclose the attributes.
$('#properties_form')
.append('<label for="' + i + '">' + i + '</label>' +
'<input id="' + i + '" value="' + field + '">');
EDIT
This will break for the cases where the value for i is something like This "works". Best solution is to append as jQuery or JS objects rather than using HTML string just like Daniel's answer.
Following snippet contains the correct fix for this. Updated based on the answer from Daniel.
i = 'Hello "World"';
field = 'Hello "World"s';
$('#properties_form')
.append($('<label>').attr('for', i).text(i))
.append($('<input>').attr('id', i).val(field));
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div id="properties_form"></div>

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

How to append free text elements from array to DOM

I'm trying to append information to my page from two different JavaScript arrays. It looks like this.
var i = 0;
var videoArr=["big long array"];
var descriptArr=["big long array"];
function appendVideo(i) {
var url = "http://i.ytimg.com/vi/" + videoArr[i] + "/mqdefault.jpg";
$("#history").append("<img src=\"" + url + "\" width=\"120\" height=\"68\" />**NEED TO PRINT descriptArr[i] HERE**<br />");
}
function loadHistory() {
while (i < '.$length.') {
appendVideo(i);
i = i + 1;
}
}
So the above code is appending all the elements from the videoArr no problem. The problem is the descriptArr is full of free text descriptions that I need to print beside each videoArr element. What's he best way to do this? I presume it's not document.write(descriptArr[i])...
Try this, as long as you are sure that descriptArr does not contain any HTML literals.
$("#history").append("<img src=\"" + url + "\" width=\"120\" height=\"68\" />" + descriptArr[i] + "<br />");
Not the best way, but just try something like this
$("#history").append("<img src=\"" + url + "\" width=\"120\" height=\"68\" />" + descriptArr[i] + "<br />");
Ive used this for achieving the same thing:
aDate = (document.getElementById("datepicker").value);
$('.daysContain').find('div').eq(dateArray.length-1).prepend(aDate + '<br>');

WHy Doesnt This Javascript Function Work

What I'm trying to do here is make one function that does all the functionality for a custom select element. So I made a function that accepts three parameters which are defined in the function itself (see code below for more detail). I'm trying to accomplish the following: I want the parameters to be the IDs of the various elements (the wrapper div for example), and I want those parameters to be dropped in the function. My Code is below. Thanks so much
function createList(ParentDivID,SelectMenuID,ListMenuID) {
$('#' + ParentDivID + "'");
$('#' + SelectMenuID + "'");
$('#' + ListMenuID + "'");
var options = $("#" + SelectMenuID +'"' ).find("option");
$(options).each(function(){
$(ul).append('<li>' +
$(this).text() + '<span class="value">' +
$(this).val() + '</span></li>');
});
var ul = '<ul id="' + ListMenuID + "></ul>";
$('#' + ParentDivID + "'").append(ul).end().children('#' + ListMenuID + "'").hide().click(function(){$(ul).slideToggle();});
$("#" + SelectMenuID + '"').hide();
}
createList(fancySelectLarge,selectWalkerType,walkerTypeLi);
At a guess, it is probably because your ids don't end in quote characters (which aren't allowed in ids in HTML 4), but you are appending them to the strings you are searching for with jQuery.
You only need to do your selectors like this
$('#' + ParentDivID);
Also you need to stop interchanging 's and "s because it is causing you to miss some closing quotes
function createList(ParentDivID,SelectMenuID,ListMenuID) {
var options = $('#' + SelectMenuID).find('option');
$(options).each(function(){
$(ul).append('<li>' +
$(this).text() + '<span class="value">' +
$(this).val() + '</span></li>');
});
var ul = '<ul id="' + ListMenuID + '"></ul>';
$('#' + ParentDivID).append(ul).end().children('#' + ListMenuID).hide().click(function(){$(ul).slideToggle();});
$('#' + SelectMenuID).hide();
}
createList(fancySelectLarge,selectWalkerType,walkerTypeLi); `
You are messing up all of your string concatenations like:
$('#' + ParentDivID + "'"); should be $('#' + ParentDivID);
It's generally a bit of a mess but I've tried to fix as much as possible.
function createList(ParentDivID,SelectMenuID,ListMenuID) {
var options = $("#" + SelectMenuID).find("option");
var ul = $('<ul>', {id: ListMenuID});
$(options).each(function(){
ul.append('<li>' +
$(this).text() + '<span class="value">' +
$(this).val() + '</span></li>');
});
$('#' + ParentDivID)
.append(ul)
.end()
.children('#' + ListMenuID)
.hide()
.click(function() { ul.slideToggle(); });
$("#" + SelectMenuID).hide();
}
When you call the function, are the three parameters already variables assigned elsewhere in your code? If not, and the are actually the string id attributes, you need to enclose them in quotes.
createList("fancySelectLarge", "selectWalkerType", "walkerTypeLi");
Note: See other valuable responses about the incorrect quoting in $('#' + ParentDivID + "'");
$(ul) is undefined when execution reaches it, because var ul is only declared a few lines later on. You will also need to use document.body.createElement('ul') instead of putting '<ul ...>' in a string.
Also, the lines $('#' + ParentDivID + "'"); don't do anything.
You need to define ul before using it. Also, define it as $('<ul.../>') not just '<ul.../>', so that you can create a jQuery element from that definition.
and you want also try to create the dom element like this
$('<span class="value">') instead of a string value '<span class="value">'.

JQuery UnBind Works, Attempt to "re" bind does not

I'm working my way through a JQuery Solution and for the most part it works but I"m stumped on seemingly a small detail I know I'm overlooking. Heck, maybe my implementation/approach needs to be reconsidered.
Here's the flow of what works.
1. Click an anchor that adds to a table.
2. Add CSS Class.
3. Disable (Unbind) click on after preappend().
4. From the table of dynamically added record remove table based on ID.
5. delete class that was added in step 2.
6. Bind 'click'
However, although I can bind the click and alert on it. The expected functionality does not allow me to step through the above process again.
The code in question:
HTML SAMPLE:
link that starts the process:
table that holds new records after click of link
<table id="carrier-table"><tbody></tbody></table>
JQUERY and Custom Javascript Function
<script type="text/javascript" id="removeCarrier">
function removeCarrierFromList(obj) {
var i = obj.parentNode.parentNode.rowIndex;
document.getElementById('carrier-table').deleteRow(i);
$('a#' + obj.id).removeClass('delete-carrier-company');
//alert(obj.id); //.hasClass('add-carrier-company').tostring() ); //
$('a#' + obj.id).bind('click', function() {
//alert('User clicked on ' + obj.id);
});
}
</script>
<script type="text/javascript" id="carrierListJS">
$(function() {
// Link
// This adds a carrier to a list
$('.add-carrier-company').click(
function() {
var target = $(this).attr("id");
alert(target);
$("#carrier-table").prepend("<tr id='carrierRow_" + target + "'>" +
"<td><a href='#' id='" + target + "' class='delete' onclick='removeCarrierFromList(this)'> </a></td>" +
"<td class='carrier-list-text'>" + target + " " + $("#name_" + target).val() + "</td>" +
"</tr>");
return false;
});
$('.add-carrier-company').click(
function() { $(this).addClass('delete-carrier-company').unbind('click'); }
);
});
</script>
There were a few issues I noticed with the code. For one thing, as #RussellUresti mentioned, you create two tags with the same ID. For another thing, if you're using ID's in a selector in jQuery, don't include the tag name, just use the id (ie. use $('#id') not $('a#id')) it will be faster (it won't break your code though).
I have created a jsfiddle to answer your question (though I rewrote most of it). :) I think it's what you're looking for.
Here's the code:
Test HTML
aa
bb
cc
10002
10003
<table id="carrier-table" style="border:1px solid #000"><tbody></tbody></table>
JavaScript
function addCarrier() {
var target = $(this).attr("id");
$("#carrier-table").prepend("<tr id='carrierRow_" + target + "'>" + "<td><a href='#' id='a" + target + "' class='delete'> </a></td>" + "<td class='carrier-list-text'>" + target + " " + $("#name_" + target).val() + "</td>" + "</tr>");
$('#a' + target).click(removeCarrierFromList);
$(this).addClass('delete-carrier-company').unbind('click');
return false;
}
function removeCarrierFromList() {
var $this = $(this);
var id = $this.attr('id').replace("a","");
$this.closest('tr').remove();
$('#' + id).removeClass('delete-carrier-company').click(addCarrier);
}
$(function() {
// Link
// This adds a carrier to a list
$('.add-carrier-company').click(addCarrier);
});

Categories

Resources