Get up to 80 % extra points for free! More info:

Discussion: document.GetElementsByName not working

Douglas Northwell:4/7/2018 20:10

Hey, I'm working on an application that renders a collage of images (album covers). However, whenever I run this code, the update function doesn't send an alert, so I'm assuming it cannot find any elements with the name I assigned with the onClick function. Why is that? The render function works fine and assigns the name properly. The classes are in PHP, but the user input (click events, etc.) is handled in Javascript.

Here is the render function which is located in the Album class:

public function render()
        "<script>function setName(id){document.getElementById(id).setAttribute('name','selected');}</script>" .
        "<input type='image' onClick='setName(' id='$this->id' src='" . $this->url . "'/>";

Here is the update function which is located in the Chart class (manages Album objects):

public function update($url)
        "<script type='text/javascript'>" .
        "var clicked = document.getElementsByName('selected');" .
        "alert(clicked[0].id);" .
        "document.getElementById(clicked[0].id).src='" . $url . "';" .
        "clicked[0].setAttribute('name','');" .
Edited 4/7/2018 20:12
4/7/2018 20:10
David Capka Hartinger team
Replies to Douglas Northwell
David Capka Hartinger:4/8/2018 4:53

Hi Douglas,
did you check the "Console" tab in the developer tools (F12) for error messages? Usually, you can find what's wrong there.

I wouldn't use the name attribute to select items, this is usually done by assign a class, e.g. a .selected class. I'd also use a single JavaScript file to handle all of that. It's always a good idea to separate JS code from PHP code because it's difficult to find an error otherwise.

I'm not sure why do you use the <input> element to render images? I'll use the <img> element instead.

public function render()
        '<img src="' . $this->url . '" alt="" id="' . $this->id . '" class="album-image" />';

I assigned the .album-image class to the images so I can manipulate with them in JS easily.

Your JS file can look as follows:

let images = document.getElementsByClassName('album-image'); // selects all the images
for (let image of images) { // iterates through all of them
        image.onClick = function() { this.classList.add('selected'); }; // adds the onClick event to all of them

I'm not sure about your update() PHP function. It would be a big help if you specified what the application should do.

Up Reply
4/8/2018 4:53
You can walk through a storm and feel the wind but you know you are not the wind.
To maintain the quality of discussion, we only allow registered members to comment. Sign in. If you're new, Sign up, it's free.

2 messages from 2 displayed.