Search code examples
phpjqueryjquery-ui-slider

Load UI-slider more then one time with dynamic data jquery


I want to use this jquery slider in my page.I want to load slider multiple time on the page.it didn't work for me.This is my code .

    <script>
    jQuery(function() {
<?php 
    for( $i =0; $i<3;$j++){ 
    ?>  
        jQuery( "#slider-range-max+<?php echo $i?>" ).slider({
        range: "max",
        min: 1,
        max: 10,
        value: 2,
        slide: function( event, ui ) {
        jQuery( "#amount+<?php echo $i?>" ).val( ui.value );
    }
});
    jQuery( "#amount+<?php echo $i?>" ).val( jQuery( "#slider-range-max+<?php echo $i?>" ).slider( "value" ) );
<?php } ?>
});
</script>
<?php 
for( $j =0; $j<3;$j++){  ?>
<p>
     <label for="amount<?php echo $i?>">Minimum number of bedrooms:</label>
    <input type="text" id="amount<?php echo $i?>" style="border: 0; color: #f6931f; font-weight: bold;" />
    </p>
<div id="slider-range-max<?php echo $i?>"></div>
<?php  } ?>

This is the output of the above code

<script>
jQuery(function() {

jQuery( "#slider-range-max0" ).slider({
range: "max",
min: 1,
max: 10,
value: 2,
slide: function( event, ui ) {
jQuery( "#amount0" ).val( ui.value );
}
});
jQuery( "#amount0" ).val( jQuery( "#slider-range-max0" ).slider( "value" ) );

jQuery( "#slider-range-max1" ).slider({
range: "max",
min: 1,
max: 10,
value: 2,
slide: function( event, ui ) {
jQuery( "#amount1" ).val( ui.value );
}
});
jQuery( "#amount1" ).val( jQuery( "#slider-range-max1" ).slider( "value" ) );

jQuery( "#slider-range-max2" ).slider({
range: "max",
min: 1,
max: 10,
value: 2,
slide: function( event, ui ) {
jQuery( "#amount2" ).val( ui.value );
}
});
jQuery( "#amount2" ).val( jQuery( "#slider-range-max2" ).slider( "value" ) );
});
</script>
<p>
 <label for="amount3">Minimum number of bedrooms:</label>
<input type="text" id="amount3" style="border: 0; color: #f6931f; font-weight: bold;" />
</p>
<div id="slider-range-max3"></div>
<p>
 <label for="amount3">Minimum number of bedrooms:</label>
<input type="text" id="amount3" style="border: 0; color: #f6931f; font-weight: bold;" />
</p>
<div id="slider-range-max3"></div>
<p>
 <label for="amount3">Minimum number of bedrooms:</label>
<input type="text" id="amount3" style="border: 0; color: #f6931f; font-weight: bold;" />
</p>
<div id="slider-range-max3"></div>

Solution

  • The main problem is that you have repeated the same IDs 3 times. jQuery will not know which one to take. Simply make the IDs unique.

    In your PHP file at the HTML part use $j instead of $i. Otherwise as you see in your HTMl output $i is stuck at 3 resulting in duplicate IDs

    FIDDLE