Following code add div on click button. But I want to add classes to all divs in code with id(1), id(2) etc without clicking position. Is this possible.
JS:
$(function() {
$('button').on('click', function() {
var $sparkLines = $('.sparkLines');
$("#sparkLineContainer").append('<div id="id' + ($sparkLines.length + 1) + '" class="sparkLines">Some Stuff Here</div>');
});
});
HTML:
<div id="sparkLineContainer">
<div class="sparkLines" id="id1">Some stuff here</div>
<div class="sparkLines" id="id2">Some stuff here</div>
<div class="sparkLines" id="id3">Some stuff here</div>
</div>
<button>Add Spark Line</button>
Actually I want to add class to all divs but with id1, id2, id3.
For example:
<div class="addclass" id="id1"></div>
<div class="addclass" id="id2"></div>
Hi you can do that using a counter on your function, Let me use Jquery on this.
function addDiv(){
var counter =0;
$('id').append('div id="' + counter +'"');
counter = counter + 1;
}
This should work.
Related
I have a problem concerning the use of .append("..."). I am coding a simple To-Do List and want to delete a list element when I click on the appended "REMOVE" button by reference to the buttons class.
I think it is not working because .append() isn't changing the html code of the website. At least I can't spot a difference after clicking the "ADD ITEM" button.
Do you have any ideas?
Thanks in advance!
var inputText;
var itemList = [];
$("#addButton").click(function(){
inputText = $("#textInput").val();
itemList.push(inputText);
$("#textInput").val("");
showItems();
});
//not working
$(".deleteButton").click(function(e){
console.log("test");
var className = e.attr("id");
console.log("ID:" + className);
});
function showItems(){
$("#list").html('');
for(var i=0; i<=itemList.length-1; i++){
$("#list").append('<div class="listelement"><p type="text" class="listItem" id="listItem '+ i +'">'+ itemList[i] +'</p> <button type="button" class="deleteButton" id="'+ i +'">REMOVE</button><div>');
}
}
<body>
<div class="container">
<div class="headline">
<h1 id="headline">TO DO LIST</h1>
</div>
<div class="userInput">
<input type="text" id="textInput">
<button type="button" id="addButton">ADD ITEM</button>
</div>
<div class="list" id="list">
<div class="listelement" id="listelement">
</div>
</div>
</div>
<script src="jquery-3.4.1.min.js"></script>
<script src="script.js"></script>
</body>
</html>
You need to use event delegation.
$(document).on("click",".deleteButton",function(e) {
$(this).closest(".listelement").remove()
});
$(".deleteButton").click(function(e){ will only work on those elements that exist on the page, but not on newly added elements.
var inputText;
var itemList = [];
$("#addButton").click(function() {
inputText = $("#textInput").val();
itemList.push(inputText);
$("#textInput").val("");
showItems();
});
//not working
$(document).on("click",".deleteButton",function(e) {
$(this).closest(".listelement").remove()
});
function showItems() {
$("#list").html('');
for (var i = 0; i <= itemList.length - 1; i++) {
$("#list").append('<div class="listelement"><p type="text" class="listItem" id="listItem ' + i + '">' + itemList[i] + '</p> <button type="button" class="deleteButton" id="' + i + '">REMOVE</button><div>');
}
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="container">
<div class="headline">
<h1 id="headline">TO DO LIST</h1>
</div>
<div class="userInput">
<input type="text" id="textInput">
<button type="button" id="addButton">ADD ITEM</button>
</div>
<div class="list" id="list">
<div class="listelement" id="listelement">
</div>
</div>
</div>
If you just want to remove that specific div where you are clicking you can use following code. You dont need to match id here.
$(document).on("click",".deleteButton",function(e){
let parent = $(this).closest(".listelement");
parent.remove();
});
But according to your code after delete if you add something, all the data of the array will show.Because you are not deleting data from array. I think you need to delete that data from the array too.
$(document).on("click",".deleteButton",function(e){
let parent = $(this).closest(".listelement");
let id = $(this).attr("id");
console.log(id);
itemList.splice(id, 1);
parent.remove();
});
The issue here is that the element appended doesn't have an event listener attached to it, when you're calling $(...).click it will attach an event listener only to the currently existing elements. Since you're calling it when the document loads and there are no elements with the class deleteButton at that time it won't do anything.
You can solve this by moving the deletion code to it's own function and attaching a click event listener for each new element you create.
In order to do so efficiently, you'll need to get the element you're creating, you can do this like so:
$(HTML Code).appendTo('#list').click(...);
This will create an element from the html you pass it, append it to the element with the id list and attach a click event listener to it, so in the end this will the result:
var inputText;
var itemList = [];
$("#addButton").click(function() {
inputText = $("#textInput").val();
itemList.push(inputText);
$("#textInput").val("");
showItems();
});
function deleteItem(e) {
console.log(e.target.id);
}
function showItems() {
$("#list").html('');
for (var i = 0; i <= itemList.length - 1; i++) {
var html = '<div class="listelement"><p type="text" class="listItem" id="listItem ' + i + '">' + itemList[i] + '</p> <button type="button" class="deleteButton" id="' + i + '">REMOVE</button><div>';
$(html).appendTo('#list').click(deleteItem);
}
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="container">
<div class="headline">
<h1 id="headline">TO DO LIST</h1>
</div>
<div class="userInput">
<input type="text" id="textInput">
<button type="button" id="addButton">ADD ITEM</button>
</div>
<div class="list" id="list">
<div class="listelement" id="listelement">
</div>
</div>
</div>
If you try to do something with the elements that are dynamically added to DOM using the jQuery click() method it will not work, because it bind the click event only to the elements that exist at the time of binding
you can use
$(document).on("click", "button.deleteButton" , function() {
$(this).parent().remove();
});
https://jsfiddle.net/82d0e5at/3/
I created a css class for 8 divs, I need to use the each function of jquery to count the divs and show the result in the page's html, example: "8 divs appear".
I created a code but it doesn't work, it doesn't show the result.
code:
<script>
$( ".class" ).each(function( index ) {
console.log( index + ": " + $( this ).text() );
});
</script>
if you just want to count them, you can do:
$('.class').length
From each() method to get whole same class divs index + content or You want to count how many divs has same class then simply use .length.
Note: Check on Full page. then you can see same class divs count result.
// Console inded with each div text.
$('.sameclass').each(function(index){
console.log(index +':'+ $(this).text());
});
//Count How many divs has (sameclass) class.
$('.result').text($('.sameclass').length);
<script type="text/javascript" src="https://code.jquery.com/jquery-3.4.1.min.js"></script>
<div class="sameclass">Text #1</div>
<div class="sameclass">Text #2</div>
<div class="sameclass">Text #3</div>
<div class="sameclass">Text #4</div>
<div class="sameclass">Text #5</div>
<div class="sameclass">Text #6</div>
<div class="sameclass">Text #7</div>
<div class="sameclass">Text #8</div>
<hr>
<p>Total divs has (sameclass): <strong class="result"></strong></p>
After a few attempts, I managed to solve the problem.
I created three codes and they worked and gave me the result I wanted. Thanks a lot for the help.
1.
var totalPageProducts;
jQuery('.products-grid .item').each(function(index, value) {
totalPageProducts = index + 1;
jQuery('.show-no').html('Showing '+ totalPageProducts +' products');
});
2.
jQuery(document).ready(function($) {
jQuery('.show-no').html('Showing '+ jQuery('.products-grid .item').length +' products');
});
3.
jQuery('.show-no').html('Showing '+ jQuery('.products-grid .item').length +' products');
Okay, once i see the answer to this, I will feel stupid. I'm certain of that.
I've created this exactly the way I want to before, but I am refactoring my code for a new version right now. I am trying to dynamically create collapsible sets in jQuery Mobile, but my html does not render right.
<div data-role="header">
<h2>Playground</h2>
</div>
<div data-role="content">
<div data-role="button" id="addprimary" data-inline="true">Add 5</div>
<div data-role="collapsible">
<h4>Collapsible</h4>
<form id="makecollapsible">
</form>
</div>
</div>
<div data-role="footer">
<h4>Please, no applause</h4>
</div>
</div>
<script>
$('#addprimary').on('click', function () {
Markup.Collapsible();
});
var Markup = new Object();
Markup.Collapsible = function () {
$('#makecollapsible')
.append($('<div>')
.attr({ 'data-role': 'collapsible-set', 'id': 'primary' })
);
for (i = 0; i < 5; i++) {
($('<div>')
.attr({ 'data-role': 'collapsible', 'data-content-theme': 'c',
'data-collapsed': 'true' })
.html('<h4>' + i +'</h4>'))
.appendTo('#primary');
}
}
</script>
Could somebody please take a look at this http://jsfiddle.net/c2jLY/ and tell me what I have wrong? My <div>s with data-role='collapsible' are not rendering as collapsibles, which is also having an effect on the HTML I am trying to put in them later on.
Help is appreciated, thanks!
Inside Markup.Collapsible function and at the end of it, add the below. For collapsible-set, you need to tell jQM that you're enhancing a .collapsibleset() and combine it with .trigger('create').
$('#makecollapsible').collapsibleset().trigger('create');
Demo
I forgot to mention that when appending items dynamically, call enhancement methods on parent element; doing so, will enhance children elements. Thus, you don't need to use .collapsible().trigger('create') for each collapsible appended.
what i show here is a simple one but working:
<script type="text/javascript">
//dynamically make 10 collapsible items and append them to the collapsible-set
var jj = "SUPER item added..";
$('[data-role="content"]').append('<div id="set" data-role="collapsible-set"></div>');
var count;
for (count=0; count < 10; count++) { // div id should be from id='c0' to 'c9'
$("#set").append('<div id="c' + count + '" data-role="collapsible">');
$("#c" + count.toString()).append('<h3>Adding element_' + count +'</h3>');
$("#c" + count.toString()).append(jj + 'count ' + count + '</div>');
}
// either one is tested working below:
// $('[data-role="content"]').trigger('create');
$( "#set" ).collapsibleset( "refresh" );
</script>
<script src="http://code.jquery.com/mobile/1.4.5/jquery.mobile-1.4.5.min.js"></script>
<link href="http://code.jquery.com/mobile/1.4.5/jquery.mobile-1.4.5.min.css" rel="stylesheet"/>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<body>
<!------------------------page 1 ListView template-->
<div data-role="page" id="page01">
<div data-role="header" data-theme="b" data-position="fixed">
<h2>-- DEMO -- </h2>
</div>
<div data-role="content" id="content">
</div>
</body>
I have problem in hide and show the div element.
In this scenario when user click on the year the respect content is shown.
Problem I want to inactive hyperlinking on respective year when it is opened.
The script and html is below;
for this I have tried .preventDefault(). but not got any success:
<script type="text/javascript" >
$(document).ready(function() {
$("div.new:gt(0)").hide();// to hide all div except for the first one
$("div[name=arrow]:eq(0)").hide();
// $("div.nhide:gt(0)").hide();
// $("a[name=new]").hide();
$("a[name=new]").hide();
$('#content a').click(function(selected) {
var getID = $(this).attr("id");
var value= $(this).html();
if( value == '<< Hide')
{
// $("#" + getID + "arrow").hide();
$("a[name=new]").hide();
$("#" + getID + "_info" ).slideUp('slow');
$("div[name=arrow]").show();
$("div.new").hide();
$(this).hide();
// var getOldId=getID;
// $("#" + getID ).html('<< Hide').hide();
}
if($("a[name=show]"))
{
// $("div.new:eq(0)").slideUp()
$("div.new").hide();
$("div[name=arrow]").show();
$("a[name=new]").hide();
$("#news" + getID + "arrow").hide();
$("#news" + getID + "_info" ).slideDown();
$("#news" + getID ).html('<< Hide').slideDown();
}
});
});
</script>
The html code is below:
<div id="content">
<div class="news_year">
<a href="#" name="show" id="2012">
<div style="float:left;" name="year" id="news2012year">**2012** </div>
<div style="float:left;" name="arrow" id="news2012arrow">>></div>
</a>
</div>
<div class="new" id="news2012_info">
<div class="news">
<div class="news_left">News for 2012</div>
</div>
<div class="nhide" ><< Hide </div>
</div>
<div id="content">
<div class="news_year">
<a href="#" name="show" id="2011">
<div style="float:left;" name="year" id="news2012year">2012 </div>
<div style="float:left;" name="arrow" id="news2012arrow">>></div>
</a>
</div>
<div class="new" id="news2011_info">
<div class="news">
<div class="news_left">News for 2011</div>
</div>
<div class="nhide" ><< Hide </div>
</div>
Fiddle
if i am understanding your problem,
event.preventDefault(); not works with all browser so if you are using other browser like IE
then use event.returnValue = false; instead of that.so you can detect your browser using javascript as
var appname = window.navigator.appName;
This is what I'm currently using in my projects to "disable" an anchor tag
Disabling the anchor:
Remove href attribute
Change the opacity for added effect
<script>
$(document).ready(function(){
$("a").click(function () {
$(this).fadeTo("fast", .5).removeAttr("href");
});
});
</script>
Enabling the anchor:
$(document).ready(function(){
$("a").click(function () {
$(this).fadeIn("fast").attr("href", "http://whatever.com/wherever.html");
});
});
Original code can be found here
Add a class called 'shown' to your wrapper element when expanding your element and remove it when hiding it. Use .hasClass('shown') to ensure the inappropriate conditional is never executed.
Surround the code inside of the click function with an if statement checking to see if a variable is true or false. If it is false, it won't run the code, meaning the link is effectively inactive. Try this..
var isActive = true;
if (isActive) {
// Your code here
}
// The place where you want to de-activate the link
isActive = false;
You could also consider changing the link colour to a grey to signify that it is inactive.
Edit
Just realised that you want to have multiple links being disabled.. the code above will disable all of them. Try the code below (put the if around the code in the click function)
if(!$(this).hasClass("disabled")) {
// Your code here
}
// The place where you want to de-activate the link
$("#linkid").addClass("disabled");
// To re-enable a link
$("#linkid").removeClass("disabled");
// You can even toggle the link from disabled and non-disabled!
$("#linkid").toggleClass("disabled");
Then in your CSS you could have a declaration like this:
.disabled:link {
color:#999;
}
I'm trying to show appropriate content using this method: determine id of the clicked div, than open div content with determined id + '-box'. But it doesn't work.
JQuery that doesn't work:
$(".portfolio-apps section").click(function() {
var currentID = '#' + $(this).attr('id');
console&&console.log(currentID);
var currentIDBox = currentID + "-box";
console&&console.log(currentIDBox);
$(currentID).click(function() {
$('.portfolio-entry-text').hide('fast');
var bcn = $(currentIDBox);
if ($('.box-content').is(':visible')) {
$('.box-content').hide();
bcn.show();
}
else {
$('.box-content').hide();
bcn.slideToggle(200);
}
});
});
Similar JQuery that is working:
$("#gterminal").click(function() {
$('.portfolio-entry-text').hide('fast');
var bcn = $('#gterminal-box');
if ($('.box-content').is(':visible')) {
$('.box-content').hide();
bcn.show();
}
else {
$('.box-content').hide();
bcn.slideToggle(200);
}
});
HTML
<div class="portfolio-apps clearfix">
<section class="button" id="gterminal">
<span>Google in Terminal</span>
</section>
<section class="button" id="MySQLToJSON">
<span>MySQL to JSON</span>
</section>
</div>
<div id="wrapper" >
<div class="box-content" id="gterminal-box">
<p>BOX 1</p>
</div>
<div class="box-content" id="MySQLToJSON-box">
<p>BOX 2</p>
</div>
</div>
You're binding a .click event internally, which means that the -box showing/hiding won't be triggered until a second click. This doesn't make sense to me. If you just remove the internal .click binding, it seems to work quite nicely:
http://jsfiddle.net/Th3wT/