将三个加/减按钮与五个数字计数器组合在一起

时间:2017-11-28 19:12:53

标签: javascript jquery

根据标题我有三个加/减按钮,三个按钮必须彼此独立,即当点击一个按钮时,其他两个按钮的输出不受影响。这三个都需要在两个独立的输出中显示它们的总输出。 我已经研究过这个并尝试了一些试验和错误的东西,但还没有运气。我希望我已经解释过自己好了,请在这里写下https://codepen.io/anon/pen/RjeGQy以及下面的代码。如果有帮助我可以使用jquery。

<input type="text" value="0" class="count"><br><br>
<input type="text" value="0" class="count"><br><br>

<input type="button" value="-" onclick="minus()">
<input type="text" value="0" class="count">
<input type="button" value="+" onclick="plus()"><br><br>
<input type="button" value="-" onclick="minus()">
<input type="text" value="0" class="count">
<input type="button" value="+" onclick="plus()"><br><br>
<input type="button" value="-" onclick="minus()">
<input type="text" value="0" class="count">
<input type="button" value="+" onclick="plus()"> 

var count = 1;
    var countEl = document.querySelectorAll(".count");
    function plus(){
        count++;
        countEl.value = count;
    }
    function minus(){
      if (count > 1) {
        count--;
        countEl.value = count;
      }  

更新

到目前为止,感谢您的回答。澄清我想要实现的目标,因为解释起来非常复杂: 三个按钮/计数器可以在任何时候具有三个不同的输出,例如1 2 3总共6个,需要在两个独立计数器中显示6个,每次使用按钮/计数器时该数字被添加或取消。

UPDATE1

新代码和笔,请参阅下面的评论

<input type="number" name="quantity1" value="0">
<input type="number" name="quantity1" value="0"><br><br><br>

<input type="button" class="" data-quantity="minus" data-field="quantity1" value="-">
<input type="number" name="quantity1" value="0">
<input type="button" class="" data-quantity="plus" data-field="quantity1" value="+">

<input type="button" class="" data-quantity="minus" data-field="quantity2" value="-">
<input type="number" name="quantity2" value="0">
<input type="button" class="" data-quantity="plus" data-field="quantity2" value="+">

<input type="button" class="" data-quantity="minus" data-field="quantity3" value="-">
<input type="number" name="quantity3" value="0">
<input type="button" class="" data-quantity="plus" data-field="quantity3" value="+">

jQuery(document).ready(function() {
  // This button will increment the value
  $('[data-quantity="plus"]').click(function(e) {
    // Stop acting like a button
    e.preventDefault();
    // Get the field name
    fieldName = $(this).attr("data-field");
    // Get its current value
    var currentVal = parseInt($("input[name=" + fieldName + "]").val());
    // If is not undefined
    if (!isNaN(currentVal)) {
      // Increment
      $("input[name=" + fieldName + "]").val(currentVal + 1);
    } else {
      // Otherwise put a 0 there
      $("input[name=" + fieldName + "]").val(0);
    }
  });
  // This button will decrement the value till 0
  $('[data-quantity="minus"]').click(function(e) {
    // Stop acting like a button
    e.preventDefault();
    // Get the field name
    fieldName = $(this).attr("data-field");
    // Get its current value
    var currentVal = parseInt($("input[name=" + fieldName + "]").val());
    // If it isn't undefined or its greater than 0
    if (!isNaN(currentVal) && currentVal > 0) {
      // Decrement one
      $("input[name=" + fieldName + "]").val(currentVal - 1);
    } else {
      // Otherwise put a 0 there
      $("input[name=" + fieldName + "]").val(0);
    }
  });
});

https://codepen.io/anon/pen/NwOLNL

2 个答案:

答案 0 :(得分:0)

当你标记这个jQuery时,我正在使用jQuery来促进某些部分。而且我不确定为什么你需要将相同的数据输出到多个位置,但这也应该是非常轻松的。

编辑注意:您在评论中指出您希望三个字段相加(添加所有三个值)而不是连接(创建所有三个值的字符串)。这实际上是一个非常小的变化,只需更改循环中的处理,我们遍历所有plusMinusWidgets。这是删除逗号行,并更改我们将字段组合到resultEl字段的方式 - 默认情况下,它们被视为字符串。我编辑了代码以将它们强制转换为Number值,并将它们添加到当前resultEl字段(我也将其转换为Number值)。

var resultEl = $(".resultSet");

$(".plusMinusThing").on("click", ".minusBtn", function(){
  var currentWidget = $(this).parents(".plusMinusThing");
  var countEl = currentWidget.find(".count");
  countEl.val(Number(countEl.val())-1);
  countEl.trigger("change");
}).on("click", ".plusBtn", function(){
  var currentWidget = $(this).parents(".plusMinusThing");
  var countEl = currentWidget.find(".count");
  countEl.val(Number(countEl.val())+1);
  countEl.trigger("change");
}).on("change keyup", ".count", function(){
  resultEl.val("");
  /******
   * This is the only piece changed in order to sum the fields,
   *   rather than concatenate them. I've removed the comma,
   *   and I've cast the element values to numbers, then added.
   ******/
  $(".plusMinusThing").each(function(index, element){
    // Set the value of the resultEl to itself plus the next
    //  count el. Note it will work if the value is negative.
    resultEl.val( Number(resultEl.val() ) + Number($(element).find(".count").val() ) );
  })
})
fieldset {
  border: 0;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<fieldset class="results">
  <input type="text" class="resultSet" />
</fieldset>
<hr/>
<fieldset class="plusMinusThing">
  <input type="button" class="minusBtn" value="-">
  <input type="text" value="0" class="count">
  <input type="button" class="plusBtn" value="+">
  <br>
</fieldset>
<fieldset class="plusMinusThing">
  <input type="button" class="minusBtn" value="-">
  <input type="text" value="0" class="count">
  <input type="button" class="plusBtn" value="+">
  <br>
</fieldset>
<fieldset class="plusMinusThing">
  <input type="button" class="minusBtn" value="-">
  <input type="text" value="0" class="count">
  <input type="button" class="plusBtn" value="+">
  <br>
</fieldset>

很多相同的事情没有jQuery的选项,尽管它有点复杂。以下介绍了相同的功能。最大的区别是我没有输出到多个目标els。否则,它处理的大致相同。

// Store references that all functions can use.
var resultEl = document.querySelector(".resultSet"),
  plusMinusWidgets = document.querySelectorAll(".plusMinusThing");

// Attach the handlers to each plus-minus thing
for (var i = 0; i < plusMinusWidgets.length; i++) {
  plusMinusWidgets[i].querySelector(".minusBtn").addEventListener("click", clickHandler);
  plusMinusWidgets[i].querySelector(".plusBtn").addEventListener("click", clickHandler);
  plusMinusWidgets[i].querySelector(".count").addEventListener("change", changeHandler);
}

/*****
 * both plus and minus use the same function, but value is set by the class of the
 *  button
 *****/
function clickHandler(event) {
  // reference to the count input field
  var countEl = event.target.parentNode.querySelector(".count");
  if (event.target.className.match(/\bminusBtn\b/)) {
    countEl.value = Number(countEl.value) - 1;
  } else if (event.target.className.match(/\bplusBtn\b/)) {
    countEl.value = Number(countEl.value) + 1;
  }
  // When we programmatically change the value, we need to manually trigger
  //  the change event.
  triggerEvent(countEl, "change");
};

/*****
 * changeHandler() processes whenever a plusMinusWidget's count el is changed.
 *  It iterates over all plusMinusWidgets, gets their count, and outputs that
 *  to the given resultEl input field.
 *****/
function changeHandler(event) {
  // remove all value from the result el.
  resultEl.value = 0;
  /******
   * Here is the only functional change, per your comment. Rather
   *  concatenating a string, you want to sum values of the 
   *  plusMinusWidget. To do this, we need to cast the value of each
   *  plusMinusWidget to a Number value, and add that to the Number
   *  value of the resultEl.
   *****/
  for (var i = 0; i < plusMinusWidgets.length; i++) {
    // Add the current plusMinusWidget value to the resultEl value.
    resultEl.value = Number(resultEl.value) + Number(plusMinusWidgets[i].querySelector('.count').value);

  }

};

/*****
 * triggerEvent() -- function to trigger an HTMLEvent on a given element.
 *  similar to jquery's trigger(), simply a convenience function. Not the
 *  point of this exercise.
 *****/

function triggerEvent(el, type){
   if ('createEvent' in document) {
        // modern browsers, IE9+
        var e = document.createEvent('HTMLEvents');
        e.initEvent(type, false, true);
        el.dispatchEvent(e);
    } else {
        // IE 8
        var e = document.createEventObject();
        e.eventType = type;
        el.fireEvent('on'+e.eventType, e);
    }
}
fieldset {
  border: 0;
}

.plusMinusThing {
  display: block;
  width: 206px;
  padding: 0;
  border: 1px solid #ccc;
}

.plusMinusThing input {
  float: left;
  margin: 0;
  border: 0;
}
<fieldset class="results">
  <input type="text" class="resultSet" />
</fieldset>
<fieldset class="plusMinusThing">
  <input type="button" class="minusBtn" value="-">
  <input type="text" value="0" class="count">
  <input type="button" class="plusBtn" value="+">
  <br>
</fieldset>
<fieldset class="plusMinusThing">
  <input type="button" class="minusBtn" value="-">
  <input type="text" value="0" class="count">
  <input type="button" class="plusBtn" value="+">
  <br>
</fieldset>
<fieldset class="plusMinusThing">
  <input type="button" class="minusBtn" value="-">
  <input type="text" value="0" class="count">
  <input type="button" class="plusBtn" value="+">
  <br>
</fieldset>

无论哪种方式,所有这一点的重点在于,由plusMinusWidget表示的复杂元素(包含plusBtn,minusBtn和count输入的fieldSet)应该是自包含的。我不想尝试确定哪个按钮引用了哪个元素 - 按钮是复杂元素的一部分,它们引用自己的计数输入。尝试使用DOM层次结构,尽可能让您的生活更轻松。

**额外的信用:因为我是简化的粉丝,我想用对象创建同样的效果。这种方法的优点是,我可以创建一个PlusMinusWidget,然后根据自己的喜好创建尽可能多的实例。页面设计者不必知道我的程序元素,她只需要为它们创建一个容器。以下代码将处理其他所有内容。

/******
 * Constructor for my plusMinusWidget complex input element.
 *  At this point, it contains two functions:
 *  -- __init() initializes the DOM elements and the event listeners for
 *            the current PlusMinusWidget. The double-underscore is a
 *            lazy attempt at hiding the function.
 *  -- getHtml() returns the DOM content, so we can append that into
 *            the DOM itself.
 *
 * It is designed to be used within a containing element, as i use that
 *    to handle the recalculation event. I don't want the PlusMinusWidgets
 *    to have to be aware of much. Ideally, I would have created a container
 *    complex widget to handle the event listening for the recalculate
 *    event, but this was purely a prototype. More refinement is always
 *    an option.
 ******/
 
var PlusMinusWidget = function(id){
  // when the new PlusMinusWidget gets created, we
  //  create the DOM node containing everything, and then
  //  we initialize the DOM content and the listeners.
  this.DOMEl = $("<fieldset>").addClass("plusMinusWidget");
  this.__init(id);
};

$.extend(PlusMinusWidget.prototype, {
  // init() gets called above, when we create the DOM structure and
  //   set up the listeners.
  __init: function(id){
    // create a reference to the DOMEl. This isn't necessary for creating
    //  the structures, but within the listeners, we can't use 'this.DOMEl'
    //  as the value of 'this' has changed. Thus, we create a reference here.
    var domEl = this.DOMEl;
    // If we don't get an ID, we don't want to error out, so set it to "".
    var id = id || "";
    
    // The three DOM components that will be part of the PlusMinusWidget
    var minusEl = $("<input>")
                   .addClass("minusBtn")
                   .attr("type", "button")
                   .val("-");
    var valueEl = $("<input>")
                   .addClass("quantity")
                   .attr("type", "text")
                   .val("0");
    var plusEl = $("<input>")
                   .addClass("plusBtn")
                   .attr("type", "button")
                   .val("+");
    
    // set the ID of the PlusMinusWidget, and insert the DOM els.
    domEl.attr("id", id).append(minusEl, valueEl, plusEl);
    
    /*****
     * Setting up the listeners. There are three events that
     *  are integral to this PlusMinusWidget, and one that is
     *  more external and could be handled elsewhere.
     *  .minusBtn.click
     *  .plusBtn.click
     *  .quantity.change / .quantity.keyup
     *
     *  ... and the external listener is the parent node's
     *      'plusMinus:recalculate', a custom event that we can
     *      monitor and handle.
     *****/
    domEl.on("click", ".minusBtn", function(){
      valueEl.val(Number(valueEl.val() ) -1);
      valueEl.trigger("change");
    }).on("click", ".plusBtn", function(){
      valueEl.val(Number(valueEl.val() ) + 1);
      valueEl.trigger("change");
    }).on("change keyup", ".quantity", function(){
      domEl.parent().trigger("plusMinus:recalculate");
    });
    /*****
     * the plusMinus:recalculate event is called on the DOMEl's parent
     *   node. This is the only el that should be aware of its child nodes,
     *   thus the only el that should have access to its descendant 
     *   PlusMinusWidget nodes. 
     *****/
    $(document).on("plusMinus:recalculate", domEl.parent(), function(){
      resultEl.val(0);
      $(".plusMinusWidget").each(function(){
        resultEl.val(Number(resultEl.val()) + Number($(this).find(".quantity").val()) )
      })
    })
  },
  getHtml: function(){
    return this.DOMEl;
  }
})
/******************
 * Everything above could be moved into
 *   a separate file, and saved as
 *   plusMinus.widget.js (for example). 
 *   That piece can be hidden from the end
 *   user -- all they need to know is the
 *   code below: how to initialize the 
 *   PlusMinusWidget object, and how to 
 *   use its sole public function, getHtml.
 *
 ******************/
// So here, we actually create an array of our PlusMinusWidget objects.
//  As each is created, it's initialized and its DOM el is populated.
var plusMinusWidgets = [new PlusMinusWidget("firstQty"), new PlusMinusWidget("secondQty"), new PlusMinusWidget("thirdQty")];

// Create the reference to our results input and to the container itself.
var resultEl = $(".resultSet");
var plusMinusContainer = $(".container");

// iterate over the array we created just above, and for each member of the
//   array, stick its DOM structure into the containing element. Note that this
//   handles all the DOM, all the listeners, everything. 
$.each(plusMinusWidgets, function(){
  plusMinusContainer.append(this.getHtml());
})
fieldset {
  border: 0;
}
.plusMinusThing {
  display: block;
  width: 206px;
  padding: 0;
  border: 1px solid #ccc;
}
.plusMinusThing input {
  float: left;
  margin: 0;
  border: 0;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<fieldset class="results">
  <input type="text" class="resultSet" />
</fieldset>
<div class="container">

</div>

这是再次使用jQuery创建的,仅仅因为它确实简化了对象和侦听器的创建,但它并非完全必要。同样,这种方法的优点在于DOM创建和事件监听器位完全隐藏在“引擎盖下”。最终用户真的只需要知道如何初始化PlusMinusWidget,以及如何将其弹出到DOM中。其他一切都无缝地发生。

而且,这只是另一种方法。不好,更好或最好,只是一个思想实验。

答案 1 :(得分:0)

我没有使用querySelectorAll来查找类计数的每个元素,而是给每个输入框一个ID,例如“input1”,“input2”,“input3”。

然后我会改变加号和减号函数来接受一个参数来指示它来自哪一行。

最后,我会用新值更新正确的输入。

它看起来像这样:

<?php
    function OpenConnectionMsSQL()
    {
        try{
            $serverName = "***";
            $database = "***";
            $uid = "***";
            $pwd = "***";

            $connectionOptions = array("Database"=>"$database","Uid"=>"$uid","PWD"=>"$pwd");
            $conn = sqlsrv_connect($serverName, $connectionOptions);
            if($conn == false)
                die( print_r( sqlsrv_errors(), true));
            }

        catch(Exception $e)
            {
                exit("<h1>"."Verbindung fehlgeschlagen!". "</br>". "Server Stopped"."</h1>");#.$e->getMessage());
                exit("<!--"."<h1>"."Serverstatus: Verbindung fehlgeschlagen!". "</br>". "Server Stopped"."</h1>"."-->");#.$e->getMessage();

            }
    }

?>