0

I have this code below that has a Multidimensional Array and i'm using this array to dynamically create DOM elements to populate my HTML Tab the problem now is that i'm trying to use my ['hobbies'] array to append it below every name in the tab.

I have used a foreach loop to make each [hobbies] array value have their own div tag. But i'm not sure how to use each of this divs to append it below the names. Any suggestion would be greatly appreciated. enter image description here

var personArr = [];
var person = {["first-Name"]: "John", ["last-Name"]: "Doe", ["age"]: 21, ["hobbies"]:["football","swimming","dancing"],
  ["person-desc"]: "<br />Bacon ipsum dolor amet short loin doner tail meatloaf hamburger jerky <br />boudin picanha shankle turducken prosciutto cow kielbasa tenderloin."
};
var person2 = {
  ["first-Name"]: "Paul",
  ["last-Name"]: "Logan",
  ["age"]: 22,
  ["hobbies"]:["camping","sleeping","eating"],
  ["person-desc"]: "Bacon ipsum dolor amet short loin doner tail meatloaf hamburger jerky boudin picanha shankle turducken prosciutto cow kielbasa tenderloin. "
};
var person3 = {
  ["first-Name"]: "Sean",
  ["last-Name"]: "Kim",
  ["age"]: 32,
  ["hobbies"]:["running","jogging","climbing"],
  ["person-desc"]: "Bacon ipsum dolor amet short loin doner tail meatloaf hamburger jerky boudin picanha shankle turducken prosciutto cow kielbasa tenderloin."
};
var person4 = {
  ["first-Name"]: "Ken",
  ["last-Name"]: "Chow",
  ["age"]: 12,
  ["hobbies"]:["gyming","movies","tv"],
  ["person-desc"]: "Bacon ipsum dolor amet short loin doner tail meatloaf hamburger jerky boudin picanha shankle turducken prosciutto cow kielbasa tenderloin."
};

personArr.push(person, person2, person3, person4);
console.log(personArr);
var $parent = $('.line1').eq(0);



personArr.forEach((person, i) => {
  var $name = $('<h4/>');
  var $desc = $('<p/>');
  var $hobbie = $('<div/>');
	
	
  var hobbieArray = '';
	$.each(person['hobbies'], function (index) {
    hobbieArray += ('<div class="hobclass ">' + person['hobbies'][index] + '</div>');
	});
  
  $name.html(` ${person['first-Name']} ${person['last-Name']}`);
  $desc.html(` ${person['person-desc']}`);
  $parent.append($name).append($desc).append($hobbie);

});


//<---------------------------------------------- TAB FUNCTION ------------------------------------------------------->
function openCity(evt, cityName) {
  var i, tabcontent, tablinks;
  tabcontent = document.getElementsByClassName("tabcontent");
  for (i = 0; i < tabcontent.length; i++) {
    tabcontent[i].style.display = "none";
  }
  tablinks = document.getElementsByClassName("tablinks");
  for (i = 0; i < tablinks.length; i++) {
    tablinks[i].className = tablinks[i].className.replace(" active", "");
  }
  document.getElementById(cityName).style.display = "block";
  evt.currentTarget.className += " active";
}
document.getElementById("defaultOpen").click();
body {font-family: Arial;}

/* Style the tab */
.tab {
    overflow: hidden;
    border: 1px solid #ccc;
    background-color: #f1f1f1;
}

/* Style the buttons inside the tab */
.tab button {
    background-color: inherit;
    float: left;
    border: none;
    outline: none;
    cursor: pointer;
    padding: 14px 16px;
    transition: 0.3s;
    font-size: 17px;
}

/* Change background color of buttons on hover */
.tab button:hover {
    background-color: #ddd;
}

/* Create an active/current tablink class */
.tab button.active {
    background-color: #ccc;
}

/* Style the tab content */
.tabcontent {
    display: none;
    padding: 6px 12px;
    border: 1px solid #ccc;
    border-top: none;
}
.line1{
display:inline-block;
}
.size{
width:50%;
}
a.morelink {
	text-decoration:none;
	outline: none;
}
.morecontent span {
	display: none;

}
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width, initial-scale=1">
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
    <script src="//code.jquery.com/ui/1.12.1/jquery-ui.js"></script>

</head>
<body>
<div class ="size">
<div class="tab">
  <button class="tablinks" onclick="openCity(event, 'People')" id="defaultOpen">People</button>
</div>

<div id="People" class="tabcontent">
<div class="line1"> 

 </div>
 </div>
</div>

</body>
</html> 

3 Answers 3

2

You just need to insert hobbieArray (which is an HTML string, not an array) into the $hobbie element. Use .html like you have elsewhere.

var hobbieHTML = '';
$.each(person['hobbies'], function (index) {
    hobbieHTML += ('<div class="hobclass ">' + person['hobbies'][index] + '</div>');
});
$hobbie.html( hobbieHTML );

Using JS to write HTML is a bit clumsy, it's often easier to work with elements (like you've already done with $name and $desc)

$.each(person['hobbies'], function (index) {
    var $h = $('<div/>').addClass('hobclass').text( person['hobbies'][index] );
    $hobbie.append( $h );
});

When defining object keys you never need to use both [] and "". You only need "" when the key has special characters. It's usually better to name your keys without special characters if you can.

var person2 = {
    firstName: "Paul",
    lastName: "Logan",
    age: 22,
    hobbies: [ "camping", "sleeping", "eating" ],
    description: "Bacon ipsum dolor amet short loin doner tail meatloaf hamburger jerky boudin picanha shankle turducken prosciutto cow kielbasa tenderloin. "
};

Now it's easier to access properties of the object with dot notation. You could also use the native Array.forEach instead of jQuery's $.each.

person.hobbies.forEach( function ( hobby ) {
    var $h = $('<div/>').addClass('hobclass').text( hobby );
    $hobbie.append( $h );
})
$name.html(` ${ person.firstName } ${ person.lastName }`);
$desc.html(` ${ person.description }`);
Sign up to request clarification or add additional context in comments.

1 Comment

that works perfectly but what if i want to add extra opening div tag before the first value and a closing tag after the last value
1

in your code $hobbie has nothing to show. You are constructing divs with hobbiearray, I've updated your code, is that is what you want?

Updated code snippet

var $hobbieArray = '<div>';
        $.each(person['hobbies'], function (index) {
        $hobbieArray += ('<div class="hobclass ">' + person['hobbies'][index] + '</div>');
        });
$hobbieArray += '</div>'

var personArr = [];
var person = {["first-Name"]: "John", ["last-Name"]: "Doe", ["age"]: 21, ["hobbies"]:["football","swimming","dancing"],
  ["person-desc"]: "<br />Bacon ipsum dolor amet short loin doner tail meatloaf hamburger jerky <br />boudin picanha shankle turducken prosciutto cow kielbasa tenderloin."
};
var person2 = {
  ["first-Name"]: "Paul",
  ["last-Name"]: "Logan",
  ["age"]: 22,
  ["hobbies"]:["camping","sleeping","eating"],
  ["person-desc"]: "Bacon ipsum dolor amet short loin doner tail meatloaf hamburger jerky boudin picanha shankle turducken prosciutto cow kielbasa tenderloin. "
};
var person3 = {
  ["first-Name"]: "Sean",
  ["last-Name"]: "Kim",
  ["age"]: 32,
  ["hobbies"]:["running","jogging","climbing"],
  ["person-desc"]: "Bacon ipsum dolor amet short loin doner tail meatloaf hamburger jerky boudin picanha shankle turducken prosciutto cow kielbasa tenderloin."
};
var person4 = {
  ["first-Name"]: "Ken",
  ["last-Name"]: "Chow",
  ["age"]: 12,
  ["hobbies"]:["gyming","movies","tv"],
  ["person-desc"]: "Bacon ipsum dolor amet short loin doner tail meatloaf hamburger jerky boudin picanha shankle turducken prosciutto cow kielbasa tenderloin."
};

personArr.push(person, person2, person3, person4);
console.log(personArr);
var $parent = $('.line1').eq(0);



personArr.forEach((person, i) => {
  var $name = $('<h4/>');
  var $desc = $('<p/>');
  var $hobbie = $('<div/>');
	
	
  var $hobbieArray = '<div class="root-div">';
	$.each(person['hobbies'], function (index) {
    $hobbieArray += ('<div class="hobclass ">' + person['hobbies'][index] + '</div>');
	});
$hobbieArray += '</div>'
  
  $name.html(` ${person['first-Name']} ${person['last-Name']}`);
  $desc.html(` ${person['person-desc']}`);
  $parent.append($name).append($desc).append($hobbieArray);

});


//<---------------------------------------------- TAB FUNCTION ------------------------------------------------------->
function openCity(evt, cityName) {
  var i, tabcontent, tablinks;
  tabcontent = document.getElementsByClassName("tabcontent");
  for (i = 0; i < tabcontent.length; i++) {
    tabcontent[i].style.display = "none";
  }
  tablinks = document.getElementsByClassName("tablinks");
  for (i = 0; i < tablinks.length; i++) {
    tablinks[i].className = tablinks[i].className.replace(" active", "");
  }
  document.getElementById(cityName).style.display = "block";
  evt.currentTarget.className += " active";
}
document.getElementById("defaultOpen").click();
body {font-family: Arial;}

/* Style the tab */
.tab {
    overflow: hidden;
    border: 1px solid #ccc;
    background-color: #f1f1f1;
}

/* Style the buttons inside the tab */
.tab button {
    background-color: inherit;
    float: left;
    border: none;
    outline: none;
    cursor: pointer;
    padding: 14px 16px;
    transition: 0.3s;
    font-size: 17px;
}

/* Change background color of buttons on hover */
.tab button:hover {
    background-color: #ddd;
}

/* Create an active/current tablink class */
.tab button.active {
    background-color: #ccc;
}

/* Style the tab content */
.tabcontent {
    display: none;
    padding: 6px 12px;
    border: 1px solid #ccc;
    border-top: none;
}
.line1{
display:inline-block;
}
.size{
width:50%;
}
a.morelink {
	text-decoration:none;
	outline: none;
}
.morecontent span {
	display: none;

}
.root-div {
background-color: yellow
}
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width, initial-scale=1">
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
    <script src="//code.jquery.com/ui/1.12.1/jquery-ui.js"></script>

</head>
<body>
<div class ="size">
<div class="tab">
  <button class="tablinks" onclick="openCity(event, 'People')" id="defaultOpen">People test</button>
</div>

<div id="People" class="tabcontent">
<div class="line1"> 

 </div>
 </div>
</div>

</body>
</html> 

2 Comments

As Ben West said, you have to use $hobbie.html(hobbieArray);
Yeah this is what i want but i also want to have div tag at the start of the first value and at closing at the end
1

move the declaration of the var hobbieArray = ''; to a place before the loop then append it the same way you did to name and desc

var personArr = [];
var person = {["first-Name"]: "John", ["last-Name"]: "Doe", ["age"]: 21, ["hobbies"]:["football","swimming","dancing"],
  ["person-desc"]: "<br />Bacon ipsum dolor amet short loin doner tail meatloaf hamburger jerky <br />boudin picanha shankle turducken prosciutto cow kielbasa tenderloin."
};
var person2 = {
  ["first-Name"]: "Paul",
  ["last-Name"]: "Logan",
  ["age"]: 22,
  ["hobbies"]:["camping","sleeping","eating"],
  ["person-desc"]: "Bacon ipsum dolor amet short loin doner tail meatloaf hamburger jerky boudin picanha shankle turducken prosciutto cow kielbasa tenderloin. "
};
var person3 = {
  ["first-Name"]: "Sean",
  ["last-Name"]: "Kim",
  ["age"]: 32,
  ["hobbies"]:["running","jogging","climbing"],
  ["person-desc"]: "Bacon ipsum dolor amet short loin doner tail meatloaf hamburger jerky boudin picanha shankle turducken prosciutto cow kielbasa tenderloin."
};
var person4 = {
  ["first-Name"]: "Ken",
  ["last-Name"]: "Chow",
  ["age"]: 12,
  ["hobbies"]:["gyming","movies","tv"],
  ["person-desc"]: "Bacon ipsum dolor amet short loin doner tail meatloaf hamburger jerky boudin picanha shankle turducken prosciutto cow kielbasa tenderloin."
};

personArr.push(person, person2, person3, person4);
console.log(personArr);
var $parent = $('.line1').eq(0);


 var hobbieArray = '';

personArr.forEach((person, i) => {
  var $name = $('<h4/>');
  var $desc = $('<p/>');
  var $hobbie = $('<div/>');
	
	
      	$.each(person['hobbies'], function (index) {
    hobbieArray += ('<div class="hobclass ">' + person['hobbies'][index] + '</div>');
	});
  
  $name.html(` ${person['first-Name']} ${person['last-Name']}`);
  $desc.html(` ${person['person-desc']}`);
  $hobbie.html(hobbieArray)
  $parent.append($name).append($desc).append($hobbie);

});


//<---------------------------------------------- TAB FUNCTION ------------------------------------------------------->
function openCity(evt, cityName) {
  var i, tabcontent, tablinks;
  tabcontent = document.getElementsByClassName("tabcontent");
  for (i = 0; i < tabcontent.length; i++) {
    tabcontent[i].style.display = "none";
  }
  tablinks = document.getElementsByClassName("tablinks");
  for (i = 0; i < tablinks.length; i++) {
    tablinks[i].className = tablinks[i].className.replace(" active", "");
  }
  document.getElementById(cityName).style.display = "block";
  evt.currentTarget.className += " active";
}
document.getElementById("defaultOpen").click();
body {font-family: Arial;}

/* Style the tab */
.tab {
    overflow: hidden;
    border: 1px solid #ccc;
    background-color: #f1f1f1;
}

/* Style the buttons inside the tab */
.tab button {
    background-color: inherit;
    float: left;
    border: none;
    outline: none;
    cursor: pointer;
    padding: 14px 16px;
    transition: 0.3s;
    font-size: 17px;
}

/* Change background color of buttons on hover */
.tab button:hover {
    background-color: #ddd;
}

/* Create an active/current tablink class */
.tab button.active {
    background-color: #ccc;
}

/* Style the tab content */
.tabcontent {
    display: none;
    padding: 6px 12px;
    border: 1px solid #ccc;
    border-top: none;
}
.line1{
display:inline-block;
}
.size{
width:50%;
}
a.morelink {
	text-decoration:none;
	outline: none;
}
.morecontent span {
	display: none;

}
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width, initial-scale=1">
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
    <script src="//code.jquery.com/ui/1.12.1/jquery-ui.js"></script>

</head>
<body>
<div class ="size">
<div class="tab">
  <button class="tablinks" onclick="openCity(event, 'People')" id="defaultOpen">People</button>
</div>

<div id="People" class="tabcontent">
<div class="line1"> 

 </div>
 </div>
</div>

</body>
</html> 

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.