user2636556
user2636556

Reputation: 1915

CHtml:button onclick event

I'm trying to add an onlick event to my button. here is my code

 CHtml::button("Compare",
array('class'=>"btn btn-warning",'onclick'=>'js:var str = $.map($(\'input[name="checkbox_compare"]:checked\'), 
function(n, i){
return n.value;}).join(\',\'); 
if (isNotEmpty(str)) { window.location.href = "'.url('/compare/').'?ids="+str; } else { alert("Select atleast one"); }'))

the code works fine, but generates a html that looks like this

  <input class="btn btn-warning" onclick="js:var str = $.map($(&#039;input[name=&quot;checkbox_compare&quot;]:checked&#039;), 
function(n, i){
return n.value;
}).join(&#039;,&#039;); 
if (isNotEmpty(str)) { window.location.href = &quot;/wm/frontend/www/compare/?ids=&quot;+str; } 
else { alert(&quot;Select atleast one&quot;); }" name="yt0" type="button" value="Compare" />

still new to Yii, but was wondering if there is a better way / cleaner way to do this?

Upvotes: 1

Views: 3504

Answers (1)

Jap Mul
Jap Mul

Reputation: 18759

If you don't want to use a js file, I would do it like this:

<?php
    Yii::app()->clientScript->registerScript('myscript', '
    function myAwesomeFunction() {
        var myVar = 12;
        alert(myVar);
    }
    ', CClientScript::POS_END);

    echo CHtml::button("Compare", array('class ' => "btn btn-warning", 'onclick' => 'js:myAwesomeFunction()'));
?>

Upvotes: 1

Related Questions