Rails外部js函数不会触发

Rails external js function does not fire

本文关键字:函数 外部 js Rails      更新时间:2023-09-26

我有以下表格:

<%= form_for @question, {:as => :question, :method => :post, :url => {:action => :multiple_choice}, :html => {:onsubmit=> "return checkAnswers();"}, :class => "form-inline"} do |f| %>

在提交时应该调用checkAnswers() JS函数并做一些检查。

如果我有这个函数在html。它工作得很好. ...但是当我在公共/javascript/myJSfunctions.js中设置它时,它不起作用。

js文件包含在layout中。有什么问题吗?

函数checkAnswers () {

var emptyStatus = false;
// prueft ob es leere antworten gibt - diese sind nicht zulaessig
$(".answerinput").each(function(){
    if ($(this).val == "" || $(this).val() == " " || $(this).html() == " " || $(this).val() == ""){
        $(".modal-title").html("Error");
        $(".modal-body").html("Leere Antwort moeglichkeit unzulaessig");
        $("#modalbox").modal("show");
        emptyStatus = true;
    }
});
if (emptyStatus){
    return false;
}
}

你正在使用jQuery和turbollinks吗?我有同样的问题与我的javascript代码和解决方案是使用gem 'jquery- turbollinks '。您还需要在application.js中以正确的顺序要求它:

//=需要jquery

//=需要jquery.turbolinks

//=所有其他脚本

//=require turbollinks(这应该是最后一个!)

似乎你正在使用旧版本的rails可能<所以application.js文件不在那里>

在你的布局中包含它。在views/layouts/application.html.erb

中添加以下行
<%= javascript_include_tag "myJSfunctions.js" %>