Discussion: document.GetElementsByName not working

JavaScript JavaScript document.GetElementsByName not working

Activities (1)
Avatar
Douglas Northwell:7. April 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()
{
        echo
        "<script>function setName(id){document.getElementById(id).setAttribute('name','selected');}</script>" .
        "<input type='image' onClick='setName(this.id)' 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)
{
        echo
        "<script type='text/javascript'>" .
        "var clicked = document.getElementsByName('selected');" .
        "alert(clicked[0].id);" .
        "document.getElementById(clicked[0].id).src='" . $url . "';" .
        "clicked[0].setAttribute('name','');" .
        "</script>";
}
Edited 7. April 20:12
 
Reply 7. April 20:10
Avatar
David Capka
ICT.social team
Avatar
Replies to Douglas Northwell
David Capka:8. April 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()
{
        echo
        '<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 8. April 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.