Get the both "ID" and "HREF" attributes and create a JSON object - javascript

I have a dinamically generated code as follows which lists some files and let the user delete them by clicking on their links:
<div id="filenames">
<div>
<a id="1" class="delete" href="#1984.xls">1984.xls
</div>
<div>
<a id="2" class="delete" href="#1984.xml">1984.xml
</div>
</div>
Each file has its ID. The list is generated via AJAX when the user uploads the files.
When the user clicks a link, before the file is passed to the "delete.php" call, I would like to have a JSON object that lists all the files like this:
{1 : 1984.xls, 2 : 1984.xml}
I managed to made it using an array
var files = [];
$('#filenames').find('a').each(function() {
files.push($(this).attr('href'));
});
But this simply adds to the array the name of the file which is stored inside href.
I don't know how to find both id and attr and create instead of an array a JSON object as said above.

You can do it in following way:
var files = {};
$('#filenames').find('a').each(function() {
files[$(this).attr('id')] = $(this).attr('href');
});
console.log(files);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
<div id="filenames">
<div>
<a id="1" class="delete" href="#1984.xls">1984.xls
</div>
<div>
<a id="2" class="delete" href="#1984.xml">1984.xml
</div>
</div>

You have to create an object using {} (and not array []) then affect the key:value to it as files[key] = value when the key is the id of the link and value represented by the href, check the example below.
Hope this helps.
var files = {};
$('#filenames').find('a').each(function() {
var key = $(this).attr('id');
var value = $(this).attr('href');
files[key] = value;
});
console.log(files);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="filenames">
<div>
<a id="1" class="delete" href="#1984.xls">1984.xls
</div>
<div>
<a id="2" class="delete" href="#1984.xml">1984.xml
</div>
</div>

Use bracket-notation to assign value to the object when key is dynamic!
Initialize files as object({}), not as array as you are expecting result as an object
Note: Use .substr(1); if you are suppose to remove #(first character) from string.
var files = {};
$('#filenames').find('a').each(function(i) {
//files[i] = $(this).attr('href').substr(1);;//For index iteration as key
files[this.id] = $(this).attr('href').substr(1); //For ID attribute as key
});
console.log(files);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
<div id="filenames">
<div>
<a id="1" class="delete" href="#1984.xls">1984.xls</a>
</div>
<div>
<a id="2" class="delete" href="#1984.xml">1984.xml</a>
</div>
</div>

Please try this code
var files = [];
item = {}
$('#filenames').find('a').each(function () {
item[$(this).attr('id')] = $(this).attr('href');
});
files.push(item);
console.log(files);

Related

Compare dynamic value with Comma separated attibute value

Please suggest how can I compare page Url Value inside all anchors element using Jquery.
<div class="sidebar">
<a class="button" module="Users" page-actions="user/edit,user/create,user/list" href="user/index">User</a>
<a class="button" module="Users" page-actions="" href="user/Demo">Demo</a>
<a class="button" module="" page-actions="" href="/">Dashboard</a>
</div>
Suppose my page Url is user/edit I want to access the element where page-actions attribute is equal to the page Url.
Use jQuery filter() and parse the page actions to array and compare to the window.location.pathname
/** for demo only since demo url doesn't match */
var pageUrl ='http://example.com/user/edit';
var pagePath = new URL(pageUrl).pathname;
$('.sidebar a[page-actions]').filter(function(){
var actionArray = $(this).attr('page-actions').split(',');
return actionArray.includes( pagePath.slice(1));
// on live site use:
// return actionArray.includes('/' + location.pathname.slice(1));
}).css('color','red')
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="sidebar">
<a class="button" module="Users" page-actions="user/edit,user/create,user/list" href="user/index">User</a>
<a class="button" module="Users" page-actions="" href="user/Demo">Demo</a>
<a class="button" module="" page-actions="" href="/">Dashboard</a>
</div>

Trying to set a VAR to be the name of a DIV

So I have a DIV with a name assigned to it (actually the database Id). I'm trying to on click, set a new VAR to be the name of that div (going to use it for a PUT request).
When I log the following it comes back as undefined?
This is the HTML
<div class="deleterow" id='removerow' name="${product._id}">
<img src="images/icons/icon-delete.png" alt="delete button" />
</div>
This is the JS
$(document).on('click', '#removerow', function() {
let id = this.name;
console.log(id); //undefined
});
If I change this.name to just this, it logs the information with the name correctly as below, so I know it's pulling the product._id correctly.
$(document).on('click', '#removerow', function() {
let id = this;
console.log(id);
});
This will log;
<div class="" id="removerow" name="5bfcbf1d181c4573f089a24c">
<img src="images/icons/icon-delete.png" alt="delete button">
</div>
Try with jQuery's .attr():
Get the value of an attribute for the first element in the set of matched elements or set one or more attributes for every matched element.
$(document).on('click', '#removerow', function() {
let id = $(this).attr('name');
console.log(id);
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="" id="removerow" name="5bfcbf1d181c4573f089a24c">
<img src="images/icons/icon-delete.png" alt="delete button">
</div>
OR: You can also use vanilla JavaScript's getAttribute():
getAttribute() returns the value of a specified attribute on the element. If the given attribute does not exist, the value returned will either be null or "" (the empty string); see Notes for details.
$(document).on('click', '#removerow', function() {
let id = this.getAttribute('name');
console.log(id);
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="" id="removerow" name="5bfcbf1d181c4573f089a24c">
<img src="images/icons/icon-delete.png" alt="delete button">
</div>

Dynamically create a class name in Javascript

I have some code in PHP file that creates a button and the target of that button is a DIV (findOptionsBox).
The button gets repeated multiple times on the page and so the target of each button should be a unique DIV Id.
<button type="button" id="myBtn" class="btn" data-toggle="collapse" data-
target="#findOptionsBox">
......
</button>
<div id="findOptionsBox" class="search-box collapse">
......
<div>
So my question is how to make 'findOptionsBox' a variable that can be supplied to the data-target of each myBtn and the same variable can also be the ID of the corresponding div.
I am looking to end up with something like this:
......
<div id="findOptionsBox_1" class="search-box collapse">
......
<div>
......
<div id="findOptionsBox_2" class="search-box collapse">
......
<div>
I need the btnIds and the DivIds to be unique and each btnId to refer to the corresponding DivId.
I am looking to do this in Javascript and am trying something like:
<script type="application/javascript">
$(function(){
var count = 0;
count++;
});
</script>
Thanks.
https://jsfiddle.net/sudarpochong/0hx4mLaw/1/
Create a div to contain options box (#options-container)
Clone #findOptionsBox and change the id
Insert into #options-container
Code:
var PREFIX_ID = "findOptionsBox_";
$("#myBtn").click(function(e) {
$("#options-container").empty();
var totalOptions = $("#numberOfOptions").val();
for (var i=0; i<totalOptions; i++) {
var newBox = $("#findOptionsBox").clone();
newBox.attr("id", PREFIX_ID + i);
newBox.appendTo("#options-container");
newBox.show();
}
e.preventDefault();
});

getElementByID for Dynamically generated ID Elements

I am having an issue with getting the value of an ID element of the item that is dynamically generated from the data obtained from the database. I have a query SELECT ItemID, ItemName, ItemImageName FROM Items. Than I have the following code that will generate ID for each <div> for all rows returned from the database by concatenating the value of ItemID to each ID name.
for ($i=0; $i <$numrows; $i++) {
$stmt->fetch()
<div> <img class="itemImage" id="Image" .$ItemID src=/images/itemImage . $itemID> $ItemID </div>
<div id= "ItemID" .$ItemID> $ItemID </div>
<div id= "ItemName" .$ItemID> $ItemName" </div>
}
This should return a similar result to this for an item with ItemID=002:
<div> <img class="itemImage" id=Image002 src=/images/Image002 > </div>
<div id= ItemID002> 002 </div>
<div id= ItemName002> SomeNameOfItem002" </div>
Then I want to be able to click an image with an ID=Image002 and I want to get a value of ItemID with the getElementById("ItemID").innerHTML. I have the following code:
var itemID = document.getElementById("ItemID").innerHTML;
$( ".itemImage" ).click(function() {
var itemID= document.getElementById("ItemID").innerHTML;
console.log(itemID);
This however returns itemID as undefined. Any help would be greatly appreciated!
<div> <img class="itemImage" id=Image001 src="/images/Image001"> </div>
<div id=ItemID001> 001 </div>
<div id=ItemName001> SomeNameOfItem001" </div>
<div> <img class="itemImage" id=Image002 src="/images/Image002"> </div>
<div id=ItemID002> 002 </div>
<div id=ItemName002> SomeNameOfItem002" </div>
<div> <img class="itemImage" id=Image003 src="/images/Image003"> </div>
<div id=ItemID003> 003 </div>
<div id=ItemName003> SomeNameOfItem003"> </div>
<script>
$(document).ready(function () {
$(".itemImage").click(function () {
var imgID = $(this).prop('id').replace("Image", "");
// you can directly use value imgID variable if its same. or you
//can use from ItemID inner html
var yourValue = $("#ItemID" + imgID).html();
alert(yourValue);
})
});
</script>
getElementById("ItemID").innerHTML returns undefined, because it is undefined. The correct id is ItemID002. You need to be able to tell which it is.
First, change your PHP to create HTML like this.
<div id="ItemID002" onclick="clicked(002)" />
Then, go to your Javascript and create this function.
function clicked(id){
var itemID= document.getElementById("ItemID"+id).innerHTML;
console.log(itemID);
}
Lastly, you're PHP creates <div id="ItemID"002>, you need to fix that by changing it from <div id= "ItemID" .$ItemID> $ItemID to <div id='ItemID.$itemId'>
EDIT: Also, I'd like to point out that in some places in your example, you forgot to use quotes when specifying the value of an attribute in HTML. I would recommend you fix that.
Good luck!
Alternatively you can achieve this by javascript only. So you don't need to change markup or PHP.
Here is a sample fiddle https://jsfiddle.net/L3bwfyve/
The key part is extraction of part of id of clicked element:
var itemIdPart = e.target.id.substr(5);
Be sure to check for nulls in e.target id etc...
Personally I would consider this solution a bit hacky... but you ask for javascrit, you get it ;-)

How iterate a jQuery function for each slide in a slider?

Summary: The purpose of this is to display a 3-part slider that users can click through, and they can use the index on each slide to filter the cards on that slide to a specific topic. The filters are working fine, but there's a problem in the JavaScript when it populates the indices: it's populating an index for all 3 cards, and showing that large index on each slide. Instead, the index for each slide needs to be unique, and only contain the hashtags from the cards in that same slide. I really want to avoid duplicating code for the different slides.
HTML
The following HTML has 3 (li) slides. Each slide contains a visible index (.hashtag-list), and one or more article cards (.item). Each (.item) besides the first one contains a hidden input with one or more hashtag values.
<li class="trend-cards">
<div class="card-items">
<div class="item trendingtopiccardblock">
<div class="hashtag-list"></div>
</div>
<div class="item">
<input class="tags" type="hidden" value="TopicA,TopicB"/>
</div>
<div class="item">
<input class="tags" type="hidden" value="TopicC"/>
</div>
</div>
</li>
<li class="trend-cards">
<div class="card-items">
<div class="item trendingtopiccardblock">
<div class="hashtag-list"></div>
</div>
<div class="item">
<input class="tags" type="hidden" value="TopicC, TopicD"/>
</div>
<div class="item">
<input class="tags" type="hidden" value="TopicA,TopicC,TopicD"/>
</div>
</div>
</li>
<li class="trend-cards">
<div class="card-items">
<div class="item trendingtopiccardblock">
<div class="hashtag-list"></div>
</div>
<div class="item">
<input class="tags" type="hidden" value="TopicA, TopicD"/>
</div>
<div class="item">
<input class="tags" type="hidden" value="TopicB,TopicC,TopicD"/>
</div>
</div>
</li>
JavaScript
The following jQuery pulls the values from the .tags classes, stores them in an array, removes duplicates, sorts them, and then populates the HTML in a callback. (Ignore the countryButtons and countries array, as that's not relevant.)
populateHashtagList: function() {
var $cards = $(".card-items .tags");
var list = [];
var $countryButtons = $('.card-filtering li .country-filtering');
var countries = [];
$countryButtons.each(function() {
countries.push(this.firstChild.data.replace("#", "").toLowerCase());
});
//Get tag values, set to lowercase and store in List array
$cards.each(function() {
var tags = getTags($(this).val());
$(tags).each(function (index, value) {
var tagValue = value.toLowerCase();
if($.inArray(tagValue, countries) === -1) list.push(value);
});
});
//Remove duplicates from the array
var uniqueTags = [];
$.each(list, function(i, el){
if($.inArray(el, uniqueTags) === -1) uniqueTags.push(el);
});
uniqueTags.sort();
function getTags(parameter) {
var arr = parameter.split(',');
return arr;
}
//Populate hash-tag List
var hashtagList = $('.hashtag-list');
populateHashtagList();
function populateHashtagList(callback) {
$.each(uniqueTags, function(i, el){
var htmlToInsert = '<span class="active">' + el + '</span>';
hashtagList.append(htmlToInsert);
});
if(typeof callback == "function")
callback();
}
}
What I've tried
Isolating the function using a $(".trend-cards").each function. This resulted in the same large list, but it was tripled on each slide.
Adding more specific paths to the .tags selectors, which changed nothing.
Using a parent selector once the .tags variable is set, and calling the remainder of the function from there. No hashtags populate in this case.
I appreciate any feedback and input on this. I want to learn how to do this better in the future. Thank you very much!
Wrapping this code in .each() function is the best solution here. You said you tried that and you probably forgot to specify parent element for cards and hashtag-list selectors.
Here is a working example: https://jsfiddle.net/k3oajavs/
$(".trend-cards").each(function(){
var $cards = $(".card-items .tags", this);
// ...
var hashtagList = $('.hashtag-list', this);
});

Categories