Javascript/JQuery Dynamic UL Troubles - javascript

I have been working on a problem adding dynamic UL and LI's to a webpage through javascript and jQuery and am stumped.
I almost have a solution but it's not adding the styling and it is not putting each UL on a separate line. I have a feeling that the tags I am creating are not closing but I'm not sure.
My end goal is to have each JSON line as a separate UL and showing on a separate line, with the first name + last name + phone number as the list items of each UL and displaying like a table (without using a table). No inline styles and no HTML markup other than whatever is added dynamically through Javascript.
I was given the following code as a starting point but my solution has definitely veered a little off course. I have searched for hours and so far you can see my best attempt at the jsfiddle link below. Any help is greatly appreciated.
function showContacts(data){
var markup = "";
$("body").html(markup);
};
$(document).ready(function myFunction() {
var jsonText = '[ {"firstname":"Bill","lastname":"Gates","phone":"123-456-7891"}, {"firstname":"Steve","lastname":"Jobs","phone":"198-765-4321"}, {"firstname":"Kevin","lastname":"Spencer","phone":"007-008-0099"}, {"firstname":"David","lastname":"Zimmerman","phone":"800-256-6321"}, {"firstname":"Bert","lastname":"Ernie","phone":"127-624-1138"}, {"firstname":"Guy","lastname":"Lafleur","phone":"806-797-4213"} ]';
showContacts(jsonText);
});
https://jsfiddle.net/bkweLctq/embedded/result/

You just missed element creation.
Your odd & even class style also needs to be changed.
Updated js
function showContacts(data) {
var markup = "";
var jo = $.parseJSON(data);
console.log(jo);
var $body = $('body');
var _html = '';
for(var i = 0; i<jo.length; i++){
if((i+1)%2 == 0 ){
_html += '<ul class="even">';
}else {
_html += '<ul class="odd">';
}
var _index = 0;
$.each(jo[i], function(k,n) {
if((_index+1)%2 == 0 ){
_html += '<li class="even"> '+ n +' </li>'
}else {
_html += '<li class="odd"> '+ n +' </li>'
}
_index++;
});
_html += '</ul>';
}
$body.html(_html);
};
$(document).ready(function myFunction() {
var jsonText = '[ {"firstname":"Bill","lastname":"Gates","phone":"123-456-7891"}, {"firstname":"Steve","lastname":"Jobs","phone":"198-765-4321"}, {"firstname":"Kevin","lastname":"Spencer","phone":"007-008-0099"}, {"firstname":"David","lastname":"Zimmerman","phone":"800-256-6321"}, {"firstname":"Bert","lastname":"Ernie","phone":"127-624-1138"}, {"firstname":"Guy","lastname":"Lafleur","phone":"806-797-4213"} ]';
showContacts(jsonText);
});
I have also updated your fiddlejs link

Related

How to make columns with collapsible ul and li tags dynamically?

I am currently using the following two functions to dynamically create a collapsible list from an object which contains info on the individual parts within the object. I have also included a checkbox for each item in the collapsible list, but that check box always appears right next to the names. I would prefer these checkboxes to be in the same row as the list item, but in a separate column so that it looks neater. I might also add more columns later on with material info. So I was trying to figure out how I can do this with my current setup below or if there was a better way to achieve what I want instead of using my list.
<div class="objtree"></div>
function check(obj) {
var html = '';
var name = obj.name ? obj.name +' (' +obj.type+')' : obj.type;
html +='<div class="node">'
html += '<li class="ntitle">' + name + '<input type="checkbox" name="'+(obj.id-id)+'" value="checked" onchange="snap(this)"/></li>';
if (obj.children) {
html += '<ul class="children hide">';
for (var i = 0; i < obj.children.length; i++) {
html += check(obj.children[i],)
}
html += '</ul>';
}
html += "</div>";
return html;
}
function assignEvent() {
$('.ntitle').click(function () {
var p = $(this);
var c = p.parent().find('.children:first')
if (c.hasClass('hide')) {
c.removeClass('hide');
p.addClass('open');
}
else {
c.addClass('hide');
p.removeClass('open');
}
})
}
The following is what I currently have which is collapsible if I click on the items:
And I am trying to achieve the following:

Why doesn't my innerHTML method work to list things in my contact form?

I am making a program, and I'm wondering why all I see on my html page is the form, but only a single . where the bulleted list for an unordered list should be. I input the user input in the fields, but it doesn't show me the data in the fields, like it's supposed to, when I click submit. Here's the code.
function getFormElements() {
var gather_form_elements = new Array(
$("#first_name").val(),
$("#last_name").val(),
$("email").val(),
$("#phone_number").val()
);
displayValues(gather_form_elements);
}
function displayValues(gather_form_elements) {
for(i=0; i<gather_form_elements.length; i++)
{
document.getElementById("contact_info").innerHTML = "<li>" + gather_form_elements[i] + "</li>";
}
}
Because you are overiding it on every iteration. Try to accumulate the html before using innerHTML like this:
var html = "";
for(var i = 0; i < gather_form_elements.length; i++) {
html += "<li>" + gather_form_elements[i] + "</li>";
// ^^ the += is crucial. If you don't use it, it will just replace the content of html (the innerHTML in your code), we need to use += to append to html instead of overriding it.
}
document.getElementById("contact_info").innerHTML = html;
You can acheive the same result using only one line of code:
document.getElementById("contact_info").innerHTML =
'<li>' + gather_form_elements.join('</li><li>') + '</li>';

jQueryUi Tabs isn't working when I use dynamically created divs

I'm currently working on a dealer search for my company. I want to add some tabs, so that the cutomers can filter the dealers per state. This means that the divs for the states are created dynamically, because the information comes from a CSV file.
I add the information like this:
function erzeugenTab() {
var $tabsDiv = $("#mapstabs");
var linkList ='';
var divRegion ='';
var linkZahl = 1
for (var i = 0; i < unique.length - 1; i++) {
linkList = linkList + "<li>" + unique[i] + "</li>" ;
divRegion = divRegion + "<div id =\"tabs"+linkZahl+"\">Test123</div>";
linkZahl = linkZahl + 1;
}
linkList = linkList + "</ul>";
$tabsDiv.append(linkList);
$tabsDiv.append(divRegion);
$(function() {
$('#mapstabs').tabs();
});
}
However, no tabs are apearring. You can se it here.
Any idea what I"m missing?
Can you try removing the $ on $tabsDiv turning it into just var tabsDiv?
Also, I do not see an open ul tag
Can you try by removing function()?
$(function() {
$('#mapstabs').tabs();
});
to
$('#mapstabs').tabs();

Using javascript/regex to filter through dynamically generated <input> tags

I am currently trying to create a dynamic printable-document generator for my training department at work. I would like the entire project to remain in Javascript/browser-side scripting, as I'm trying to gain knowledge in Javascript exclusively. The UI is linked below (can't post images until I have 10 rep):
Hosted on my personal website - cgiv.webs.com/Test Platform/Training Plan.png
The issue I'm having is with regular expressions. I am fairly new to Javascript, but VERY new to regular expressions within Jscript. I'm currently using the following function to generate and identify three input texts per execution:
/*Variable Declarations*/
var i1 = 0;
var i2 = 0;
/* ------------------- */
function generateInput()
{
if (i1<15)
{
i1++;
var appendSpan = document.getElementById('appendSpan');
var appendStr = "<div class='row'><input id='text_topic" + i2.toString() + i1.toString() + "' class='text_topic' type='text'/>|<input id='text_instructor" + i2.toString() + i1.toString() + "' class='text_instructor' type='text'/>|<input id='text_date" + i2.toString() + i1.toString() + "' class='text_date' type='text'/></div>";
appendSpan.innerHTML += appendStr;
}
else
{
alert("Action Cancelled. Maximum fields reached.");
}
}
The i2 variable indicates the header number that the input fields fall under, where the i1 variable indicates the row that each cell falls into. I would like to place a regex identifier script within the following function to pull the values from each cell and append them underneath their respective target spans within the "newPage" variable:
function createPage()
{
var newPage = "<html><head><title></title>";
newPage += "<link rel='stylesheet' lang='text/css' href='output.css'>";
newPage += "</head><body>";
newPage += "<div class='head'>" + promptVal[0] + "</div><br/>";
newPage += "<span id='hcontent1'></div></span>";
var inputs = document.getElementsByTagName("input");
/* Uhhh.. Yeah. This is where I'm lost */
newPage += "</span>";
newPage += "</body></html>";
var j = window.open('')
j.document.write(newPage);
j.document.close();
}
Once I can get, for example, text_(topic, instructor, date)(11-13) all within the "hcontent1" span, I can format it out. I just want the data to be pulled from the text fields and placed into div tags on a separate page.
Thanks for your time, ahead of time!
I figured it out! After like three days of searching, this worked:
var regex1 = /1/g;
for (var i=0; inputs[i]; i++)
{
if (inputs[i].id.search(regex1) == 10)
{
alert("It worked");
}
else if (inputs[i].id.search(regex1) == 15)
{
alert("It worked again");
}
else if (inputs[i].id.search(regex1) == 9)
{
alert("You did it, man");
}
else
{
alert("Skip this one");
}
}

Append a header to dynamically-loaded tables using JQuery

I've been having a hard time trying to append new headers to tables I build dynamically using data grabbed from an AJAX call.
I've already asked here a question about my problem, but it seems that there's no logical answer to it.
So my problem is that I can't actually get the table I want to append my new info to, what I tired was this:
console.log(id); //This prints the right id!
//THIS is not working...
$('#'+id+' tr:first').append("<td>Well "+(wellCounter)+"</td>");
//...
//$('#'+401+' tr:first').append("<td>Well "+(wellCounter)+"</td>");--this will work
table+="<td>M "+fourthLevel.male+"</td>";
table+="<td>H "+fourthLevel.herm+"</td>";
But it didn't work, so I was wondering if you can help me with another way to get the same functionality without using the id to get the table. Maybe the closest function will work but I don't have experience with that, and I tried it but failed.
Here the full code:
$.each(data, function(index, firstLevel) {
$.each(firstLevel, function(index2, secondLevel) {
var id = firstLevel['id'];
var author = firstLevel['author'];
var date = firstLevel['date'];
var experimental_conditions = firstLevel['experimental_conditions'];
if(index2 == 'items'){
var table = '<div class=tableWrapper><table id=\"'+id+'\" class=\"experimentTable\">';
table += '<input id=\"basketButton\" type=\"submit\" value=\"Add to basket\" class=\"basketButton\" experimentBatch=\"'+id+'\"> <div class="superHeader"><span class=\"superHeader\">Date: '+date+', By '+author+'</span><br /><span class=\"subHeader\">Experimental conditions: '+experimental_conditions+'</span>'
table += '<tr><td></td><td COLSPAN=2>Totals</td></tr>';
table += '<tr id="header"><td width="20%">Genotype</td><td width="10%"><img src="images/herma.png"></td><td width="10%"><img src="images/male.png"></td>';
//for each table
$.each(secondLevel, function(index3, thirdLevel) {
var nWells = 0;
table += "<tr><td>"+thirdLevel['mutant_name_c']+"</td><td>"+thirdLevel['herm_total']+"</td><td>"+thirdLevel['male_total']+"</td>";
currentRow = 3;
wellCounter = 0;
//for each row
$.each(thirdLevel, function(index4, fourthLevel) {
wellCounter++;
if (fourthLevel.date_r != undefined){
console.log(id);
//THIS is not working...
$('#'+id+' tr:first').append("<td>Well "+(wellCounter)+"</td>");
//...
table+="<td>M "+fourthLevel.male+"</td>";
table+="<td>H "+fourthLevel.herm+"</td>";
}
});
});
table +='</table></div>'
$('#searchResults').append(table);
}
});
});
NOTE: Male and herm are worm genders, not options!
I didn't go through your code, but when I'm working with dynamic table in jquery i try with Jquery "OBJECT". something like
var $tbl = $('<table />'), $tr=$('<tr />'), $td=$('<td />');
then you can add attr, append etc, and is much easier to read, and manipulate.
$tbl.attr('id',id).append($tr.append($td);
etc.

Categories

Resources