javascript getElementsByClassName not working with <select> [duplicate] - javascript

This question already has answers here:
How to use getElementsByClassName in javascript-function? [duplicate]
(3 answers)
Closed 8 years ago.
I am trying to use getElementsByClassName to make my select's options jump to their URL's depending on the value:
http://www.example.com/?page_id="value"
Here's what I've done: http://jsfiddle.net/VvLXk/2/
But it's not working.
I know I can use the getElementByID but I have three select elements (and I might add more). I believe it only applies to one element. And for that reason I have resorted to getElementsByClassName which is not working.
What is wrong with my code? Javascript / JQuery solutions are welcome.

As discussed in How to use getElementsByClassName in javascript-function?, getElementsByClassName() provides a collection of elements. To assign an event handler, you'll have to iterate over it and modify each individual element.
for (var i = 0, l = dropdown.length; i < l; i++) {
dropdown[i].onchange = onCatChange;
}
Along with that, you can then reference the single dropdown that the event was triggered for with this inside the handler function.
function onCatChange() {
if ( this.options[this.selectedIndex].value > 0 ) {
// etc.
}
}
Modified fiddle: http://jsfiddle.net/jLLHH/ (note: logs rather than redirecting)

This question has been answered here : How to use getElementsByClassName in javascript-function?
http://jsfiddle.net/VvLXk/9/ here is a sample of it working :
var dropdown = document.getElementsByClassName("page-dropdown")[0];
function onCatChange()
{
if ( dropdown.options[dropdown.selectedIndex].value > 0 )
{
location.href = "http://www.example.com/?page_id="+dropdown.options[dropdown.selectedIndex].value;
}
}
dropdown.onchange = onCatChange;

What you are selecting will return array, please try this:
var dropdown = document.getElementsByClassName("page-dropdown");
function onCatChange()
{
alert(dropdown[0]);
if ( dropdown[0].options[dropdown[0].selectedIndex].value > 0 )
{
window.location.href = "http://www.example.com/?page_id="+dropdown[0].options[dropdown[0].selectedIndex].value;
}
}
dropdown[0].onchange = onCatChange;
Hope this helps.. Cheers !!

Related

JS: I can't get the inner HTML of elements with a specific class name

I'm trying to create a calculator out of javascript to work on my skills. I've added the class num to all of my buttons that have a number.
I'm trying to display to display the innerHTML of those buttons in the console when I click them with this code:
var num = document.getElementsByClassName('num');
num.addEventListener('click', getNum);
function getNum(){
console.log(num.innerHTML);
}
getNum();
However all I get is
num.addEventListener is not a function.
Here is my codepen: https://codepen.io/teenicarus/pen/wrEzwd
what could I be doing wrong?
You need to change the code like below. getElementsByClassName returns collection of elements. Loop through the elements and add click event listener. In getNum, you can use this to get access to the button clicked.
var num = document.getElementsByClassName('num');
for (var i = 0; i < num.length; i++) {
num[i].addEventListener('click', getNum);
}
function getNum(){
console.log(this.innerHTML);
}
You can also use Array forEach like the following:
[].forEach.call(num, function(el){
el.addEventListener('click', getNum);
})
getElementsByClassName returns a collection of elements, not a single element. If you want to get single element assign it an id attribute and use getElementById. This way you can use addEventListener function
Here's a solution you can plug directly in your codepen:
var nums = document.getElementsByClassName('num');
[].forEach.call(nums, num => num.addEventListener('click', numClick));
function numClick(){
// adding + turns the text into an actual number
console.log(+this.innerHTML);
}
getElementsByClassName() returns an HTMLCollection, to iterate over it you can pass it to [].forEach.call() like I showed above.
I also renamed the handler to numClick, since it doesn't "get" the number. And added +, which is a nice shortcut to turn text into a number (otherwise, adding two numbers would yield unexpected results, like "1" + "2" => "12"
The .getElementsByClassName returns not an element, but a collection of them.
You can access elements using .getElementsByClassName(num)[element's sequential number], or better use id's and getElementById method.
Here is the modified code for your desired output.just copy and try:
var num = document.getElementsByClassName('num');
//num.addEventListener('click', getNum);
for (var i = 0; i < num.length; i++) {
num[i].addEventListener('click', getNum);
}
function getNum(){
document.getElementById('result').innerHTML+=this.innerHTML;
console.log('value:'+this.innerHTML);
}
//getNum();
As you tagged Jquery to your question I suppose that you are able to use Jquery as well. You can grab the clicked element's class and referance it with 'this' to get its text.
$('.num').click(function(){
var x = $(this).text();
console.log(x);
});
This is a working example you can check the console.log DEMO

document.getElementById(array[x]) returning null [duplicate]

This question already has answers here:
Why does jQuery or a DOM method such as getElementById not find the element?
(6 answers)
Closed 7 years ago.
I am trying to call an element using an array index value but I keep getting a null message.
JS:
function img_disp() {
var num = 0;
var images_array = ["person_1","person_2","person_3","person_4","person_5","person_6","person_7","person_8","person_9","person_10","person_11","person_12"];
document.getElementById(images_array[num]).style.visibility = "visible";
}
What can I do to make this work? I want to be able to call different ids using 1 function.
Thanks
You're not incrementing the variable num, You can use loops to do it, eg:
function img_disp() {
var images_array = ["person_1","person_2","person_3","person_4","person_5","person_6","person_7","person_8","person_9","person_10","person_11","person_12"];
for(var num = 0; num < images_array.length; num++){
document.getElementById(images_array[num]).style.visibility = "visible";
}
}
img_disp() It should be called when the DOM is loaded. Check this question, for know more about it.

tried to change the inner element of dynamic div through class name but its not working [duplicate]

This question already has answers here:
How to use getElementsByClassName in javascript-function? [duplicate]
(3 answers)
Closed 8 years ago.
I have create the dynamic div and now trying to change the inner html of it but its not working please help me here is the code
function like(id)
{
var orgnldiv=document.getElementById(id);
var ndiv=document.createElement('DIV');
ndiv.id = 'like';
ndiv.className="likeclass";
var classname = document.getElementsByClassName("likeclass");
orgnldiv.appendChild(ndiv);
classname.innerHTML="example";
//alert(id);
}
Beware of the s in Elements. That means that you are getting a list rather than a single control.
Check How to use getElementsByClassName in javascript-function?
Use this:
function like(id)
{
var orgnldiv=document.getElementById(id);
var ndiv=document.createElement('DIV');
ndiv.id = 'like';
ndiv.className="likeclass";
orgnldiv.appendChild(ndiv);
var elements = document.getElementsByClassName("likeclass");
for(var i = 0; i < elements.length; i++) {
elements[i].innerHTML="example";
}
}
You get error because getElementsByClassName returns array of elements, not one elements. So you have to work with result like with array. If 1 element return loop will fire only 1 time. If 0 elements it wouldn't fire.
Hope this will help.

Get the highest attribute value from a set of DOM elements [duplicate]

This question already has answers here:
jQuery: How to calculate the maximal attribute value of all matched elements?
(7 answers)
Closed 8 years ago.
I have a set of DOM elements with data attributes. How can I get the maximum value?
<li data-for-something="1"></li>
<li data-for-something="1"></li>
<li data-for-something="2"></li>
<li data-for-something="3"></li>
<li data-for-something="4"></li>
I can use $('[data-some-value]') to get all the li with this attribute, and then loop through them. But I'm not sure what js or jquery methods are available to make this easier.
The best I've got is doing this:
function getMaxAttributeValue(attribute_name) {
var max_value = 0;
$('[' + attribute_name + ']').map(function(){
var this_value = this.attr(attribute_name);
if (this_value > max_value) {
max_value = this_value;
}
});
return max_value;
}
I like this way:
function getMaxAttributeValue(attribute_name) {
return Math.max.apply( Math, $('[' + attribute_name + ']').map(function(){
return Number($(this).attr(attribute_name)) || -Infinity;
}))
}
console.log(getMaxAttributeValue("data-for-something")) // outputs 4
I think #juvian's answer is probably the best, however I fiddled around with this before I saw his answer, so I thought I'm going to share the way I wanted to do it. It's not a function, but works perfectly with your html structure. I made use of the dataset property.
var array = new Array;
$('li').each( function() {
array.push(parseInt($(this)[0].dataset.forSomething));
});
console.log(Math.max.apply(Math, array));
I added this to this fiddle: http://jsfiddle.net/vVkr6/

Passing values to onclick [duplicate]

This question already has answers here:
JavaScript closure inside loops – simple practical example
(44 answers)
Closed 8 years ago.
If I create a whole lot of HTML elements using a loop, like
for (i= 1; i < 100; i++) {
var my_element = document.createElement ("td");
row.appendChild (my_element);
my_element.onclick = function () {my_function (i));
}
then when the element is clicked, the value of i passed to my_function is always 100, regardless of what number element is calling it. I have worked around this by using
my_element.id = "something"+i;
my_element.onclick = function (e) {my_function (e.target.id)};
(For Internet Explorer, the target needs to be srcElement, apparently.) I am curious to know whether there is any way to create the function without having to add the ID to the element like this.
The value of i changes with each iteration of the loop. You need a closure to capture the value of i:
(function(i) {
my_element.onclick = function () {my_function (i)};
}(i))
If you write a function which builds you a handler function, you can use the new scope which that gives you to ensure that you get the number you want. For example:
function BuildHandler (i) { return function () { alert(i); };
for (i= 1; i < 100; i++) {
var my_element = document.createElement ("td");
row.appendChild (my_element);
my_element.onclick = BuildHandler(i);
}
if I were you I will use Jquery (or prototype or whatever js frameworks that available)
on each elements you should add attributes like myid for example so that when you did on click you can retrive it.
for(i=1; i ++ ; i<100){
var myelement = "<td myid='something"+i+"' class='myTD'></td>" ;
row.append(myelement);
}
....
$(document).ready(function(){
$('.myTD').click(function(){
var id = $(this).attr('myid');
my_function(id);
});
});
I did this trick on my web app :)

Categories

Resources