Richlewis
Richlewis

Reputation: 15374

Submit value to Rails Model

if i have this as my form

<%= form_for @rating, :id =>"ratingForm" do |f| %>
<%= f.hidden_field :ratings, :value => '' %>
<%= f.hidden_field :user_id, :value => current_user.id %>
<%= f.hidden_field :recipe_id, :value => @recipe.id %>
<div class="rateit" id="rateit10">
</div>
<%= f.submit "Submit" %>
<% end %>

How do i pass the value of the content within this div

<div class="rateit" id="rateit10">
</div>

if i use this jquery I can get the value of rateit10

$("#rateit10").bind('rated', function() { 
 $(this).rateit('value');
  });

The value derives from clicking upon a set of stars, im trying to implement a rating system in rails using the Rateit plugin

Upvotes: 0

Views: 233

Answers (3)

Ryan
Ryan

Reputation: 5682

This will pass a hash to your controller method:

   function pass_to_controller(){
    var rate_value = $("#ratings").value();
    var user_id = $("#user_id").value();  /*you already have access to this through current_user.id */
    var recipe_id = $("#recipe_id").value();

    $.ajax({
        type: "Get",
        url: "path_to_your_controller_action_here",
        timeout: 5000,
        data: {rating : rate_value, user : user_id, recipe : recipe_id }
    }).done(function(response){//do your response here});
}

You can't directly pass to the model - that circumvents the whole thought process behind MVC. So the best way to do it is to use ajax, pass it to your controller method, then if you need to do something in your database call your model method.

The advantage of using ajax like this is that it won't reload your page when someone rates something.

Upvotes: 2

sjain
sjain

Reputation: 23344

To show text inside div using javascript:

divObj = document.getElementById("rateit10");
            if ( divObj ){
                if ( divObj.textContent ){ //FF
                    alert ( divObj.textContent );
                }else{  //IE            
                    alert ( divObj.innerText );  //alert ( divObj.innerHTML );
                } 
            }  

To show innerdiv inside div using javascript:

myDivObj = document.getElementById("rateit10");
if ( myDivObj ) {
   alert ( myDivObj.innerHTML ); 
}else{
   alert ( "Text Found" );
}

To show text inside div using jquery

$(function(){
       var txt = $('#rateit10').text();
       alert(txt);
    };

Upvotes: 0

St&#233;phane V
St&#233;phane V

Reputation: 1094

The easiest way is to trigger an update of your hidden field when the user click on a star, rather than read the value of the stars when the form is submitted.

I should add a onnclick event on the stars to update the hidden field. To do this, add an ID to your hidden field with :id => "my_hidden_field" to name it.

Then, trigger a javascript function when the user click on a star :

$("#second_star").click(function() {
  $("my_hidden_field").value = 2;
});

Upvotes: 2

Related Questions