首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >使用f.select选择课程并自动输入字段count_stud value

使用f.select选择课程并自动输入字段count_stud value
EN

Stack Overflow用户
提问于 2014-04-29 23:22:27
回答 1查看 50关注 0票数 0

有一种形式可以让我们选择年份和课程。另一个字段不可见(它应更改学生数量,它对应于所选课程).Сhose使用f.select的课程,并自动输入字段count_stud值等于此课程的学生数量。该怎么做呢?可能需要JavaScript (Ajax技术)

EN

回答 1

Stack Overflow用户

发布于 2014-04-29 23:47:40

使用ajax可以做到这一点,如下所示更改您的选择

代码语言:javascript
复制
 <%= f.select(:course_id, @courses.map{|p| [p.id]},{},{:class => "course_id"}) %>

年份:

代码语言:javascript
复制
 <%= f.select(:year_id, @years.map{|p| [p.name, p.id]} ,{},{:onchange => "update_student(this.value)"}) %>

文本框:

代码语言:javascript
复制
<%= f.text_field :count_stud, :value => @student_count,:class => "student" %>

在ajax代码中:

代码语言:javascript
复制
function update_student(year) {  
 var course = jQuery(".course_id").val(); // finding course value
 if(course == ""){                        // checking course value being selected or not
   alert("Please select course ");
   return false;
 }
 jQuery.ajax({
 url: "update_student",
 type: "GET",
 data: {"course_id" : course,"year": year },
 dataType: "text",
 success: function(data) {
 jQuery(".student").val(data); // inserting response to text field.
 }
 });
}

因此,课程选择框的onchange一个ajax请求将使用年份和课程值,然后在您的操作中,您将获得params中的值,并找到no of student并像YearCoursesController中那样返回

代码语言:javascript
复制
   def update_student
      year = params[:year]
      course = params[:course]
      #write logic to find student
      #assign in one variable 
      year_courses = YearCourse.find_by(year_id: year, course_id: course)
      student_count = year_courses ? year_courses.students.count : 0
      render :text => student_count  #we are returning the value
   end

然后,该值将插入到文本框中。

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/23368828

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档