Reputation: 215
I have an array in PHP (it has to be PHP for somewhat complicated reasons that go beyond the scope of this post):
<?php
$arr = array(Div1, Div2);
foreach ($arr as $value) {
print_r($value);
}
?>
I then have some Jquery that I'm attempting to use to hide every element that has a class in that array.
<script>
$(document).ready(function(){
$("."+"<?php echo $value; ?>").hide();
});
</script>
However, this only hides elements whose class is equivalent to the last item in the array. In other words, only items whose class is Div2
hide. How can I make this apply to each item in the array?
Upvotes: 0
Views: 53
Reputation: 2537
you can take the php array and use it in javascript. the easiest way is to use json:
<?php
$arr = array('Div1', 'Div2');
?>
<script>
$(document).ready(function(){
var arr = <?=json_encode($arr);?>;
arr.forEach((className)=>$("."+className).hide());
});
</script>
or you can join the array and let jquery iterate over it:
<script>
$(document).ready(function(){
var arr = <?=json_encode($arr);?>;
$('.'+arr.join(', .')).hide();
});
</script>
Upvotes: 2
Reputation:
Try this :
<?php
$arr = array(Div1, Div2);
//give us the resulat of this please add to the post
var_dump($arr);
$array_to_object_json = json_encode($arr);
?>
We need to known what return this var_dump
<script>
var global_json_from_php = <?php echo $array_to_object_json; ?>;
$(document).ready(function(){
console.log(global_json_from_php);
for(i in global_json_form_php){
$("."+global_json_from_php[i]).hide();
}
});
</script>
Upvotes: 0
Reputation: 413
Kindly Replace it with the Below code and give a test.
<script>
$(document).ready(function(){
<?php
$arr = array(Div1, Div2);
foreach ($arr as $value) {
echo '$("."+"'.$value.').hide();';
}
?>
});
</script>
Upvotes: 0
Reputation: 2126
Replace that JS line with this, it will work as long as $arr
is in scope wherever the JS code is (which it should be based on your question).
<?php
foreach($arr as $value) {
echo '$("' . '.' . $value . '").hide();';
}
?>
You were previously just looping over the array and not doing anything with the values (other than using print_r()
on them). Therefore when you reached the code in your second snippet, only the last value of $value
was usable.
Upvotes: 1
Reputation: 8374
after the foreach
loop finishes, $value
is still bound to the last value of your $arr
. either somehow include the js-output into the loop or loop through the array again in your js-php-loop
Upvotes: 1