Javascript 如果选中,则更改文本-复选框
我有一个带有解释性文本的复选框:Javascript 如果选中,则更改文本-复选框,javascript,ruby-on-rails,checkbox,coffeescript,Javascript,Ruby On Rails,Checkbox,Coffeescript,我有一个带有解释性文本的复选框: <%= f.label :is_company do %> <%= f.check_box :is_company %> <span>Are you Representing a Company / Organization ?</span> <% end %> 我在咖啡馆工作 所以我做了一件可憎的事: $(document).on "ready page
<%= f.label :is_company do %>
<%= f.check_box :is_company %> <span>Are you Representing a Company / Organization ?</span>
<% end %>
我在咖啡馆工作
所以我做了一件可憎的事:
$(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()
但是我认为它有很多代码,没有任何代价……类似的东西应该可以工作。如果没有,那就玩一玩,调整一下,如果你还有问题就回来
$(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 ?")
注意:使用jQuerytoggle
可能有一种更短的方法来实现这一点,但我对JS的了解有限
$ ->
$("#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 ?"
到目前为止你尝试了什么?使用Javascript。使用复选框状态在
span
之间切换文本。我对咖啡相当陌生,所以我使用了很多教程或代码片段中的代码。但似乎我无法让它工作。你能显示上面erb的html输出吗?@DamienRoche你能把代码作为答案写下来让我看一下吗?请随意发送任何错误。我怀疑复制/粘贴就行了。可能需要修改一些内容。您介意和我一起聊天吗?->
# 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 ?"