我有一个带有解释性文字的复选框:
<%= f.label :is_company do %>
<%= f.check_box :is_company %> <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">
<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()
但我觉得它的代码很多,一无所有......
答案 0 :(得分: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的了解有限。
答案 1 :(得分:0)
$ ->
$("#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 ?");
});
});
关于我的代码选择的一些评论...
# 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 ?"