簡體   English   中英

如果選中則更改文本-復選框

[英]Change Text if checked - checkbox

我有一個帶有說明文字的復選框:

<%= 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 ?更改文本(如果觸發了復選框) 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>

寫咖啡

所以我做了這個可憎的事情:

$(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 ?")

注意:使用jQuery toggle可能有更短的方法,但是我對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 ?");
  });
});

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

關於我的代碼選擇的一些評論...

# 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 ?"

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM