【问题标题】:Change Text if checked - checkbox如果选中则更改文本 - 复选框
【发布时间】:2014-02-01 20:40:42
【问题描述】:

我有一个带有说明文字的复选框:

<%= f.label :is_company do %>
  <%= f.check_box :is_company %>&nbsp;&nbsp; <span>Are you Representing a Company / Organization ?</span>
<% end %> 

我需要将文本(如果触发复选框)从 Are you Representing a Company / Organization ? 更改为 I'm representing a Company / Organization !

谁能帮帮我?

HTML 输出:

<label for="user_is_company">
  <input name="user[is_company]" type="hidden" value="0">
  <input id="user_is_company" name="user[is_company]" type="checkbox" value="1">&nbsp;&nbsp; 
  <span>Are you Representing a Company / Organization ?</span>
</label>

我在 coffeescript

工作

所以我做了这个可憎的:

$(document).on "ready page:load", ->
  check = ->
    if input.checked
      document.getElementById("label_cmp").innerHTML = "I am representing a Company / Organization !"
    else
      document.getElementById("label_cmp").innerHTML = "Are you representing a Company / Organization ?"
  input = document.querySelector("input[type=checkbox]")
  input.onchange = check
  check()

但我认为它有很多代码,一无所获......

【问题讨论】:

  • 到目前为止你尝试了什么?
  • 使用 Javascript。使用复选框状态切换 span 之间的文本。
  • 我对咖啡还很陌生,所以我使用了很多在教程或 sn-ps 上找到的代码。但似乎我无法让它工作。
  • 你能从上面的erb显示你的html输出吗?
  • @DamienRoche 你能把代码写成答案让我看看吗?

标签: javascript ruby-on-rails checkbox coffeescript


【解决方案1】:

这样的东西应该工作。如果没有,请尝试一下并进行调整,如果仍有问题,请返回。

$(document).on "ready page:load", ->
  $("input#user_is_company").on 'change', ->
    if $(this).is(":checked")
      $("#label_cmp").text("I'm representing a Company / Organization !")
    else
      $("#label_cmp").text("Are you Representing a Company / Organization ?")

注意:使用 jQuery toggle 可能有更短的方法来执行此操作,但我对 JS 的了解有限。

【讨论】:

【解决方案2】:
$ ->
  $("#user_is_company").on 'change', ->
      $("#label_cmp").text if $(this).is(":checked") then "I am representing a Company / Organization !" else "Are you representing a Company / Organization ?"

编译为...

$(function() {
  return $("#user_is_company").on('change', function() {
    return $("#label_cmp").text($(this).is(":checked") ? "I am representing a Company / Organization !" : "Are you representing a Company / Organization ?");
  });
});

演示:http://jsfiddle.net/VcFCL/

我的代码选择上的一些 cmets...

# jquery shorthand form for on-ready wrapper function
# ensures DOM is loaded before executing inner function
$ ->
  # identify elements by ID alone, as ID should be unique on the page
  # listen for `change` event on selected element, and run callback
  $("#user_is_company").on 'change', ->
    # set the text of the label conditionally by the `checked` status of the selected element
    $("#label_cmp").text if $(this).is(":checked") then "I am representing a Company / Organization !" else "Are you representing a Company / Organization ?"

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2016-03-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-01-08
    • 2012-06-19
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多