2013-10-07 128 views
0

我正在使用Rails应用程序。在index.html.haml上,我还渲染了_form.html.haml(用于新增和编辑操作)。索引页面上有一个“添加组”链接,点击时应禁用表单中的某些字段。我已经为它写了jquery代码。我的问题是,当我点击链接时,这些字段被禁用(变灰),但立即再次启用。如果我刷新页面,则会看到禁用的字段。当我点击链接并保持禁用时,我希望它发生。jquery禁用不起作用

jQuery代码

$(function(){ 
    $("#add_requirement_group").click(function() { 
     $("#requirement_text_full, #requirement_requirement_type").prop("disabled", true); 
    }); 
}); 

表为新的和编辑的操作。

= form_for ([@requirement.requirements_template, @requirement]), html: { class: "form-horizontal" } do |f| 
    - if @requirement.errors.any? 
    #error_explanation 
     %h2= "#{pluralize(@requirement.errors.count, "error")} prohibited this requirement from being saved:" 
     %ul 
     - @requirement.errors.full_messages.each do |msg| 
      %li= msg %fieldset 
    .control-group 
     = f.hidden_field :parent_id 
    .control-group 
     = f.label :text_brief, class: "control-label" 
     .controls 
     = f.text_field(:text_brief, class: "input-block-level") 
    .control-group 
     = f.label :text_full, class: "control-label" 
     .controls 
     = f.text_area(:text_full, rows: 5, class: "input-block-level") 
    .control-group 
     = f.label :obligation, class: "control-label" 
    .control-group 
     = f.label :requirement_type, class: "control-label" 
     .controls 
     = f.select :requirement_type, options_for_select([:text, :numeric, :date, :enum]), include_blank: true 
     .actions.pull-right 
    %br/ 
    = f.submit 'Save', class: 'btn btn-info' 
    = button_to 'Finish', '#', class: 'btn btn-info', method: :get 

index.html.haml

%hr 
.row-fluid 
    .span4 
    %fieldset.template_outline 
     %strong Template Outline 
     %br 
     = link_to 'Add Group', new_requirements_template_requirement_path(@requirements_template), id: "add_requirement_group" 
     %hr 
     = render 'form' 

我知道它是这样一个简单的代码,但由于某种原因,如预期的那样禁止是行不通的。

回答

0

好的。当点击“添加组”链接时,点击事件处理程序将触发,这将按照您的预期禁用HTML控件。但是,它会继续并重定向到“new_requirements_tempate_reqquirement_path”,我认为您不希望它这样做。为了抑制DOM元素的默认操作,您可能希望使用“preventDefault()方法。

$(function(){ 
    $("#add_requirement_group").click(function(e) { 
     e.preventDefault(); 
     $("#requirement_text_full, #requirement_requirement_type").prop("disabled", true); 
    }); 
}); 

您所描述的行为告诉我,你正在使用的Turbo-链接,船舶on Rails的4

标准
+0

嗨,它的工作!谢谢你这么多,但一个简短的问题。当你说“为了抑制DOM元素的默认行为”在这种情况下,你是什么意思? – bhvd

+0

没关系弄清楚你的意思。再次感谢您。 – bhvd

+0

没问题,如果您能将我的标记为答案,我将不胜感激。谢谢。:) –