简体   繁体   中英

how to calculate percentage for nested fields in ruby on rails

I have set default 3 nested attributes fields when page loads in controller

def new
@candidate = Candidate.new
#@candidate.educations.build
3.times do
  education = @candidate.educations.build
end

end I am calculating percentage for nested fields using jquery in my candidates.coffee files i have

$('#max_marks, #marks_obtained').keyup ->
max_marks = parseFloat($('#max_marks').val()) or 0
marks_obtained = parseFloat($('#marks_obtained').val()) or 0
$('#percentage').val marks_obtained * 100 / max_marks
return

In _education_fields.html.erb i have my fields

 <div class="form-group">
      <%= f.label :max_marks %><br>
      <%= f.text_field :max_marks, id: 'max_marks' %>
    </div>
    <div class="form-group">
      <%= f.label :marks_obtained %><br>
      <%= f.text_field :marks_obtained, id: 'marks_obtained'%>
    </div>
    <div class="form-group">
      <%= f.label :percentage %><br>
      <%= f.text_field :percentage, id: 'percentage' %>
    </div>

Now i am able to calculate percentage for first field but second and third field i am not able to apply jquery because id's are same for 3 fields how do i calculate percentage for other 2 fields

There is child_index thing that rails provide in nested association when using in html.erb.

Below code may resolve your problem.

<div class="education_<%= f.options[:child_index] %>">
  <div class="form-group">
      <%= f.label :max_marks %><br>
      <%= f.text_field :max_marks, class: 'max_marks', data: {index: f.options[:child_index]} %>
    </div>
    <div class="form-group">
      <%= f.label :marks_obtained %><br>
      <%= f.text_field :marks_obtained, class: 'marks_obtained', data: {index: f.options[:child_index]}%>
    </div>
    <div class="form-group">
      <%= f.label :percentage %><br>
      <%= f.text_field :percentage, class: 'percentage' %>
    </div>
</div>



$('.max_marks, .marks_obtained').focusout(function(event){
      var target = $(event.target), parent = target.parents().find('.education_' + target.attr('data-index'));
      if (parseInt(parent.find('.marks_obtained').val()) > parseInt(parent.find('.max_marks').val())){
         alert('Marks Obtained cannot be greater then Maximun Marks');
         parent.find('.marks_obtained').val('');
      } else {
        var max_marks = parseFloat(parent.find('.max_marks').val())
        var marks_obtained = parseFloat(parent.find('.marks_obtained').val())

max_marks = max_marks === NaN ? 0 : max_marks

marks_obtained = marks_obtained === NaN ? 0 : marks_obtained
        parent.find('.percentage').val(marks_obtained * 100 / max_marks)
      }
    });

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM