开发者

Passing a php variable to javascript and javascript if statements [duplicate]

This question already has answers here: How do I pass variables and data from PHP to JavaScript? (19 answers) Closed 8 years ago.

I have a form that submits on itself with edit, delete add parts.

I used a jquery slider to set salary range (It's a job board).

The slider sets SalaryR (the range out put for the screen), SalaryMin and SalaryMax to hidden fields for saving to db.

What I would like to do is have the range set as the already stored amounts if SalaryMin,Max are already set so that I can edit the form. At the moment it defaults back to 20000,50000.

I have no knowledge of Javascript and was surprised I managed to get the min/max values out in the first place. Here is the slider code:

$( "#slider-range" ).slider({
        range: true,
        min: 8000,
        max: 100000,
        step: 500,
        values: [ 20000, 25000 ],
        slide: function( event, ui ) {
            $( "#SalaryR" ).val( "£" + ui.values[ 0 ] + " - £" + ui.values[ 1 ] );
            $( "#SalaryMin" ).val( ui.values[ 0 ] );
            $( "#SalaryMax" ).val( ui.values[ 1 ] );
        }
    });
    $( "#SalaryR" ).val( "£" + $( "#slider-range" ).slider( "values", 0 ) +
        " - £" + $( "#slider-range" ).开发者_开发技巧slider( "values", 1 ) );


I would put these values in a hidden html element on the page and then get the values from these elements in JavaScript. That way, it means you don't have to generate JavaScript through PHP. It keeps your JavaScript independent from your server-side scripting.

PHP

<span id="max" class="hidden"><?php echo $max;?></span>
<span id="min" class="hidden"><?php echo $min;?></span>

CSS

.hidden{display:none;}

JS

var max = $('#max').text();
var min = $('#min').text();


Or if the javascript is part of php file, you can use normal PHP tags, for example: <?php echo $amount; ?>. PHP part of the script is processed on the server side and pure javascript code comes to client. Then, your existing script is used.

Example:

var x = { "values" : [ <?php echo $x; ?>, <?php echo $y; ?> ]};

Depends where your JS code is, if you keep it independent or injected in PHP files.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜