在rails中选择向表单添加文本字段的最佳方式

What is the best way to add a text field to a form select in rails?

本文关键字:字段 文本 最佳 方式 添加 表单 rails 选择      更新时间:2023-12-19

在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()

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

禁用的表单元素不会被提交,所以你可以添加一点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)

以在CCD_ 3改变时显示启用/隐藏禁用CCD_。

演示: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/