How to add repetitive div with jQuery? - javascript

When I click on the new button with jQuery it adds the div, but it only adds one. When I check from DevTools it constantly creates the same place. But I want it to add another one after that. Can you help me?
HTML code
<div class="text-left" style="margin-bottom: 15px;">
<button type="button" class="add-extra-email-button btn btn-success" disabled><i class="fas fa-plus"></i></button>
</div>
<div class="clone"></div>
Here are the sample js codes
$('.add-extra-email-button').click(function() {
var element = $('.clone');
element.html(
'<div class="clone_edilen_email">' +
'<li>' +
'<a href="javascript:;"> Test' +
'<i class="fa fa-circle-o-notch fa-spin fa-3x fa-fw"></i>' +
'</a>' +
'</li>' +
'</div>'
);
$('.clone_edilen_email').addClass('single-email remove-email');
$('.single-email').append('<div class="btn-delete-branch-email"><button class="remove-field-email btn btn-danger"><i class="fas fa-trash"></i></button></div>');
$('.clone_edilen_email > .single-email').attr("class", "remove-email");
});
$(document).on('click', '.remove-field-email', function(e) {
$(this).parent('.btn-delete-branch-email').parent('.remove-email').remove();
e.preventDefault();
});

If I understand correctly, you want to add the <div class="clone_edilen_email"> again and again, as soon somebody clicks on the .add-extra-email-button button.
In general, calling element.html('<some_wild_html></some_wild_html>') will always override the full inner content of element with <some_wild_html></some_wild_html>. Also, if the element already contains some other sub-elements, they will got lost. In your given code example, I assume, your intention was to extend the element's html and not replace it.
Here is my suggestion:
$('.add-extra-email-button').click(function() {
var newDiv = $('<div class="clone_edilen_mail"></div>');
newDiv.html('<li><a href="javascript:;"> Test<i class="fa fa-circle-o-notch fa-spin fa-3x fa-fw"></i></li>');
$('.clone').append(newDiv); // This is the important clue here!
// afterwards you may insert your residual class stuff
// $('.clone_edilen_email').addClass('single-email remove-email'); <- I would suggest you add these classes already at the begining, where I set the variable "newDiv"
// ...
// $('.single-email').append('<div class="btn-delete-branch-email"><button class="remove-field-email btn btn-danger"><i class="fas fa-trash"></i></button></div>');
// $('.clone_edilen_email > .single-email').attr("class", "remove-email");
});
// .. your other code may follow here ...
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="clone">I am a clone-div!</div>
<button class="add-extra-email-button">Click Me!</button>
Hope that this might help you!

Try This Method, Append Duplicate Elements and Contents Using jQuery .clone() Method
<!doctype html>
<html>
<head>
<title>jQuery Clone() – Add Elements and its Contents</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.10.1/jquery.min.js"></script>
<style>
div {
margin:3px;
padding:3px;
border:solid 1px #999;
width:300px;
}
</style>
</head>
<body>
<p>Click the button to clone (make a duplicate) of the DIV element!</p>
<div id="Container">Hello, how was your day!</div>
<p><input type="button" id="Button1" value="Clone it" /></p>
</body>
<script>
$(document).ready(function () {
$('#Button1').on('click', function () {
$('#Container')
.clone()
.appendTo("body");
});
});
</script>
</html>

In your first click function you replace all the content of your div clone so even if you click again you are going to have only one. He is just replacing the old one.
I didn't get what you are trying to do with the second click function.

Related

Remove input by clicking times icon

I have the following code which adds divs within a container (#subtask_container) via clicking a link (similar to Google Tasks):
HTML:
<p class="text-muted">
<i class="fas fa-tasks mr-2"></i>
Add subtasks
</p>
<div id="subtask_container"></div>
JS (this successfully adds unique inputs within the subtask container div along with a clickable x after each input)
var i = 1
$("#add_subtask").click(function () {
$("#subtask_container").append('<input name="subtask'+i+'" class="mt-1" id="subtask'+i+'" placeholder="Enter subtask"><i class="fas fa-times ml-1 text-muted"></i><br>');
i++;
});
What logic do I need to add to the x class to remove it's associated input?
I've tried
$('.fa-times').click(function(){
$(this).prev('input').remove();
});
but it doesn't seem to work...
Thanks!
You can simply wrap your subtask append in a div and simply use .parent() and .remove() function on that. No need to use <br>
Also, do not use .fa-times as primary click event handler as you might have other fa-times on the same page as well Which might cause issues later on. Add a custom class to your fa item (.subtask_remove_icon)
Live Demo:
var i = 1
$("#add_subtask").click(function() {
$("#subtask_container").append('<div><input name="subtask' + i + '" class="mt-1" id="subtask' + i + '" placeholder="Enter subtask"><i class="fas fa-times ml-1 text-muted subtask_remove_icon"></i></div>');
i++;
});
$(document).on('click', '.subtask_remove_icon', function() {
$(this).parent().remove(); //remove the input when X clicked
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://kit.fontawesome.com/a076d05399.js"></script>
<p class="text-muted">
<i class="fas fa-tasks mr-2"></i>
Add subtasks
</p>
<div id="subtask_container"></div>
The event handler gets attached to all elements that are on the page load. Since the icons are appended, the right way to do this would be the following:
var i = 1
$("#add_subtask").click(function () {
$("#subtask_container").append('<div><input name="subtask'+i+'" class="mt-1" id="subtask'+i+'" placeholder="Enter subtask"><i class="fas fa-times ml-1 text-muted removeIcon"></i><br></div>');
i++;
});
$(document).on('click', '.removeIcon', function(){
$(this).parent().remove();
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://kit.fontawesome.com/a076d05399.js"></script>
<p class="text-muted">
<i class="fas fa-tasks mr-2"></i>
Add subtasks
</p>
<div id="subtask_container"></div>

Using js onclick on one button to inject link into another

I have two buttons, both without links, and want to add a link to one when the other is clicked. How can I make one button with an onclick give a link attribute to something else on the page? If not a button, maybe a div?
The following is my current code:
<div class="container">
<div class="jumbotron" style="background-color:#000000 !important;">
<img id="myImage" src="images/closed.png" style="width:100%">
<p id="texthere"></p>
<div class="container">
<div class="row">
<div class="col">
<button onclick="document.getElementById('myImage').src='images/open.png'" class="btn btn-primary active btn-block">Open Eyes</button>
</div>
<div class="col">
<button onclick="document.getElementById('myImage').src='images/closed.png'"class="btn btn-primary active btn-block">Close eyes</button>
</div>
</div>
</div>
Thank you in advance for your help.
*Edited to clarify and pose as a question.
I think you may be confused about how HTML links work. HTML has the a tag for elements that a user can click to go to a different URL. The (worse) alternative is to use an onclick handler to redirect the user by setting the value of window.location.
To make a button that creates a link on the page, put a script tag at the bottom of the body that attaches a listener to a button that, when called, places a link on the page.
<script type="text/javascript">
var button = document.getElementById('my-button'); // This button has to exist.
button.addEventListener('click', function() {
var link = document.createElement('a');
link.href = 'google.com'; // Or wherever you want the link to point.
document.body.appendChild(link);
});
</script>
While there are many ways to do what you want, without knowing what programming skills you have and what you want to see on the screen, perhaps this sort of structure would help you. Replace your current onclick handlers on the BUTTONs:
<button id="open" class="btn btn-primary active btn-block">Open Eyes</button>
<button id="close" class="btn btn-primary active btn-block">Close eyes</button>
<script>
document.getElementById("open").addEventListener("click", function() {
changeState('open');
});
document.getElementById("close").addEventListener("click", function() {
changeState('closed')
});
function changeState(state) {
document.getElementById("myImage").src = 'images/' + state + '.png';
var new_para = document.createElement("p");
var new_link = document.createElement("a");
new_link.setAttribute("href", "https://www.google.com/search?" + state);
var new_link_text = document.createTextNode("Search for '" + state + "'");
new_link.appendChild(new_link_text);
new_para.appendChild(new_link);
document.body.appendChild(new_para);
}
</script>

Unable to find the specific items value jQuery

I am facing an easy problem but unable to find a solution the problem is
i am creating a dynamic div with some elements also with some data
$("#divSearchedIssue").append(`
<div class="statistic d-flex align-items-center bg-white has-shadow">
<div class="icon bg-red">
<i class="fa fa-tasks"></i>
</div>
<div class="text">
***//want to get this below id value//**
Mobile Code :
<small id="mbCode">
${ data[0].MobileCode }
</small>
***/want to find/**
<br>
Failed From:
<small>
${ data[0].FailedStation }
</small>
<br>
Issues :
<small>
${ data[0].Issues }
</small>
</div>
<div class="text"><strong> </strong></div>
<div class="text">
<button type="button" id="btn" class="btn btn-warning pull-right">Start</button>
</div>
<div class="text"><br></div>
</div>`);
Here I have a button .On this button click i want to fetch the value of
small text which id is #mbCode as mentioned above inside the code
I am trying this by using the following button click code
$(document).on('click', '#btn', function () {
var data = $(this).closest('small').find('#mbCode').val();
alert(data);
});
but its not working.I mean I cant fetch the value of #mbCode on this button click .So help needed
Thanks for helping
Based on .closest()
Description: For each element in the set, get the first element that
matches the selector by testing the element itself and traversing up
through its ancestors in the DOM tree.
As <small> is not an ancestors to button in hierarchy(while traversing-up),
So You need to first go the parent of <small> through .closest() and then try to find <small> html using .find() and .html()
$(document).on('click', '#btn', function () {
var data = $(this).closest('.statistic').find('small').html();
alert(data);
});
Working snippet:-
data = [{'MobileCode':20,'FailedStation':'WATERLOO','Issues':'broken'}];
$("#divSearchedIssue").append('<div class="statistic d-flex align-items- center bg-white has-shadow"><div class="icon bg-red"><i class="fa fa-tasks"></i></div><div class="text">Mobile Code :<small id="mbCode">' + data[0].MobileCode + '</small><br>Failed From: <small> ' + data[0].FailedStation + '</small><br>Issues :<small> '+ data[0].Issues + '</small></div><div class="text"><strong> </strong></div><div class="text"><button type="button" id="btn" class="btn btn-warning pull-right">Start</button></div><div class="text"><br></div></div>');
$(document).on('click', '#btn', function () {
var data = $(this).closest('.statistic').find('small').each(function(){
alert($(this).html());
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="divSearchedIssue"></div>
Note:- .text() will work too
https://jsfiddle.net/tyz4ox50/
As identifiers must be unique, Directly use ID Selector with .text()/.html() method
var data = $('#mbCode').text()
However if you are appending multiple elements I would recommend an alternative to persist Mobile code arbitrary data using custom data-* attribute along with <button> which can be fetched using .data(key) and attach event handler using Class Selector
$("#divSearchedIssue").append('<button type="button" id="btn" class="btn btn-warning pull-right" data-mobilecode="' + data[0].MobileCode + '" >Start</button>');
var counter = 0;
function append() {
$("#divSearchedIssue").append('<button type="button" id="btn" class="btn btn-warning pull-right" data-mobilecode="' + ++counter + '" >Start</button>');
}
append();
append();
append();
$(document).on('click', '.btn', function() {
var data = $(this).data('mobilecode');
console.log(data);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="divSearchedIssue"></div>
Try the following code snippet
var value = $('#mbCode').val();
Make sure the id is unique
Ids shouldn't be duplicate in an web-page.
Also, small is not one of the parent nodes of btns, and use html instead of val.
You need to go two-level higher to statistic Make it
$(document).on('click', '.text #btn', function () {
var data = $(this).closest('.statistic').find('#mbCode');
console.log(data.html());
});
Demo
var counter = 0;
function append() {
$("#divSearchedIssue").append(
`<div class="statistic d-flex align-items-
center bg-white has-shadow">
<div class="icon bg-red"><i class="fa fa-tasks">
</i></div>
<div class="text">
Mobile Code :<small id="mbCode">` +
(counter++) +
`</small><br>Failed From: <small> ' +
data[0].FailedStation + '</small><br>Issues :<small> ' + data[0].Issues +
'</small></div>
<div class="text"><strong> </strong>
</div>
<div class="text"><button type="button" id="btn" class="btn btn-
warning pull-right">Start</button></div>
<div class="text"><br></div>
</div>`
);
}
append();
append();
append();
$(document).on('click', '.text #btn', function () {
var data = $(this).closest('.statistic').find('#mbCode');
console.log(data.html());
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="divSearchedIssue"></div>
If your element already has an ID attribute you should be able to find the element by the ID. $("#mbCode")
Your js code
$(this).closest('small').find('#mbCode').val(); // "$(this)", in your code, represents the "button" that was clicked.
is looking for "small" tag inside "button" element, but it's not there. It would work if your button was like
<button type="button" id="btn" class="btn btn-warning pull-right"><small id="mbCode"></small></button>
This should work:
$(document).on('click', '#btn', function () {
var $mbCode = $('#mbCode');
console.log($mbCode);
});

jQuery .remove() not working to remove JQuery var

I am trying to remove the $movieDiv that is appended when clicking "#buttonLicensedMovie". It appends to the html just fine and the same button hides just fine, as it should. The issue I am having is when I click the anchor tag with id "licensedMovie1, the $movieDiv does not remove and the "#buttonLicensedMovie1" does not show back up. What am I doing wrong? Any help would be appreciated. Thanks!
JQuery:
$(function() {
$("#buttonLicensedMovie1").click(function(){
var $movieDiv = '<p class="header">Becoming An Agent</p>\n<iframe width="500" height="281" src="https://www.youtube.com" frameborder="0" allowfullscreen></iframe>\r\n<br/><a id="licensedMovie1" class="video-close"><i class="fa fa-times" aria-hidden="true"></i> Close Video</a>';
$("#movieLicensedWrapper1").append($movieDiv);
$("#buttonLicensedMovie1").hide();
});
});
$(function() {
$("#licensedMovie1").click(function(){
var $movieDiv = '<p class="header">Becoming An Agent</p>\n<iframe width="500" height="281" src="https://www.youtube.com/" frameborder="0" allowfullscreen></iframe>\r\n<br/><a id="licensedMovie1" class="video-close"><i class="fa fa-times" aria-hidden="true"></i> Close Video</a>';
$("#movieLicensedWrapper1").remove($movieDiv);
$("#buttonLicensedMovie1").show();
});
});
HTML:
<div class="col-xs-12">
<button id="buttonLicensedMovie1" type="button" class="btn btn-default"><h5>Becoming an Agent <i class="fa fa-caret-square-o-right fa-lg" aria-hidden="true"></i></h5></button>
<div class="col-xs-12" id="movieLicensedWrapper1">
</div>
</div>
You could use (won't work in your case because not everything is inside the p):
$("#movieLicensedWrapper1 p.header").remove();
Or you create a global variable and assign the value with:
$movieDiv = $.parseHTML('...');
And then you can remove with just:
$movieDiv.remove();
When you append it works fine because you are just adding html. However, when you want to remove you need to select the DOM element. Try this instead:
var $movieDiv = $('#movieLicensedWrapper1').find('.header');
$movieDiv.remove();

Hide/Show many elements on single click by jQuery

I've code few line of jQuery for Hide/Show many elements on single click and it's working. But problem is; i've many more image class items, so my script going to long, my question is how to simplify or make short my script, i mean any alternatives or any new idea? please suggest.
HTML:
<div id="choose-color">
<span>
<i class="images-red" style="">Red Image</i>
<i class="images-blue" style="display: none;">Blue Image</i>
<i class="images-pink" style="display: none;">Pink Image</i>
<!-- many many images -->
</span>
<button class="red">Red</button>
<button class="blue">Blue</button>
<button class="pink">Pink</button>
</div>
JS: live demo >
$("button.red").click(function(){
$(".images-red").show();
$(".images-blue, .images-pink").hide();
});
$("button.blue").click(function(){
$(".images-red, .images-pink").hide();
$(".images-blue").show();
});
$("button.pink").click(function(){
$(".images-red, .images-blue").hide();
$(".images-pink").show();
});
Please suggest for short and simple code of my script. Thanks.
You can do it by adding just a common class to those buttons,
var iTags = $("#choose-color span i");
$("#choose-color button.button").click(function(){
iTags.hide().eq($(this).index("button.button")).show();
});
The concept behind the code is to bind click event for the buttons by using the common class. Now inside the event handler, hide all the i elements which has been cached already and show the one which has the same index as clicked button.
DEMO
For more details : .eq() and .index(selector)
And if your elements order are not same, both the i and button's. Then you can use the dataset feature of javascript to over come that issue.
var iTags = $("#choose-color span i");
$("#choose-color button.button").click(function(){
iTags.hide().filter(".images-" + this.dataset.class).show()
});
For implementing this you have to add data attribute to your buttons like,
<button data-class="red" class="button red">Red</button>
DEMO
This works
$("#choose-color button").click(function(){
var _class = $(this).attr('class');
$("#choose-color i").hide();
$(".images-"+_class).show();
});
https://jsfiddle.net/455k1hhh/5/
I know this might not be the prettiest solution, but it should do the job.
$("button").click(function(){
var classname = $(this).attr('class');
$("#choose-color span i").hide();
$(".images-"+classname).show();
});
You're making future extensibility a little difficult this way due to relying on class names but this would solve your immediate need:
<div id="myImages">
<i class="images-red" style="">Red Image</i>
<i class="images-blue" style="display: none;">Blue Image</i>
<i class="images-pink" style="display: none;">Pink Image</i>
<!-- Many many image -->
</div>
<div id="myButtons">
<button class="red">Red</button>
<button class="blue">Blue</button>
<button class="pink">Pink</button>
</div>
$("#myButtons button").click(function(){
var color = $(this).attr("class");
var imageClass = ".images-"+color;
$('#myImages').children("i").each(function () {
$(this).hide();
});
$(imageClass).show();
});
Here's a JSFiddle
Edit: Note how I wrapped the buttons and images in parent divs to allow you to isolate just the buttons/images you want to work with.
You can do the following using data-* attributes, because when you have more elements of the same color, using index of the button won't work. And simply using the whole class attribute won't work if you have to add more classes to the button in future.
$("button").click(function() {
var color = $(this).data('color');
var targets = $('.images-' + color);
targets.show();
$("span i").not(targets).hide();
});
.hidden {
display: none
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<br/>
<br/>
<div id="choose-color">
<span>
<i class="images-red">Red Image</i>
<i class="images-blue hidden">Blue Image</i>
<i class="images-pink hidden">Pink Image</i>
<!-- Many many image -->
</span>
<br/>
<br/>
<button data-color="red">Red</button>
<button data-color="blue">Blue</button>
<button data-color="pink">Pink</button>
</div>
It would make sense to have all images share a single class (.image for example). Then you just use a shared class for the button and the image; in this example I used the color name. Now, when any button is clicked, you can grab the class name of the image you want to show.
Give this a try:
$("button").click(function(){
$(".image").hide();
var className = $(this).attr("class");
$("." + className).show();
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<br/><br/>
<div id="choose-color">
<span>
<i class="image red" style="">Red Image</i>
<i class="image blue" style="display: none;">Blue Image</i>
<i class="image pink" style="display: none;">Pink Image</i>
<!-- Many many image -->
</span>
<br/><br/>
<button class="red">Red</button>
<button class="blue">Blue</button>
<button class="pink">Pink</button>
</div>
You may try this:
<div id="choose-color">
<span>
<i class="images-red" style="">Red Image</i>
<i class="images-blue" style="display: none;">Blue Image</i>
<i class="images-pink" style="display: none;">Pink Image</i>
<!-- Many image -->
</span>
<br/><br/>
<button class="colour red" onclick="myFunction(this)">Red</button>
<button class="colour blue" onclick="myFunction(this)">Blue</button>
<button class="colour pink" onclick="myFunction(this)">Pink</button>
</div>
JS: see here
$(".colour").click(function(){
var colors = ["red", "blue", "pink"];
for (i = 0; i < colors.length; i++) {
if($(this).hasClass(colors[i])){
$(".images-"+colors[i]).show();
}else{
$(".images-"+colors[i]).hide();
}
}
});

Categories