Reputation: 14250
I have an php array that is generated by server-side code. I want to show the array value in my input field after user pick an option from my dropdown menu. Please see my code:
$(document).ready(function(){
$('select[name="job_number"]').change (function () {
var selectedVal = $(this).val();
var test="<?php echo $JNarray['selectedVal'];?>"; //where the problem is
$('input[name="project"]').val(test);
//I want show value1 to value 3 in my input field when user picks
//an option from my dropdown menu.
});
<?php
$JNarray['job1']=value1;
$JNarray['job2']=value2;
$JNarray['job3']=value3;
?>
<form action='project_manager' method='post'>
<input type='text' name='project' value='show value1 to value3 when user picks an option' />
<select name='job_number'>
<option value='job1'>job1</option>
<option value='job2'>job2</option>
<option value='job3'>job3</option>
</select>
</form>
Any thoughts? Thanks for the help!
Upvotes: 0
Views: 767
Reputation: 71908
You have to declare and populate your array before you use it on the jquery code. Move your <?php ?>
code to the top.
Then pass the whole php array to javascript, using JSON as Trevor suggested:
$(document).ready(function(){
var options = JSON.parse(<?php echo json_encode($JNarray);?>);
$('select[name="job_number"]').change (function () {
var selectedVal = $(this).val();
var test=options[selectedVal]; //where the problem was
$('input[name="project"]').val(test);
});
});
Upvotes: 1
Reputation: 171679
Here's a cleaner way to do it without having to set the array to a variable. Use a data attribute that jQuery reads with $.data()
HTML:
<option value='job1' data-job-val="<? echo $arrayvalue ?>">job1</option>
JS:
$('select[name="job_number"]').change (function () {
var test=$(this).find('option:selected').data('job-val');
$('input[name="project"]').val(test);
});
Upvotes: 2
Reputation: 4592
I agree with Trevor, however try
"<?php echo $JNarray['"+selectedVal+"'];?>"
Echoing PHP means your calling your JS from a PHP file, not a good approach dude!, The only thing I would pass is maybe a BASE_URL or FILE_UPLOAD_TYPE/SIZE, even those are ewwwwwwwy
Upvotes: 0
Reputation: 20155
<select name='job_number'>
<option value='<?php echo $JNarray['job1'] ?>'>job1</option>
...
...
</select>
<script>
$(document).ready(function(){
$('select[name="job_number"]').change (function () {
$('input[name="project"]').val($(this).val());
});
</script>
something like that.
Upvotes: 1
Reputation: 11425
Though, I don't recommened echoing php in js...
var test=JSON.parse(<?php echo json_encode($JNarray['selectedVal']);?>); //where the problem is
Upvotes: 1