Pergunta

New to Cakephp having some trouble using it with javascript

Cakephp Code:

<?php
echo "ready!",
$this->Html->image(
'button_on', array(
'style' => 'height: 40px; width: 70px;',
'id' => 'changeimg',
'onclick' => 'changeImage()'
));
?>

<script type="text/javascript">
function changeImage() {
    console.info('success');
    if (document.getElementById("changeimg").src === "/site/img/button_on") {
        console.info('success2');
        document.getElementById("changeimg").src = "/site/img/button_off";
    } else {
        document.getElementById("changeimg").src = "/site/img/button_on";
    }
    return false; 
}
</script>

Generated Code/The one you see in the browser's Page Source:

ready!<img id="changeimg" alt="" onclick="changeImage()" style="height: 40px; width: 70px;" src="/site/img/button_on">

Theoretically speaking when you are changing an image using an onclick event the image url changes as the user clicks it or as the event is triggered, to elaborate.

Generated Code:

ready!<img id="changeimg" alt="" onclick="changeImage()" style="height: 40px; width: 70px;" src="/site/img/button_on">

click: event triggered:

ready!<img id="changeimg" alt="" onclick="changeImage()" style="height: 40px; width: 70px;" src="/site/img/button_off">

The scenario above should happen, however in my case it didn't work, how can I solve this?why can't cakephp see the event being triggered. Any help is appreciated

Foi útil?

Solução

This works fine, change logic as per requirements :

<?php
echo "ready!";
echo $this->Html->image('logo.png', array('style' => 'height: 40px; width: 70px;','id' => 'changeimg','onclick' => 'changeImage()'));

$this->Html->scriptStart(array('inline' => false));
?>
function changeImage() {
    var path = document.getElementById("changeimg").src;
    if (path.search("logo.png")) {
        document.getElementById("changeimg").src = "<?php echo $this->webroot; ?>/img/logo_new.png";
    } else {
    document.getElementById("changeimg").src = "<?php echo $this->webroot; ?>/img/logo_small.png";
    }
    return false; 
}
<?php 
$this->Html->scriptEnd();
?>
Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top