I have a checkbox with a explanatory Text:
<%= f.label :is_company do %>
<%= f.check_box :is_company %> <span>Are you Representing a Company / Organization ?</span>
<% end %>
I need to change the text (if checkbox is triggered) from Are you Representing a Company / Organization ?
to I'm representing a Company / Organization !
Can anyone help me out ?
HTML Output :
<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>
I work in coffeescript
So i made this abomination:
$(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()
but i think its a lot of code, for nothing...
Something like this should work. If it doesn't, have a play and tweak, then come back if you still have trouble.
$(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 ?")
Note: there is possibly an even shorter way to do this with jQuery toggle
, but I have limited knowledge of 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 ?"
Compiles to...
$(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 ?");
});
});
Demo: http://jsfiddle.net/VcFCL/
Some comments on my code choices...
# 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 ?"
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.