Search code examples
javascriptjqueryarrayscss-selectorsinputbox

jQuery: Calculate multidimensional array by keyname


i've confused how to do calculation in javascript while using multidimensional array, i have form like this

<input type=number name="sell['FRUIT']['YELLOW']">
<input type=number name="stock['FRUIT']['YELLOW']" value=100 disabled>
<input type=number name="newstock['FRUIT']['YELLOW']" disabled>

<input type=number name="sell['WOOD']['BLACK']">
<input type=number name="stock['WOOD']['BLACK']" value=50 disabled>
<input type=number name="newstock['WOOD']['BLACK']" disabled>

<input type=number name="sell['VEGETABLE']['RED']">
<input type=number name="stock['VEGETABLE']['RED']" value=25 disabled>
<input type=number name="newstock['VEGETABLE']['RED']" disabled>

<input type=number name="sell['VEGETABLE']['GREEN']">
<input type=number name="stock['VEGETABLE']['GREEN']" value=40 disabled>
<input type=number name="newstock['VEGETABLE']['GREEN']" disabled>

that FRUIT/WOOD/VEGETABLE and COLOR Keys are Dinamicaly generated from PHP, it can be anything, but will have same key and subkey on that sell, stock and newstock array.

What i need to do is calculate and put the value on newstock input box by substracting stock with sell from user input.


Solution

  • Either be careful with the quotes or use jQuery.escapeSelector:

    $(function() {
      $('input[name^="sell"]').on("change", function() {
        var name2 = this.name.replace(/^sell/, "stock");
        var name3 = this.name.replace(/^sell/, "newstock");
        var diff = $('input[name="' + $.escapeSelector(name2) + '"]').val() - $(this).val();
                   $('input[name="' + $.escapeSelector(name3) + '"]').val(diff);
      });
    });
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
    
    <input type=number name="sell['FRUIT']['YELLOW']">
    <input type=number name="stock['FRUIT']['YELLOW']" value=100 disabled>
    <input type=number name="newstock['FRUIT']['YELLOW']" disabled>
    
    <input type=number name="sell['WOOD']['BLACK']">
    <input type=number name="stock['WOOD']['BLACK']" value=50 disabled>
    <input type=number name="newstock['WOOD']['BLACK']" disabled>
    
    <input type=number name="sell['VEGETABLE']['RED']">
    <input type=number name="stock['VEGETABLE']['RED']" value=25 disabled>
    <input type=number name="newstock['VEGETABLE']['RED']" disabled>
    
    <input type=number name="sell['VEGETABLE']['GREEN']">
    <input type=number name="stock['VEGETABLE']['GREEN']" value=40 disabled>
    <input type=number name="newstock['VEGETABLE']['GREEN']" disabled>