how to write javascript in yii

I have a table student

id

roll_no

Sub1_mark

sub2_mark

total

percentage

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 = '

        $(document).ready(function(){

             alert("hello");

        });	

';


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

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

$cs->registerScriptFile($baseUrl.'/js/myscript.js',CClientScript::POS_END);

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

If you want to register css use registercss instead

Your view:


<?php

Yii::app()->clientScript->registerScript('calc_total_mark','

  // 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.

Yii::app()->clientScript->registerScript(‘totalAmount’,’

$(document).ready(function()

{

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

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


&#036;(&quot;#Total&quot;).val(&#036;subtotal);

});

');

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.


Yii::app()->clientScript->registerScript('totalAmount','

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

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

    $("#Total").val(subtotal);

  });

');



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




<html>

<head></head>

<body>

<!-- All html code here -->


<script>

// All JS code here

</script>

<!-- else nothing -->

</body>

</html>



That’s exactly how I meant to be :)

thanks for help

1 Like