【问题标题】:Using a Button as "checkbox" in form_for?在form_for中使用按钮作为“复选框”?
【发布时间】:2017-03-02 15:53:11
【问题描述】:

目前我正在为自己构建一个小项目并提出了一个想法。

您可以在 form_for 中使用按钮作为切换来在 DB 中设置布尔值吗? 如果 bool 为真,我想要一个绿色按钮,如果 bool 为假,我想要一个红色按钮。

如果我点击按钮,它应该改变他的颜色和值,如果我提交表单,它应该将该值传递给 create 方法。

有什么想法吗?

【问题讨论】:

  • 使用普通复选框,并研究“自定义复选框”,看看有哪些技术可以让它们按您的意愿显示。

标签: javascript ruby-on-rails ajax ruby-on-rails-5


【解决方案1】:

你可以试试这样 Orginal link from where code is taken

.switch {
  position: relative;
  display: inline-block;
  width: 60px;
  height: 34px;
}

.switch input {display:none;}

.slider {
  position: absolute;
  cursor: pointer;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background-color: red;
  -webkit-transition: .4s;
  transition: .4s;
}

.slider:before {
  position: absolute;
  content: "";
  height: 26px;
  width: 26px;
  left: 4px;
  bottom: 4px;
  background-color: white;
  -webkit-transition: .4s;
  transition: .4s;
}

input:checked + .slider {
  background-color: #2196F3;
}

input:focus + .slider {
  box-shadow: 0 0 1px #2196F3;
}

input:checked + .slider:before {
  -webkit-transform: translateX(26px);
  -ms-transform: translateX(26px);
  transform: translateX(26px);
}

/* Rounded sliders */
.slider.round {
  border-radius: 34px;
}

.slider.round:before {
  border-radius: 50%;
}
<!DOCTYPE html>
<html>
<head></head>
<body>

<h2>Toggle Switch</h2>

<label class="switch">
  <input type="checkbox">
  <div class="slider"></div>
</label>

<label class="switch">
  <input type="checkbox" checked>
  <div class="slider"></div>
</label><br><br>

<label class="switch">
  <input type="checkbox">
  <div class="slider round"></div>
</label>

<label class="switch">
  <input type="checkbox" checked>
  <div class="slider round"></div>
</label>

</body>
</html> 

【讨论】:

    【解决方案2】:

    所以,我认为自定义复选框是更好的选择,但是,如果您真的想使用按钮,我会使用隐藏的复选框字段并将 onclick 函数应用于按钮以更改隐藏的复选框字段的值. 这里有一个大意的笔http://codepen.io/kaykayyali/pen/WpwvyE

    HTML

    <input type='checkbox' id='hidden_check_box'>
    <button class='red' id='toggle_button' onclick="toggle_checkbox()">
    

    CSS

    input[type='checkbox'] {
      display: none;
    }
    
    button {
      width: 20px;
      height: 20px;
      margin: 5px;
    }
    
    .green {
      background-color: green;
    }
    
    .red {
      background-color: red;
    }
    

    JS

    function toggle_checkbox() {
      var checkbox = document.getElementById('hidden_check_box');
      var button = document.getElementById('toggle_button');
      if (!checkbox.checked) {
        checkbox.checked = true;
        button.className = 'green';
      }
      else {
        checkbox.checked = false;
        button.className = 'red';
      }
      console.log(checkbox.checked);
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2014-04-23
      • 1970-01-01
      • 2011-05-18
      • 2011-08-20
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多