2013-02-15 73 views
0

我有一个包含选择器的窗体。有一个“添加新的”选项,当它被选中时,一个文本输入是用jquery动态生成的。现在我需要做的就是提交,检查是否存在文本输入,如果存在,使用该信息更新表并忽略选择器。我的问题是我应该在带有表单验证的模型中执行此操作吗?还是有更合适的方法?提交轨道形式逻辑

选择:

<%= builder.select(:line_id, ['~ Add New ~'] + Line.all.collect {|p| [p.title, p.id ]}, { :include_blank => 'select line' }, :id => "line_selector") 

的jQuery:

$(document).ready(function(){ 
    $("#line_selector").on("change", function() { 
     if($(this).prop("selectedIndex") == 1) { 
      console.log($("#line_selector").prop("selectedIndex")); 
      var new_line_title = prompt('Please enter a line title'); 
      if(!new_line_title.length) { 
       console.log("no entry"); 
       return; 
      }; 
      console.log(new_line_title); 
      $(this).after($(document.createElement("input")) 
       .attr("type", "text") 
       .attr("id", "text") 
       .attr("name", "text") 
       .attr("value", new_line_title)); 
     }; 
    }); 
}); 

enter image description here

回答

0

我不知道是否有更好的方法,但我会做到这一点与自定义验证模型,如你所说。对我而言,这是定义应用程序行为的最佳位置。

0

我只想为文本字段设置attr_accesor,并在模型中设置after_initialize回调来设置行属性。

此外,这与您的问题本身无关,但您是否打算在从下拉列表中选择其他值时隐藏输入?如果是这样,而不是动态地添加元素,为什么不切换()和禁用/启用文本字段?

+0

当您选择除“添加新”之外的任何内容时,输入不会显示。当“添加新”被选中时,它是用javascript动态创建的 – 2013-02-15 21:28:05