javascript - 使用 Jquery 和 Ajax 根据组合框中选定的值自动填充表单

标签 javascript jquery ruby-on-rails ajax

我是 ajax 和 Jquery 新手。我已经编写了代码,通过我正在设计的表单中的 ajax 调用自动填充组合框。现在,我想根据组合框中所选的值自动填充同一表单的其余字段,为此我需要另一个 ajax 调用,该调用将只返回一个 student 对象。通过这个对象,我可以像这样设置表单的字段:

$('#student_name').val(student.name); $('#student_roll_num').val(student.roll_num);等等

其中name、roll_num是表单字段的id。

我是这样写的:

//This following function will get called when one value from the combo box is 
//selected

 $("select#student_id").change(function(){
    var student_id = $(this).val(); //Here I am getting the selected value from 
    //the combo box
    $.ajax({
        url: "/students_database?student_id="+student_id, //this is the url that will
        //send me one student object
        dataType: "json",
        success: /*YET TO BE FILLED WITH CODE TO AUTO 
        /* POPULATE REST OF THE FIELDS*/ 
});

实际上,在这里我无法决定如何访问重新调整的学生对象,以便我可以像上面所说的那样访问它的字段。因此,如果有人愿意帮助我做到这一点,我将非常感激。另外如果有更好的方法请建议。谢谢。

最佳答案

假设您从 ajax 调用中获取一名学生的 json,这应该可以工作:

 $("select#student_id").change(function(){
    var student_id = $(this).val(); //Here I am getting the selected value from 
    //the combo box
    $.ajax({
        url: "/students_database?student_id="+student_id, //this is the url that will
        //send me one student object
        dataType: "json",
        success: function(student) {
           $('#student_name').val(student.name);
           $('#student_roll_num').val(student.roll_num);
        }    
    });
 });

关于javascript - 使用 Jquery 和 Ajax 根据组合框中选定的值自动填充表单,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18810361/

相关文章:

javascript - 如何在 typescript 文件 (VS2015) 中引用 jQuery (intellisense)

javascript - 在 Electron 项目中使用多个 JS 文件

javascript - 需要映射函数来运行另一个函数一次

jquery - 添加 jquery 文件后更新面板不工作

javascript - 在 CSS Transition 之前克隆元素返回应用了过渡的元素

javascript - 根据 rails 4,bootstrap 3 中的类别 id 更改下拉菜单的文本

ruby-on-rails - 如何在 Rails 4 中将 where 条件与 "or"链接起来?

ruby-on-rails - 我是否应该将二进制文件包含在 Rails 插件中?

javascript - 如何使这个方法异步?

javascript - 为什么我在以下情况下收到 jQuery 错误 "TypeError: $(...).live is not a function "?