Question

I'm trying to change an image onclick in cakephp but i'm not usre if my syntax is correct in putting an id and adding an onclick function. below is my code any help is appreciated

<?php    
echo $this -> Html -> link($this -> Html -> image('button_on', array('height' => '40','width' => '70')).''.('ready'), array('id' => 'changeimg', 'onclick' => 'changeImage'), array('escape' => false)); ?>

<script language = "javascript">

    function changeImage() {

        if (document.getElementById("changeimg").src === "button_on") {
            document.getElementById("changeimg").src === "button_off";
        } else {
            document.getElementById("changeimg").src === "button_on";
        }
    } 
    </script>
Was it helpful?

Solution

Check your HTML output to make sure that Cake is generating your link and image correctly. I'm not sure what the ready part is for, but insert as needed. You should have Cake code like this:

echo $this->Html->link(
    '#', // specify a target
    $this->Html->image(
        'button_on', 
        array(
            // height and width attributes are deprecated
            // use CSS styles in style attribute instead
            'style' => 'height: 40px; width: 70px;',
            'id' => 'changeimg',
            'onclick' => 'changeImage()'
        )
    ),
    array('escape' => false) // this goes in the link part, not the image
);

Then your Javascript should look like this:

<script>
function changeImage() {
    if (document.getElementById("changeimg").src === "button_on") {
        document.getElementById("changeimg").src = "button_off";
    } else {
        document.getElementById("changeimg").src = "button_on";
    }
    return false; // prevent the link's default behaviour
} 
</script>

Note: === is a strict comparison operator, so when you assign the src attribute to something else, you use the assignment operator = instead.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top