how to write javascript in yii

I have a table student







i want to calculate total mark on the lost focus of sub2_mark (when i enter sub1_mark & sub2_mark total display in total text field)

please help mi i cant know how to write & call javascript in yii.

you should use the registerscript or registerscriptfile

$script = '





$baseUrl = Yii::app()->baseUrl; 

$cs = Yii::app()->getClientScript();


$cs->registerScript('myscript', $script);

If you want to register css use registercss instead

Your view:



  // your js code here



<!-- some html code -->

thxy for replay i will try

This seems like a simple js task, don’t think that is necessary to do it on separate file, U can do like on any file, place your js code inside <script></script>.

i wrote this java script in _form where i call this i have no error but it cant displt value in total field.




$("#C, #Cpp").onchange(function(event){

var &#036;subtotal = &#036;(&quot;#C&quot;).val() + &#036;(&quot;#Cpp&quot;).val();




It’s a good practice to move <script> before </html>, so it’s better use registerScript function.

Use .change(function(e){}) or .on(‘change’,function(e){}) if you working with jQuery.

To math sum use parseInt or parseFloat funcs cause type of you value may be a string and it makes concatination inspite of calculation.

Also you needn’t to wrap code in $(document).ready(function(){}); And you forget to close ready function callback.


  $("#C, #Cpp").change(function(e){

    var subtotal = parseInt($("#C").val()) + parseInt($("#Cpp").val());




P.S. Please use [code] for code wrap.

I didn’t wrote that <script> tag should be outside os <html>, just said that he can just place it inside <scrpit> directly in file where he will use js

1 Like

I mean




<!-- All html code here -->


// All JS code here


<!-- else nothing -->



That’s exactly how I meant to be :)

thanks for help

1 Like