xarlotie
xarlotie

Reputation: 21

Passing a PHP variable to a javascript on an ONCHANGE event

I want to change the text of a label when i choose a new value in a dropdown list.

These are my php arrays:

$data = array(
              '1'=>array('country'=>'Philippines','capital'=>'Manila'),
              '2'=>array('country'=>'Finland','capital'=>'Helsinki'),
              '3'=>array('country'=>'India','capital'=>'Delhi') 
            );

$countries = array(1=>'Philippines', 2=>'Finland', 3=>'India');

This is how it should be displayed in the page:

    <div><?php echo form_label('Country: ', 'country'); ?></div>
    <div><?php echo form_dropdown('country',$countries,'',
                      'onChange="javascript:displayCapitalCity(?????)"'); ?></div>

    <div><?php echo form_label('Capital: ', 'capitalLabel'); ?></div>
    <div id="capcity"><?php echo form_label('','capitalcity'); ?></div>

This is the javascript:

function displayCapitalCity(?????){
document.getElementById('capcity').innerHTML = '??????';
}

????? should be the capital city of chosen country. How will I pass the value of $data[index of chosen country]['capital']?

Upvotes: 0

Views: 5491

Answers (2)

mgraph
mgraph

Reputation: 15338

try this:

<div><?php echo form_dropdown('country',$countries,'',
                      'onChange="javascript:displayCapitalCity(this)"'); ?></div>


var jsdata = <?php echo json_encode($data); ?>;
function displayCapitalCity(_targ){
   document.getElementById('capcity').innerHTML = jsdata[_targ.value]['capital'];
}

Upvotes: 2

iMoses
iMoses

Reputation: 4348

Best way (in my opinion) is to translate the PHP $data array into JSON, making it accessible on the client side (i.e. JavaScript).

<script type="text/javascript">
<?php printf('var countriesData = %s;', json_encode($data)) ?>
function displayCapitalCity(index) {
    document.getElementById('capcity').innerHTML = countriesData[index].capital;
}
</script>

Just make sure you're passing for correct index corresponding with the $data array.

Assuming you are using CodeIgniter, the onChange should look like that:

onchange="javascript:displayCapitalCity(this.value)"

Upvotes: 0

Related Questions