How can I make a new row of data using jquery? For example i have a div with an id "box" and I have two spans each with an id of "name" and "time". How can I have jquery append to this box holding both name and time? I tried experimenting and tried this code, but didn't work.
$("#button").click(function(){
$("#box").append(
$("#name").text("username"),
$("#time").text("5:00pm")
);
)}
In this code, I expected the box to create a new row of data every time I click the button. So if I want 5 rows of data, I would just click the button 5 times.
IDs must be unique and you need new spans
$("#button").on("click",function() {
$("#box").append(
"<br><span>username</span> <span>5:00pm</span>"
);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
<button type="button" id="button">Click</button>
<div id="box"></div>
With vars, you can use a template literal
var cnt=0,
data = [{ username: "John", time: "05:00pm" },
{ username: "Paul", time: "07:00pm" }];
$("#button").on("click", function() {
if (cnt < data.length) {
$("#box").append(
`<br><span class="user">${data[cnt].username}</span> <span class="time">${data[cnt++].time}</span>`
);
}
});
.user { color:green }
.time { color: red }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
<button type="button" id="button">Click</button>
<div id="box"></div>
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments