2015-08-13 22 views
0

我有以下形式:在端的外部js函數不火

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

提交checkAnswers()的JS函數應該叫和做一些檢查。

如果我在html.erb中有這個函數,它工作正常。 ...但是當我將它設置爲public/javascript/myJSfunctions.js時,它無法工作。

js文件包含在佈局中。可能是什麼問題呢?

功能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; 
} 
} 
+0

你應該包括你的JS文件上面 – vladra

+0

加js文件,把你的JavaScript文件中的應用程序/資產/ JavaScript和不忘記要求它在application.js – Felix

+0

嘗試此處 –

回答

1

您是否使用jQuery和Turbolinks?我與我的JavaScript代碼有同樣的問題,解決方案是使用gem'jquery-turbolinks'。您還需要要求它以正確的順序在你的application.js:

// =需要的jQuery

// =需要jquery.turbolinks

// =所有其它腳本

// =需要turbolinks(這應該是最後一個!)

+0

謝謝,但我不使用turbolinks – Felix

+0

你有沒有嘗試過: <%= javascript_include_tag「javascript/myJSfunctions.js」%> –

1

好像你正在使用舊版本的rails可能是< rails3,所以application.js文件不存在。

通過您的佈局包括它。 添加下面一行到你的意見/佈局/ application.html.erb

<%= javascript_include_tag "myJSfunctions.js" %> 
+0

多數民衆贊成在我的工作! – Felix

+0

嘗試放置JavaScript警報,看看它是否被調用。將提交更改爲{:onsubmit =>「alert(1);」}。如果你沒有得到這個警報意味着你正在做一些錯誤的語法。 – Ann10