Vinay
Vinay

Reputation: 75

How to add javascript code in cakePHP view

I have written the following piece of code in my view page

<script type="text/javascript">
function filldetails()
{
    document.getElementById('FirstName').value  = "hjshjsh"; 
}
</script>
echo $this->Form->select('students',$student_name,array('onchange' =>filldetails()));

but i am getting an error message

call to undefined function filldetails()

How do I solve this error?

Upvotes: 1

Views: 9789

Answers (2)

dogmatic69
dogmatic69

Reputation: 7575

it should be 'onchange' => 'filldetails()'

Upvotes: 5

Daniel Wright
Daniel Wright

Reputation: 4604

Unless your project has a specific reason to avoid JS frameworks, you will avoid a lot of long-term headaches by using jQuery instead of pure Javascript.

Rewrite your view thus:

<?php
  $selectDomId = $this->Form->domId('students');
  $firstnameDomId = $this->Form->domId('Student.first_name');

  $this->Html->scriptBlock("
      jQuery(function($){
        $('#{$selectDomId}').change(function(event){
          $('#{$firstnameDomId}').val( $(this).val() );
        });
      });
  ",array('inline'=>false));
?>
<?php echo $this->Form->select('students',$student_name,$this->Form->domId(array(),'students'))?>
<?php echo $this->Form->input('Student.first_name')?>

The jQuery takes care of the onChange event handler, so it doesn't clutter your HTML, by hooking onto your dropdown menu's change event.

The use of Helper::domId means you don't have to worry about how CakePHP's helpers generate their id attributes, which is a net win in reliability and maintainability.

Upvotes: 0

Related Questions