Just trying to access a value in an a element - javascript

I've got multiple a elements, that are generated on the page view by a for loop that when they are clicked, send an ajax post to the database, to mark the item in the database by its id, that is equal to the value in the a element but my code is not working, anybody have any insight on why? Thanks.
<a href='#' value='(loaded from database)' id='markAsRead'>
var element = document.getElementById('markAsRead');
element.addEventListener('click', function() {
alert(this.value);
});

Anchors don't have values like inputs do, you should use a data-attribute
<a href='#' data-value='(loaded from database)' id='markAsRead'>
var element = document.getElementById('markAsRead');
element.addEventListener('click', function() {
alert(this.getAttribute("data-value"));
});

the id attribute must be unique.
if you want to have a group of controls with the same identifier you can use the name attribite.
if you look at the functions for dom manipulation:
document.getElementById() - Element (singular)
document.getElementsByName() - Elements (plural)
An example of adding a unique (depending on circumstances) id
for (var index = 0; index < 10; index++) {
var element = document.createElement("a");
element.setAttribute("data-value", "your value");
element.setAttribute("id", "markAsRead_" + index);
element.addEventListener('click', function() {
alert(this.getAttribute("data-value"));
});
document.getElementsByTagName("body")[0].appendChild(element);
}

Related

Having trouble setting an element's onclick attribute with jQuery

I have a few elements on my webpage that share the class name "table-data". I am trying to loop through them and give each one of them a unique id, then I want all them to have the same onclick attribute. I was able to successfully give each one of them a unique id with pure JavaScript, but the part that I am having trouble with is giving them all the same onclick attribute. I tried with JavaScript and jQuery and failed using both.
Here is my code:
// this counter will be used to give each element a unique id
var counter = 0;
// x holds all elements with the class name "table-data"
var x = document.getElementsByClassName("table-data");
// loop through all the elements in the array x
for (var i = 0; i < x.length; i++) {
// give each element the name "idNum" plus whatever number the counter variable holds
var idName = 'idNum' + String(counter);
// set the id name to the variable defined above
x[i].setAttribute('id', idName);
// here is the part I am struggling with, this section is supposed to alert the id of the element when it is clicked
$('#' + idName).click(function () {
alert(idName);
});
// increment the counter
counter += 1;
The problem I am having is that all elements are showing the idName of the last element in the array "x". so if there are 5 elements in total and I run this code on them, they will all show the idName of the 5th element when clicked. I tried to alert() the idName outside of the onclick function and make it so the loop will alert the idName of each element as soon as it is assigned and that worked just fine. I would get five different ids for five different elements, so what is causing the problem inside the onclick function?
I also tried the following and it didn't work either:
x[i].setAttribute('onclick', 'call_alert(this.idName)');
function call_alert(clickedId) {
alert(clickedId);
}
I am very new to web programming so I am sorry if there are any obvious mistakes in my code.
You're making this much more complicated than your need to. You don't need to add an id to every element, you can simply bind on a class using the class(.) selector and then add the click binding all in one go:
$(document).ready(function() {
//match on the class
$('.table-data').click(function(){
//access the actual element clicked using $(this)
alert('clicked'+ $(this).text());
});
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
1
2
You won't need counter variable as you're already i:
//var counter = 0;
var x = document.getElementsByClassName("table-data");
for (var i = 0; i < x.length; i++) {
var idName = 'idNum' + String(i);
x[i].setAttribute('id', idName);
x[i].onclick = function() {
console.log(this.id);
}
//counter += 1;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="table-data">table1</div>
<div class="table-data">table2</div>
<div class="table-data">table3</div>
<div class="table-data">table4</div>
<div class="table-data">table5</div>
<div class="table-data">table6</div>
jQuery version:
$(".table-data").each((idx, element) => {
$(element).attr("id", "idNum" + String(idx));
$(element).on("click", () => {
console.log($(element).attr("id"));
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="table-data">table1</div>
<div class="table-data">table2</div>
<div class="table-data">table3</div>
<div class="table-data">table4</div>
<div class="table-data">table5</div>
<div class="table-data">table6</div>

get the all the id's from a class when the image is selected

I have few uploaded images in one div and I want to move them to another div and update the database table. For that I need the id's of the images selected and the name of the div where I want to move.
I have the id of the selected image using the check box but I am not sure how can I get all id's in the end .
function MoveImages(){
for ( var i = 0; i < $(".ct input[type=checkbox]:checked").length; i++) {
var element = $(".ct input[type=checkbox]:checked")[i];
var parent = element.parentNode;
var id = parent.getAttribute('id');
}
}
how can I get all the id's in the end ?
This is how my class looks like.
<div class="ct" id="559429bc0d559162552c9728">
<input type="checkbox" class="remove">
<img src="/image?id=c9728" data-src="random.JPG" id="previewImagec9728">
</div>
the move function should return all the id's.
With a bit of JQuery's $.each, substring, and JS array methods, you can grab the raw IDs and put them in an array like so:
var ids = [];
//For each element that matches ".ct input[type=checkbox]:checked".
$.each($('.ct input[type=checkbox]:checked'), function() {
//Find the image element, get the id value, and strip the first 12 characters.
var id = $(this).find('img').attr('id').substring(12);
//Put ID in array.
ids.push(id);
});
Use $.map():
var yourIds = $(".ct input[type=checkbox]:checked").map(function(){
return $(this).parent().attr('id');
});
Try jquery's each:
$('.ct').each(function() {
var id = $(this);
})
use :has and .map
$('.ct:has(:checked)').toArray().map(function(element, index) { return element.id })
or
$('.ct:has(:checked)').map(function(index, element) { return element.id }).toArray()
in both cases .toArray() is to get a normal array instead of a jquery array

JavaScript get h1 elements in HTML document and update unique IDs

I have a legacy html document containing h1 elements which don't have ids.
What I would like to achieve is to be able, using JavaScript, to get all h1(s) and then add to each a unique ID.
I have searched but could not find a solution that works.
Try getting all of them with document.getElementsByTagName("h1"). Loop through them, check if they have an id, and work appropriately. Try:
var h1s = document.getElementsByTagName("h1");
for (var i = 0; i < h1s.length; i++) {
var h1 = h1s[i];
if (!h1.id) {
h1.id = "h1" + i + (new Date().getTime());
}
}
DEMO: http://jsfiddle.net/kTvA2/
After running the demo, if you inspect the DOM, you'll see 3 out of the 4 h1 elements have a new, unique id. The one with the id in the first place isn't changed.
Note that this code needs to run after all elements are ready/rendered, which can be achieved by putting the code inside of a window.onload handler. The demo provided is set up to implicitly run the code then.
UPDATE:
With jQuery, you could use:
$(document).ready(function () {
$("h1:not([id])").attr("id", function (i, attr) {
return "h1" + i + (new Date().getTime());
});
});
DEMO: http://jsfiddle.net/kTvA2/7/
Use querySelectorAll() to get all of your header elements, then iterate over the result and generate yor unique id for each element.
var headerElements = document.querySelectorAll('h1');
for(h in headerElements) {
if(headerElements[h] instanceof Element) {
headerElements[h].id=uniqueIDgenerator();
}
}

Getting current URL with JavaScript then using derived value in html code

I have a simple question, but being a JavaScript newbie, I have no idea how to implement my findings.
I found a little snippit that uses JavaScript to pull in the current URL, and load that value to a variable:
<script type="text/javascript" language="javascript">
window.onload = function () {
var currentUrl = window.location.href;
}
</script>
so the value of currentUrl holds the current page's URL.
What I need to know is how to use that value within my page's HTML. The application I am attempting to use this for is the facebook comments plugin.
<div class="fb-comments" data-href="**currentUrl**" data-width="470" data-num-posts="2"></div>
Give your div an id:
<div id="fb-comments" class="fb-comments"
Then you can set the data-href like this:
window.onload = function () {
var currentUrl = window.location.href;
document.getElementById("fb-comments").setAttribute("data-href", currentUrl);
}
In this particular question, I think:
// gets all elements of class-name 'fb-comments' from the document
var fbComments = document.getElementsByClassName('fb-comments');
// iterates through each of those elements
for (var i = 0, len = fbComments.length; i<len; i++) {
// and sets the 'data-href' attribute to be the value held by the
// the currentUrl variable
fbComments[i].setAttribute('data-href', currentUrl);
}
For browsers that don't implement getElementsByClassName():
// gets all div elements within the document
var divs = document.getElementsByTagName('div');
// iterates through each of those div elements, and
for (var i = 0, len = divs.length; i<len; i++) {
// if the class attribute contains a string equal to 'fb-comments'
if (divs[i].className.indexOf('fb-comments') !== -1) {
// sets the 'data-href' attribute to be equal to the value held
// by the currentUrl variable
divs[i].setAttribute('data-href', currentUrl);
}
}
References:
getElementsByClassName().
getElementsByTagName().
setAttribute().
You might be able to do something like this -
<div id="myCommentBox" class="fb-comments" data-href="**currentUrl**" data-width="470" data-num-posts="2"></div>
var element = document.getElementById('myCommentBox');
element.setAttribute("data-href", currentUrl);
Notice that I gave the <div> an id attribute so that it would be easy to locate with getElementById. Remember that you'll need to call FB.XFBML.parse() once you change the data-href attribute in order to re-render the comment box.

get element after page loads

how do i call a function to count the number of divs with an id of 'd1' after the page loads. right now i have it in my section but doesnt that execute the script before anything in the loads? because it works if i put the code below the div tags...
Firstly there should be at most one because IDs aren't meant to be repeated.
Second, in straight Javascript you can call getElementById() to verify it exists or getElementsByTagName() to loop through all the divs and count the number that match your criteria.
var elem = document.getElementById("d1");
if (elem) {
// it exists
}
or
var divs = document.getElementsByTagName("div");
var count = 0;
for (var i = 0; i < divs.length; i++) {
var div = divs[i];
if (div.id == "d1") {
count++;
}
}
But I can't guarantee the correct behaviour of this because like I said, IDs are meant to be unique and when they're not behaviour is undefined.
Use jQuery's document.ready() or hook up to the onLoad event.
well an ID should be unique so the answer should be one.
you can use <body onload='myFunc()'> to call a script once the DOM is loaded.
You need to have the function tied to the onload event, like so:
window.onload = function() {
var divElements = document.getElementById("d1");
var divCount = divElements.length;
alert(divCount);
};
For the record, you should only have one div with that ID, as having more than one is invalid and may cause problems.

Categories

Resources