0

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']?

2
  • how does the generated markup looks like Commented Mar 8, 2012 at 8:57
  • This might be a silly question, but why not create the capital city array in JavaScript in the first place? It would save you a lot of hassle. Commented Mar 8, 2012 at 8:59

2 Answers 2

2

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'];
}
Sign up to request clarification or add additional context in comments.

1 Comment

This worked. Thanks. But how will i get the value for $res[_targ.value]['capital'] ?
0

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)"

Comments

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.