0

Here is my issue. I have an input type button with a background, it is generated by PHP. I'm trying to change the background property of this input using a simple Javascript script.

<?php
    foreach($imageList as $image){
        //My button input
        echo '<input id="button_'.$image -> getId().'" type="button" style="background: url(path) 0px 0px no-repeat">';
        //My test button input
        echo '<input id="test_button_'.$image -> getId().'" type="button" style="background: url(path) 0px 0px no-repeat">';
        ?>
        <script>
        for (var i = 0; i < idList.length; i++) {//I navigate trhough an array
            if (idList[i] == 'id_<?php echo $image -> getId(); ?>') {//If the array[value] match with the id
                //I change my background property: -20px 0px
                document.getElementById('button_<?php echo $image -> getId(); ?>').style.background = 'url(path) -20px 0px no-repeat';
                //This is to change the test button background property
                document.getElementById('test_button_<?php echo $image -> getId(); ?>').style.background = 'url(path) -20px 0px no-repeat';
            }else{
                document.getElementById('button_<?php echo $image -> getId(); ?>').style.background = 'url(path) -20px 0px no-repeat';
            }
        }
        </script>
        <?php
    }
?>

The test_button_id button input is affected by the Javascript but not the button_id input. At this point I'm struggling with this issue and I don't know why the script should affet one input and not the other. I already try to change the id of the first input but it didn't work.

Thank you for any help you could give me.

YanYan
  • 21
  • 5
  • maybe the background image of the first button is larger so it hasn't loaded by the time the script runs. Try moving your js into a window loaded function – Pete Jun 30 '15 at 08:41
  • @Pete No, it's not changing anything. I tried "$(window).load(function() { script });" and also "$(document).ready(function() { script )};". But thank you for the tip. – YanYan Jun 30 '15 at 08:53
  • Are you using jQuery? Those functions will only work if you are (and `$(document)` should be `$('document')`. If you are not using jQuery, have a look at [this post](http://stackoverflow.com/questions/9899372/pure-javascript-equivalent-to-jquerys-ready-how-to-call-a-function-when-the) for the non jQuery equivelant – Pete Jun 30 '15 at 09:19
  • Yes I am. Also the picture is only 40x20px so I think it's ok. – YanYan Jun 30 '15 at 09:27
  • you could try to use the jquery selector then: `$('#button_ getId(); ?>').css('background', 'url(path) -20px 0px no-repeat')` – Pete Jun 30 '15 at 09:55

0 Answers0