0

I have a select element...

<select name="tour" id="tour">
<optgroup label="tour">
<option value="0" selected="selected">Please Select Tour</option>
<option value="Tour1">Tour1</option>
<option value="Tour2">Tour2</option>
</optgroup>
</select>

I have an array...

<?php $array = array(Tour1=>100,Tour2=>200); ?>

I have a field element...

<input type="text" size="5" id="distance" readonly="readonly" name="distance" value="" class="value" />

I'm looking to set up a jQuery script that looks for a change in the value in the select element 'tour', searches for it in my array, returns the associative value, and writes it to the value of my input field 'distance'.

Desired output: When Tour1 is selected, text input field 'distance' will show 100.

square_eyes
  • 1,269
  • 3
  • 22
  • 52

2 Answers2

2

1st Pass the PHP array to JavaScript using json_encode:

var phpArray = <?php echo json_encode($array); ?>;

2nd Bind to the change event of that <select>:

$('#tour').on('change', /* see below */);

3rd Update the value:

function (event) {
    $('#distance').val(phpArray[$(this).val()]);
}
TimWolla
  • 31,849
  • 8
  • 63
  • 96
-1

what you want to do is not possible. PHP is a server side script. What you could do in order to make your scripts working is to pass the php Array to Javascript when loading the page. That way Javascipt is able to read it and to change the input.

Option would be to use AJAX or define a JS array with the php Array's data:

var js_array = <? echo json_encode($you_array); ?>;

For this solution you need to add a in your HTML page's if you're pointing to your JS script external.

For a longer explanation why using your php Array in Javascript that easy is not possible, see here: Difference between Javascript and PHP

Community
  • 1
  • 1
Robin
  • 1,208
  • 8
  • 17