将文本字段添加到rails中的表单选择的最佳方法是什么?

时间:2013-11-30 16:24:27

标签: javascript ruby-on-rails forms coffeescript ruby-on-rails-4

在rails 4中,我有一个带有三个选项的表单选择,其中一个称为“其他”,我想显示一个文本字段,并将输入作为表单值发送到服务器。

.field
    = f.label :answer, 'Please select..'
    = f.select :answer, ['option a','option b','other...'], prompt: 'Select One'
    #other
     .other
      = f.text_field :answer

model.js.coffee

jQuery ->
  other = $('#other').html()
  $('.other').remove()
  if $('#mymodel_answer :selected').text() == 'other...'
    $('#other').html(other)
  $('#mymodel_answer').change ->
    if $('#mymodel_answer :selected').text() == 'other...'
      $('#other').html(other)
    if $('#mymodel_answer :selected').text() != 'other...'
      $('.other').remove()

这有效,但感觉有点hacky,有什么其他方法可以做到这一点?

1 个答案:

答案 0 :(得分:1)

未提交已禁用的表单元素,因此您只需添加一些CSS来隐藏已禁用的内容:

input[disabled] {
    display: none;
}

然后使用prop在事情发生变化时启用/禁用额外输入。所以给出了像这样的HTML:

<form>
    <select name="s" id="s">
        <option value="show">With extra thing</option>
        <option value="hide">No extra thing</option>
    </select>
    <input type="text" id="t" name="t" placeholder="extra thing...">
    <button type="submit">submit</button>
</form>
你可以说:

$('#s').change ->
    disabled = $(@).val() == 'hide'
    $('#t').prop('disabled', disabled)

显示启用/隐藏 - 禁用<input type="text"> <select>更改。

演示:http://jsfiddle.net/ambiguous/LmAMR/

如果您不想使用CSS隐藏已禁用的元素,那么您只需要进行适当的showhide调用:

$('#s').change ->
    disabled = $(@).val() == 'hide'
    fn       = if disabled then 'hide' else 'show'
    $('#t')[fn]().prop('disabled', disabled)

演示:http://jsfiddle.net/ambiguous/F8Dqn/