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>
this is how you must do :
$(document).ready(function() {
$('#button').click(function(){
$("#box").append('<br><span>username</span><span>5:00pm</span>')
})
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="box">
</div>
<a id="button">button</a>
Since ID must be unique as #mplungjan mentioned, assuming you have some css linked with them, i'll just give examples with a class instead of IDs
$("#button").click(function(){
$("#main").append(
$("<div>").addClass("box")
.append($("<span>").addClass("name").text("username"))
.append($("<span>").addClass("time").text("5:00PM"))
);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="main"></div>
<button id="button">Click me</button>
As you can see, after using the syntax $("<div>") you can chain as you want like you would in jQuery. The main difference between this and what #mplungjan has shown is how dynamic you are planning to make these. If you are planning on expanding these divs and spans dynamically as you go you are better off using this. If not and you just want lesser syntax you could rather use his.
Related
I am making a gallery and in that gallery, there would be images wrapped in divs. In jQuery, I could call these divs like:
var card = $('.card');
This card variable will now contain all the elements with the 'card' class. Now, what I want to happen is whenever I click on a 'card', it would grab that very instance of card (I'm thinking by getting its index onclick) and do something with it as object-oriented as possible (though I never had much experience with it)
You can use simple this object:
https://codepen.io/bra1N/pen/ERXPJw
$('.card').on("click",function() {
$(this).css('background', 'red');
});
.card {
cursor: pointer;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="card">A</div>
<div class="card">B</div>
<div class="card">C</div>
Here is what you can do:
Dummy HTML:
<div class="card">A</div>
<div class="card">B</div>
<div class="card">C</div>
jQuery needed:
$('.card').click(function() {
alert($(this).text());
});
Here is the link to the jsfiddle supporting this answer.
$('.card').click(function() {
alert($(this).text());
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="card">A</div>
<div class="card">B</div>
<div class="card">C</div>
I am building a "edit profile" page.
Here is what I want to do:
In each section, the employer will be shown and the edit form will be hidden.
When I click the "edit employer" button, the edit form will be shown and the employer will be hidden.
Here is what I did using jQuery. It does not work when I click on the "edit employer" button. I do not know why this does not work.
<!DOCTYPE html>
<html>
<head>
<script
src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
</head>
<body>
<div class="edit">
<form class="editForm">
employer: <input type="text" value="Citigroup" />
</form>
<div class="contents">Employer: Citigroup</div>
<button class="editButton">Edit Employer</button>
</div>
<script>
$('div.edit').each(function(i) {
$(this).children('.editForm').hide();
})
$('div.edit').each(function() {
$(this).children('.editButton').click(function() {
$(this).children('.editForm').show();
$(this).children('.contents').hide();
});
})
</script>
</body>
</html>
The $(this) inside the click function contains the local instance of the $(this).children('.editButton'). For that reason your code is not finding any .editForm elements.
For this to work you could do something like this:
<script>
$('div.edit').each(function(i) {
$(this).children('.editForm').hide();
})
$('div.edit').each(function() {
var $this = $(this);
$(this).children('.editButton').click(function() {
$this.children('.editForm').show();
$this.children('.contents').hide();
});
})
</script>
If I may I would improve the code with some more changes:
<script>
$('.edit .editForm').hide(); // this will hide all instances of .editForm
$('.edit .editButton').click(function() { //assign 1 handler for all cases
$(this).siblings('.editForm').show(); // show the sibling edit form
$(this).siblings('.contents').hide(); // hide the sibling contents element
});
</script>
Reference:
Sibling Selector: https://api.jquery.com/siblings/#siblings-selector
The problem is the this inside the click handler referring to the button, not the div.edit. Here's one way to fix this:
$('div.edit').each(function(i) {
$(this).children('.editForm').hide();
});
$('div.edit').each(function() {
var $self = $(this);
$(this).children('.editButton').click(function() {
$self.children('.editForm').show();
$self.children('.contents').hide();
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="edit">
<form class="editForm">
employer:
<input type="text" value="Citigroup" />
</form>
<div class="contents">Employer: Citigroup</div>
<button class="editButton">Edit Employer</button>
</div>
You don't need to use .each() at all. Just do an .click() event on the class of .editButton and use this to find its parent. If you want to make a toggle, you're going to have to make use of a new class or something of that nature to make a conditional statement off of.
//This will hide *ANY* .editForm elements
$('.editForm').hide();
//This will fire off of *ANY* editButton clicks.
$('.editButton').click(function() {
var form = $(this).closest('.edit'); //Get the wrapper
if(form.hasClass('open')) { //Check to see if it is open or not
form.removeClass('open').addClass('close'); //Toggle Classes
form.find('.editForm').show();
form.find('.contents').hide();
} else {
form.removeClass('close').addClass('open');
form.find('.editForm').hide();
form.find('.contents').show();
}
});
I like to use closest and find more than parent and children (respectively). They can go 1-many layers up or down and search the hierarchy for whatever you're looking for, rather than parent and children going up or down a single layer.
If you are inserting your .edit form after the DOM loads, you're going to need to bind your click event to the document
$(document).on('click', '.editButton', function() {
var form = $(this).closest('.edit');
form.find('.editForm').hide();
form.find('.contents').show();
});
I am adding text to an element in Jquery using
$('.alert-saved').append('<br />See more like this >>')
I then show this to the user and pause.
$('.alert-saved').delay(5000).fadeOut(2000);
I would now like to remove all the text I appended.
I have tried this but it didn't work
$('.alert-saved').remove('<br />See more like this >>')
Just pass an empty HTML string argument:
$('.alert-saved').html('');
EDIT 1
If you need to keep other elements, you can use this method:
var newLine = jQuery('<br />See more like this');
jQuery(".alert-saved").append(newLine);
setTimeout(function() {
jQuery(newLine).remove();
}, 2000)
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<p class="alert-saved">
<span>I wanna stay!</span>
</p>
Change your code to :
$('.alert-saved').append('<div id="divId"><br />See more like this >></div>');
And while removing you can use :
$('.alert-saved').remove('#divId');
With the help of divId you can easily remove your appended element/string from '.alert-saved'.
Check the below code it will work as expected -
$('.alert-saved').append('<div class="testing" <br />See more like this >> </div>')
$('.alert-saved').delay(5000).fadeOut(2000);
$('.alert-saved').remove('.testing')
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div class="alert-saved"></div>
You could try this also :
$('.alert-saved').next().remove();
You can wrap your element in an tagged element with a class, or a custom tag, and then delete it accordingly like:
var release_id = 'demo'
$('.alert-saved').append('<div class="added"><br />See more like this >></div>')
setTimeout(function() {
$('.alert-saved>.added').remove();
}, 5000);
Demo: https://jsfiddle.net/Lxy83r43/
Whatever you append append with a class like this and remove all at once using .remove()
Checkout the demo below
$('.yes').click(function(){
$('.alert-saved').append('<div class ="added" ><br />See more like this >>');
})
$('.me').click(function(){
$('.added').remove();
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="alert-saved">
asdasdasdas
</div>
<input type="button" class="me" value="remove"/>
<input type="button" class="yes" value="add"/>
An easy way to do this work is adding class or id to appended element.
But if you don't want to do this, you can store new elements in variable and append it using .appendTo() to html document like this:
var HTML = $("<br><a>New link</a>");
$(HTML).appendTo('.alert-saved');
When you want to remove elements, use bottom code.
HTML.remove();
var HTML = $("<br><a>New link</a>");
$(HTML).appendTo('.alert-saved');
setTimeout(function(){
HTML.remove();
}, 2000);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="alert-saved">
<a>Old link</a>
</div>
I have this HTML:
<body>
<div id="switcher" class="switcher">
<h3>Style Switcher</h3>
<button id="switcher-default">
Default
</button>
<button id="switcher-narrow">
Narrow Column
</button>
<button id="switcher-large">
Large Print
</button>
</div>
<p>asdfasdfasdfas dsadf</p>
<p>asd'lfkasdf</p>
<script src="jquery.js"></script>
<script src="test.js"></script>
</body>
I want to add a class to all body elements except my first div (which has the id called switcher), when I click on the Large print button.
I have tried
$(document).ready(function(){
$("#switcher-large").bind("click", function(){
$("body:not(:first-child)").addClass("large");
});
});
and
$(document).ready(function(){
$("#switcher-large").bind("click", function(){
$("body:not(div)").addClass("large");
});
});
and
$(document).ready(function(){
$("#switcher-large").bind("click", function(){
$("body").not("#switcher").addClass("large");
});
});
but none seem to work (the class applies to all elements).
I don't want to find an alternate way like selecting only p elements. I just want to understand why the selectors I used don't work...
You need to exclude the document.body itself. Like
$("body *").not("#switcher").addClass("large");
This will query for all children of body, excluding #switcher. Maybe more convinient:
$(document.body).contents().not('#switcher').addClass('large');
$("body").children().not("#switcher").addClass("large");
I have a a link that looks similar to this
Blog
As you can the link has an ID of 'blog' what I want to do is to create an div on the fly with the ID from the link that was clicked so if the 'blog' is clicked, then the markup would be
<div id="blog">
<!--some content here-->
</div>
Like wise if for instance the news link is clicked then I would like,
<div id="news">
<!--some content here-->
</div>
to be created in the markup if this possible? and how Im pretty new to jQuery.
Try this:
$("a").click(function(){
$("#wrapper").append("<div id=" + this.id + "></div>");
});
Not tested, should work ;)
where: #wrapper is parent element, work on all a as you see.
You will need to give the div a different ID. Perhaps you could give it a class instead:
$("#blog").click(function() {
$(this).after("<div class='blog'>...</div>");
return false;
});
That's just one of many ways to create a div. You probably also want to avoid duplicates however in which case, use something like this:
$("#blog").click(function() {
var content = $("#blog_content");
if (content.length == 0) {
content = $("<div></div>").attr("id", "blog_content");
$(this).after(content);
}
content.html("...");
return false;
});
As for how to handle multiple such links I would do something like this:
Blog
News
Weather
<div id="content"></div>
with:
$("a.content").click(function() {
$("#content").load('/content/' + this.id, function() {
$(this).fadeIn();
});
return false;
});
The point is this one event handler handles all the links. It's done cleanly with classes for the selector and IDs to identify them and it avoids too much DOOM manipulation. If you want each of these things in a separate <div> I would statically create each of them rather than creating them dynamically. Hide them if you don't need to see them.
Try This :
<a id="blog">Blog</a>
<a id="news">news</a>
<a id="test1">test1</a>
<a id="test2">test2</a>
$('a').click(function()
{
$('<div/>',{
id : this.id,
text : "you have clicked on : " + this.id
}).appendTo("#" + this.id);
});
First of all you should not make 2 elements with same ID. At your example a and div will both have id="blog". Not XHTML compliant, plus might mess up you JS code if u refernce them.
Here comes non-jquery solution (add this within script tags):
function addDiv (linkElement) {
var div = document.createElement('div');
div.id = linkElement.id;
div.innerHTML = '<!--some content here-->';
document.body.appendChild(div); // adds element to body
}
Then add to HTML element an "event handler":
Blog
This question describes how to create a div. However, you shouldn't have two elements with same IDs. Is there any reason why you can't give it an id like content_blog, or content_news?
Unfortunately if you click on a link the page you go to has no idea what the idea of the link you clicked was. The only information it knows is what's contained in the URL. A better way to do this would be to use the querystring:
Blog
Then using the jQuery querystring plugin you could create the div like:
$("wrapper").add("div").attr("id", $.query.get("id"));
You shouldn't have elements in your page with the same ID. Use a prefix if you like, or perhaps a class.
However, the answer is as follows. I am imagining that your clickable links are within a div with the ID "menu", and your on-the-fly divs are to be created within a div with the ID "content".
$('div#menu a').click(function(){
$('div#content').append('<div id="content_'+this.id+'"><!-- some content here --></div>');
});
Any problems, ask in the comments!
Also the following statement is available to create a div dynamically.
$("<div>Hello</div>").appendTo('.appendTo');
Working fiddle: https://jsfiddle.net/andreitodorut/xbym0bsu/
you can try this code
$('body').on('click', '#btn', function() {
$($('<div>').text('NewDive').appendTo("#old")).fadeOut(0).fadeIn(1000);
})
#old > div{
width: 100px;
background: gray;
color: white;
height: 20px;
font: 12px;
padding-left: 4px;
line-height: 20px;
margin: 3px;
}
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Test</title>
<link rel="stylesheet" href="./index.css">
</head>
<body>
<div>
<!-- Button trigger modal -->
<button type="button" id="btn">Create Div</button>
<div id="old">
</div>
</div>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
</body>
</html>