Nitu Dhaka
Nitu Dhaka

Reputation: 1320

On change event on the selection of dropdown's value using underscore and backbone

I created the dynamic dropdown in template. and my further requirement is to change the value of the dropdown and send the value back to the web service to hit to change in the system. I have no idea how to do it in underscore template. below is the code that i write for dynamic dropdown. and where have to write the ratecall function either in template file or in main.js no idea about it. and rightnow I am just firing an alert showing on change fired but its not working. actually the error that is coming is ratecall is not defined. Any help will be appreciated. Thanks in advance.

  <select id="rate" onchange="ratecall()">
                    <% for(var i=0;i<post.scales-1;i++){
                         if(i==post.rated){
                         var a= 'selected';
                         }else{
                         a='';
                         }
                         %>
                         <option id="<%=i%>"<%=a %> > <%= i%></option>
                        <%}%> 
                </select>
                <%}else{
                }
                function ratecall(){
                document.getElementById("rate").onchange = function () {
                alert("ON CHANGE FIRED");
                };
                }

Upvotes: 0

Views: 1463

Answers (2)

mrak
mrak

Reputation: 2906

As pointed by @danblundell in the comments, the view should be responsible only for rendering. I made a minimal backbone example which illustrates how it's done (for your example): http://jsfiddle.net/dh64x/3/

Backbone provides view objects where you can specify events and event handlers:

var PostView = Backbone.View.extend({

    events: {
        'change #rate': 'postSelected'
    },

    // ...

    postSelected: function(e) {
        console.log(e);
    }

});

In this case, change events on select#rate element are bound to postSelected function.

Read the docu for more details: http://backbonejs.org/#View

Upvotes: 1

Nishant Solanki
Nishant Solanki

Reputation: 2128

Please try this code..

<select id="rate" onchange="ratecall()">
<%
for(var i = 0;i < post.scales - 1;i++)
{
var a= ''
if(i==post.rated)
    {
       a = 'selected';
    }
    else
    {
        a = '';
    }
%>
<option id="<%= i %>" <%= a %> > <%= i %></option>
<% } %> 
</select>
<%

function ratecall()
{ 
         alert("ON CHANGE FIRED");       
}

Upvotes: 0

Related Questions