I'm looking to cycle through the dom and add an ID attribute to an existing table element. Can't quite seem to get it working. Basicaly the code looks for a table that has a specific class, then adds an ID. More things will happen depending on the tables class but for the moment I'm stuck on adding the ID. Any help would be greatly appreciated.
$(document).ready(function () {
var chartTypeArray = [];
var i = 0;
// cycle tables add id and store class
$('table').each(function (i) {
if ($(this).hasClass('bar')) {
chartTypeArray.push('bar');
$(this).attr('ID', 'tableToChart' + i);
} //end bar
else if ($(this).hasClass('line')) {
chartTypeArray.push('line');
$(this).attr('ID', 'tableToChart' + i);
} //end line
else if ($(this).hasClass('area')) {
chartTypeArray.push('area');
$(this).attr('ID', 'tableToChart' + i);
} //end area
else if ($(this).hasClass('pie')) {
chartTypeArray.push('pie');
$(this).attr('ID', 'tableToChart' + i);
} //end pie
i++;
console.log('Table ' + i + ' is a ' + $(this).attr('class') + ' chart');
}); //end function
}); //end of document ready
try with lower case
$(this).attr('id', 'tableToChart' + i);
also you don't have to do
var i = 0; //outside the each loop
// and you don't need
i++; // inside the each loop
Related
I need some help with JQuery.
In my site I have a button that repeats in a layout. I decided to differentiate them by adding a class to each of them with a number with this code below which works very well.
jQuery(document).ready(function() {
// each button in the Machine loop get a unique CLASS
jQuery(".rv_button").each(function(i) {
jQuery(this).addClass("item" + (i + 1));
var its = ("item" + (i + 1));
console.log("." + its);
});
});
This button will be used to make appear or disappear a section that I also decided to differentiate them by adding a class to each of them with a number with this code below which works very well.
jQuery(".reveal").each(function(f) {
// each section in the Machine loop get a unique CLASS
jQuery(this).addClass("rive" + (f + 1));
var id = ("rive" + (f + 1)); // each section in the Machine loop get a unique CLASS
console.log("." + id);
});
I would like to create a code which has the function of when I click on item1 -> rive1 appears and disappears etc ...
here is my test code which does not work because I do not know how to include the variable included previously.
var id;
var its;
jQuery(document).ready(function() {
// The section is HIDE with the new class
jQuery("." + id).hide();
// The click function on the new button class
jQuery("." + its).click(function(e) {
// when i click on the new class button, the section appaear or desapear.
e.preventDefault();
jQuery("." + id).slideToggle();
jQuery("." + its).toggleClass('opened closed');
});
});
Any idea on how to passing the Variable into the last function ?
thanks all !
This the entire code :
jQuery(document).ready(function() {
// each button in the Machine loop get a unique CLASS
jQuery(".rv_button").each(function(i) {
jQuery(this).addClass("item" + (i + 1));
var its = ("item" + (i + 1));
console.log("." + its);
});
jQuery(".reveal").each(function(f) {
// each section in the Machine loop get a unique CLASS
jQuery(this).addClass("rive" + (f + 1));
var id = ("rive" + (f + 1)); // each section in the Machine loop get a unique CLASS
console.log("." + id);
});
var id;
var its;
jQuery(document).ready(function() {
// The section is HIDE with the new class
jQuery("." + id).hide();
// The click function on the new button class
jQuery("." + its).click(function(e) {
// when i click on the new class button, the section appaear or desapear.
e.preventDefault();
jQuery("." + id).slideToggle();
jQuery("." + its).toggleClass('opened closed');
});
});
});
I have a function that Creates new items and allows you to Delete, Update and Save the inputs on these items using localStorage
However, if I have more than one item and then update and save the changes, those changes are applied over all items.
The problem is encountered at the $(".save").click(function() but I'm not sure I have set up my .items with a proper array.
Since I use localStorage the working code can be found in the pen below:
https://codepen.io/moofawsaw/pen/NoBQKV
window.localStorage.clear();
//create localStorage item
if (!localStorage.getItem("_storage")) {
localStorage.setItem("_storage", "");
}
//set data to localStorage function
function saveData() {
localStorage.setItem("_storage", $("#content").html());
}
// Open the create dialgoue:
$(".add").on("click", function() {
$(".create").toggle();
});
//Save the entered inputs and post the item:
$(".post").click(function() {
var id = $(".createtext").val();
var createtitle = $(".createtitle").val();
var item = "";
if (id[0]) {
for (var i = 0; i < id.length; i++) {
item += "<div>" + id[i] + "</div>";
}
} else {
item = "<div>Click update to add a card</div>";
}
$("#content").append(
'<div class="item">' +
'<div class="title">' +
createtitle +
"</div>" +
"<div class='text'>" +
id +
"</div>" +
'<button class="delete">Delete</button>' +
'<button class="update">Update</button>' +
"</div>"
);
$(".createtitle").val("");
$(".createtext").val("");
$(".create").toggle();
saveData();
});
//Close out of creating a new item
$(".close").click(function() {
$(".createtitle").val("");
$(".createtext").val("");
$(".create").toggle();
});
//Get inputs and open edit window to update the items:
$("#content").on("click", ".update", function() {
var item = $(this).closest(".item");
$(".updatetext").val(
$(this)
.closest(".item")
.find(".text")
.text()
);
$(".updatetitle").val(
$(this)
.closest(".item")
.find(".title")
.text()
);
$(".edit").toggle();
});
//Save changes and update the items (error:changes all items when clicked):
$(".save").click(function() {
var id = $(".updatetext").val();
var title = $(".updatetitle").val();
var item = "";
if (id[0]) {
for (var i = 0; i < id.length; i++) {
item += "<div>" + id[i] + "</div>";
}
} else {
item = "<p>Click edit to add a card</p>";
}
$(".item").each(function() {
$(this).html(
'<div class="title">' +
title +
"</div>" +
"<div class='text'>" +
id +
"</div>" +
'<button class="delete">Deleted(2)</button>' +
'<button class="update">Updated(2)</button>'
);
});
$(".updatetext").val("");
$(".updatetitle").val("");
$(".edit").toggle();
saveData();
});
//Discard any of these changes:
$(".discard").click(function() {
$(".updatetext").val("");
$(".updatetitle").val("");
$(".edit").toggle();
});
//Delete an item:
$("#content").on("click", ".delete", function() {
$(this)
.closest(".item")
.remove();
saveData();
});
$(function() {
if (localStorage.getItem("_storage")) {
$("#content").html(localStorage.getItem("_storage"));
}
});
Point is, you call .each() in your update callback.
$(".item").each(function() {
$(this).html(
'<div class="title"> ....'
);
});
This literally means "Find all DOM elements with item class and replace their contents with given html.
But you need to replace contents of the one specific element, on which Update button was clicked. To do so, you need to persist that element somehow.
One of the ways to do that with minimum changes to your code - introduce a variable in a scope available for both update and save functions. But in your case it would be a global variable, and those are not generally a good idea.
So I'd suggest to wrap all your code into a function (like $(function() {});.
Then you can introduce a local variable:
$(function () {
// define it
var $selectedItem;
// assign a value in the update click callback
$('#content').on('click', '.update', function () {
$selectedItem = $(this).closest('.item');
// ...
});
// read the value in the save click callback
$('.save').click(function () {
// ...
$selectedItem.html('...');
// ...
});
});
Example: https://codepen.io/anon/pen/GzXaoV
I want to assign dynamic id attributes to the div(s) which are being appended through JavaScript. For example:
function x() {
for (current_list = 0; current_list < data.length; current_list++) {
$("#current").append(
"<div class="card">" +
"" + data[current_list].name + "" +
"</div>");
}
}
Two cards will be appended, so I want to assign them an id which can increase if there are more numbers of arrays present in the JSON.
you probably looking for this.
function x() {
var container=$("#current");
for(var i=1;i<10;i++)
{
var id="card"+i;
var divHtml="<div class='"+id+"'>" +
""+data[current_list].name+"" +
"</div>"
container.append(divHtml);
}
}
As Rory said, here a solution using DOM traversal.
You would have to call this after appending your "cards".
$(".card").each(function(value, index){
$(value).attr("id", "card" + index);
});
if you call x() function one time you can use
function x() {
for (current_list = 0; current_list < data.length; current_list++) {
$("#current").append('<div id="card-'+current_list+'" class="card">' + data[current_list].name + '</div>');
}
}
and if you call it many time you can use this function after every call
$(".card").each(function(value, index){
$(value).attr("id", "card-" + index);
});
below is the js code for wikipedia search project. I am getting infinite for loop even though it had condition to stop repeating the loop. I am stuck in this problem.
$(document).ready(function() {
$('.enter').click(function() {
var srcv = $('#search').val(); //variable get the input value
//statement to check empty input
if (srcv == "") {
alert("enter something to search");
}
else {
$.getJSON('https://en.wikipedia.org/w/api.php?action=opensearch&search=' + srcv + '&format=json&limit=20&callback=?', function(json) {
$('.content').html("<p> <a href ='" + json[3][0] + "'target='_blank'>" + json[1][0] + "</a><br>" + json[2][0] + "</p>");
/*for loop to display the content of the json object*/
for (i = 1; i < 20; i++) {
$('p').append("<p><a href ='" + json[3][i] + "'target='_blank'>" + json[1][i] + "</a>" + json[2][i] + "</p>");
}
});
}
});
});
You are appending to each and every one of <p> in page.
Since your for loop appends even more <p> (and you possibly have a high number of <p> elements in your page beforehand) you overflow your call stack.
You probably wanted to append to a specific <p>. Try giving an id to your selector.
from what i can see in the url you need to do the following:
loop over the terms found and select the link based on the index of the element, chose a single element .contentto append the data not a set of elements p, this will increase the number of duplicated results
$.getJSON('https://en.wikipedia.org/w/api.php?action=opensearch&search='+srcv+'&format=json&limit=20&callback=?', function(json){
$.each(json[1],function(i,v){
$('.content').append("<p><a href ='"+json[2][i]+"'target='_blank'>"+json[0]+"</a>"+v+"</p>");
});
});
see demo: https://jsfiddle.net/x79zzp5a/
Try this
$(document).ready(function() {
$('.enter').click(function() {
var srcv = $('#search').val(); //variable get the input value
//statement to check empty input
if (srcv == "") {
alert("enter something to search");
}
else {
$.getJSON('https://en.wikipedia.org/w/api.php?action=opensearch&search=' + srcv + '&format=json&limit=20&callback=?', function(json) {
$('.content').html("<p> <a href ='" + json[3][0] + "'target='_blank'>" + json[1][0] + "</a><br>" + json[2][0] + "</p>");
/*for loop to display the content of the json object*/
var i = 1;
for (i; i < 20; i++) {
$('p').append("<p><a href ='" + json[3][i] + "'target='_blank'>" + json[1][i] + "</a>" + json[2][i] + "</p>");
}
});
}
});
});
I'm trying to limit inserting elements to the page:
<script type="text/javascript">
$(function() {
var i = 1;
//allow only 3 elements
if (i < 4) {
$('#add').click(function() {
var add_input = '<input type="file" />'
var add_link = 'Remove'
$('body').append('<p>' + add_input + add_link + '</p>');
});
i++;
}
$('.remove').live('click', function() {
$(this).parent('p').remove();
});
});
</script>
But I can still add element a lot more than 4.
You need to check your variable i within your event handler.
$('#add').click(function() {
if(i < 4){
var add_input = '<input type="file" />'
var add_link = 'Remove'
$('body').append('<p>' + add_input + add_link + '</p>');
i++;
}
});
And you should decrease i within your live() handler.
See a working example : http://jsfiddle.net/CtGgg/
You could count the number of elements already on the page and limit it that way. Personally, I like treating the DOM itself as the canonical representation of user state. If that's important to you, you could do something like the following, even though it's a little less performant:
$('#add').live('click', function (evt) {
if ($('input[type=file]').length < 4) {
$('body').append('<p><input type="file"> Remove</p>');
}
evt.preventDefault();
});