Back

Explore Courses Blog Tutorials Interview Questions
0 votes
2 views
in Java by (9.5k points)

I want to check if there is an image in image_array and load the last image. If it’s not present I want to disable the preview buttons, alert the user to push the new image button and create an empty array to put the images.

if(image_array.length > 0)

    $('#images').append('<img src="'+image_array[image_array.length-1]+'" class="images" id="1" />');

else{

    $('#prev_image').attr('disabled', 'true');

    $('#next_image').attr('disabled', 'true');

    alert('Please get new image');

    var image_array = [];

}

Below is the code I’ve before loading HTML:

<?php if(count($images) != 0): ?>

<script type="text/javascript">

    <?php echo "image_array = ".json_encode($images);?>

</script>

<?php endif; ?>

The problem here is that, image_array in the else fires every time. When the array exists, it overrides it but it doesn’t display the alert. Can anyone tell me what I’m doing wrong here?

1 Answer

0 votes
by (19.7k points)

See the below code implementation:

if (typeof image_array !== 'undefined' && image_array.length > 0) {

    // the array is defined and has at least one element

}

You have to use var when you declare a variable and don’t redeclare it later like below: 

<?php echo "var image_array = ".json_encode($images);?>

// add var  ^^^ here

else {

    ...

    image_array = []; // no var here

}

Interested in Java? Check out this Java Certification by Intellipaat.  

Related questions

0 votes
1 answer
0 votes
1 answer
0 votes
1 answer
asked May 15, 2021 in Java by sheela_singh (9.5k points)
0 votes
1 answer

Browse Categories

...