1

I am coding on a page which calculates a price dynamically when changing the input field :

<input type="number" id="amount" name="amount" type="number" value="0" min="1" max="6">

The calculation is base on a php array:

$plz[01] = array( 1=> 58, 2=> 43, 3=> 32, 4=> 26, 5=> 22, 6=> 19 );
$plz[02] = array( 1=> 58, 2=> 43, 3=> 32, 4=> 26, 5=> 22, 6=> 19 );
$plz[03] = array( 1=> 58, 2=> 43, 3=> 32, 4=> 26, 5=> 22, 6=> 19 );

Im trying to parse PHP code to my script and this works:

$("#amount").on('change',function() {
var sum = <?php echo $plz[01][6]; ?>;
}

But I need the value of the selected amount as key. Something like this:

$("#amount").on('change',function() {
var sum = <?php echo $plz[01] [$(this).val();] ?>;
}

Is there a way to do this? Thanks in advance.

3
  • Why not export the PHP arrays to JavaScript using json_encode? Also note that using 01 will become base-8, instead of what you expected it to be (like "01") Commented Dec 30, 2016 at 13:17
  • I think you meant "pass" instead of "parse"/"parsing". Commented Dec 30, 2016 at 13:18
  • you can save values in to js var before or create extra php file and hold values from that via $.ajax load function. Commented Dec 30, 2016 at 13:19

1 Answer 1

1

You could use json_encode in your PHP code to output the array in JSON to your JS code which you can then parse to an object.

var json = <?= json_encode($plz) ?>;
var arr = JSON.parse(json);

From there you can read the array as required:

$("#amount").on('change', function() {
    var sum = arr['01'][this.value - 1];
});

Working example

Note in the example above I included the JSON directly, but that is what should be output from PHP given your sample array.

Sign up to request clarification or add additional context in comments.

2 Comments

Thank you very much! I will try with JSON.
No problem. If the answer helped, you can accept it by clicking the green tick to the left

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.