JavaScript输入值语法

时间:2018-08-29 17:57:37

标签: javascript jquery

我有<input>,该值取决于其他函数。
并且当值等于0时需要display: none

如何写这样的东西?

var SMTH = document.getElementById("INPUT"); 
if(SMTH.value = '0') {$("#INPUT").style.display = "none";}

 $(document).ready( function() {
        $('#BUBU-1, #BUBU-2, #BUBU-3').change( function() {
             var BOBY1 = Number( $('#BUBU-1:checked').val()||0);
             var BOBY2 = Number( $('#BUBU-2:checked').val()||0);
             var BOBY3 = Number( $('#BUBU-3:checked').val()||0);
             $('#SUM').val( BOBY1 + BOBY2 + BOBY3 );
        });
     });



   $('.SELECTOR').click(function (){
       var checkbox = $(this).find('input[type=checkbox]');
       checkbox.prop("checked", !checkbox.prop("checked")).trigger('change');
       });
   $('input[type=checkbox]').click(function (e){
       e.stopPropagation();
       return true;
       });
.SELECTOR {width: 100px; height: 100px; border: 1px solid red; cursor: pointer; text-align: center;}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="SELECTOR">
    <input type="checkbox" id="BUBU-1" value="250"> 
    <input type="checkbox" id="BUBU-2" value="750" > 
    <input type="checkbox" id="BUBU-3" value="500"> 
    <p>CLICK ME</p>
</div>

— <input id="SUM" style="border: 3px solid red; margin-top: 10px; width: 50px;">

1 个答案:

答案 0 :(得分:2)

您已经对复选框的值求和,因此您可以简单地检查总计并使用jQuery的toggle()方法隐藏/显示输入(如果该总计的值大于0):

$(document).ready(function() {
  $('#BUBU-1, #BUBU-2, #BUBU-3').change(function() {
    var BOBY1 = Number($('#BUBU-1:checked').val() || 0);
    var BOBY2 = Number($('#BUBU-2:checked').val() || 0);
    var BOBY3 = Number($('#BUBU-3:checked').val() || 0);
    var total = BOBY1 + BOBY2 + BOBY3; // get the total
    $('#SUM').val(total).toggle(total > 0); // set the value and show/hide the element 
  });

  $('.SELECTOR').click(function() {
    var checkbox = $(this).find('input[type=checkbox]');
    checkbox.prop("checked", !checkbox.prop("checked")).trigger('change');
  });
  $('input[type=checkbox]').click(function(e) {
    e.stopPropagation();
    return true;
  });
});
.SELECTOR {
  width: 100px;
  height: 100px;
  border: 1px solid red;
  cursor: pointer;
  text-align: center;
}

#SUM {
  display: none;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="SELECTOR">
  <input type="checkbox" id="BUBU-1" value="250">
  <input type="checkbox" id="BUBU-2" value="750">
  <input type="checkbox" id="BUBU-3" value="500">
  <p>CLICK ME</p>
</div>

— <input id="SUM" style="border: 3px solid red; margin-top: 10px; width: 50px;">