更改一个字段的输入值,当另一个字段键入不适用于多个字段

发布于 2025-02-12 00:55:30 字数 2665 浏览 2 评论 0原文

我有一个我有一个表格的网站,该表格有3个字段,可以在单击时多次添加,我的代码如下:

$(document).ready(function() {
  var max_fields = 10;
  var wrapper = $(".container1");
  var add_button = $("#niy");

  var x = 1;
  $(add_button).click(function(e) {
    e.preventDefault();
    if (x < max_fields) {
      x++;
      $(wrapper).append('<div class="col-lg-4 col-sm-6"><div class="mb-4"><label for="client_type">Service Type</label><input type="text" class="form-control" id="client_type" required name="service[]"></div></div><div class="col-lg-4 col-sm-6"><div class="mb-4"><label for="client_type">Price</label><input type="text" class="form-control" id="client_type" required name="price[]"></div></div><div class="col-lg-4 col-sm-6"><div class="mb-4"><label for="client_type">Total</label><input type="text" class="form-control" id="total" required name="total[]"></div></div>'); //add input box
    } else {
      alert('You Reached the limits')
    }
  });

  $(wrapper).on("click", ".delete", function(e) {
    e.preventDefault();
    $(this).parent('div').remove();
    x--;
  })
});



$('input[name="price[]"]').change(function() {
  $('input[name="total[]"]').val($(this).val());
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="row container1">
  <div class="col-lg-4 col-sm-6">
    <!-- Form -->
    <div class="mb-4">
      <label for="client_type">Service Type</label>
      <input type="text" class="form-control" id="client_type" required name="service[]">
    </div>
  </div>
  <div class="col-lg-4 col-sm-6">
    <!-- Form -->
    <div class="mb-4">
      <label for="client_type">Price</label>
      <input type="text" class="form-control" id="client_type" required name="price[]">
    </div>
  </div>
  <div class="col-lg-4 col-sm-6">
    <!-- Form -->
    <div class="mb-4">
      <label for="client_type">Total</label>
      <input type="text" class="form-control" id="client_type" required name="total[]">
    </div>
  </div>
</div>
<a id="niy" class="btn btn-warning" style="color:white">Add New Service Field &nbsp;
      <span style="font-size:16px; font-weight:bold;">+ </span>
    </a>

我希望总字段从各自的价格字段中显示值

i have a website where i have a form, the form has 3 fields which can be addedd multiple times on click, my code is like below:

$(document).ready(function() {
  var max_fields = 10;
  var wrapper = $(".container1");
  var add_button = $("#niy");

  var x = 1;
  $(add_button).click(function(e) {
    e.preventDefault();
    if (x < max_fields) {
      x++;
      $(wrapper).append('<div class="col-lg-4 col-sm-6"><div class="mb-4"><label for="client_type">Service Type</label><input type="text" class="form-control" id="client_type" required name="service[]"></div></div><div class="col-lg-4 col-sm-6"><div class="mb-4"><label for="client_type">Price</label><input type="text" class="form-control" id="client_type" required name="price[]"></div></div><div class="col-lg-4 col-sm-6"><div class="mb-4"><label for="client_type">Total</label><input type="text" class="form-control" id="total" required name="total[]"></div></div>'); //add input box
    } else {
      alert('You Reached the limits')
    }
  });

  $(wrapper).on("click", ".delete", function(e) {
    e.preventDefault();
    $(this).parent('div').remove();
    x--;
  })
});



$('input[name="price[]"]').change(function() {
  $('input[name="total[]"]').val($(this).val());
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="row container1">
  <div class="col-lg-4 col-sm-6">
    <!-- Form -->
    <div class="mb-4">
      <label for="client_type">Service Type</label>
      <input type="text" class="form-control" id="client_type" required name="service[]">
    </div>
  </div>
  <div class="col-lg-4 col-sm-6">
    <!-- Form -->
    <div class="mb-4">
      <label for="client_type">Price</label>
      <input type="text" class="form-control" id="client_type" required name="price[]">
    </div>
  </div>
  <div class="col-lg-4 col-sm-6">
    <!-- Form -->
    <div class="mb-4">
      <label for="client_type">Total</label>
      <input type="text" class="form-control" id="client_type" required name="total[]">
    </div>
  </div>
</div>
<a id="niy" class="btn btn-warning" style="color:white">Add New Service Field  
      <span style="font-size:16px; font-weight:bold;">+ </span>
    </a>

i want the total field to show the value from its respective price field, however here only first row does that, can anyone please tell me how to fix this, thanks in advance

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

白云悠悠 2025-02-19 00:55:30

代码中的主要问题是因为您仅绑定更改事件,该事件会在页面首次加载时更新字段的值。这忽略了动态添加的所有字段。要修复此使用委托事件处理程序 - 与.delete按钮一样。

话虽如此,值得注意的是,还有其他几个问题需要解决:

  • 不要在DOM中重复相同的id属性值。他们需要是独一无二的。另外,在内容中根本不使用id,可以动态重复。使用class属性。
  • 不要使用样式属性使用内联样式。将一种代码放入另一种代码是不好的习惯,例如。您的HTML中的CSS或JS中的HTML。在这种情况下,使用外部样式表。
  • 同样,不要将HTML放入JS。克隆现有内容,而不是将大量HTML倾倒在JS中。在您的原始内容中,如果您更改了HTML模板,则还需要记住也需要更新JS文件。使用克隆可以避免此问题。
  • 不要将您的jQuery对象包裹起来。例如。 add_button已经是jQuery对象,您不需要使用$(add_button)。因此,值得以$将jQuery对象的变量名称前缀。
  • 在可能的情况下不要使用全局变量。出于各种原因,它们是不良的练习,尤其是它们会导致更长,更难维护代码。在这种情况下,更好的方法是检索DOM中现有的元素数量,并将其与已知限制进行比较。

话虽如此,这是一个工作的演示:

jQuery($ => {
  var max_fields = 10;
  var $container = $(".container");
  var $add_button = $("#niy");

  $add_button.on('click', e => {
    e.preventDefault();

    if ($('.row').length >= max_fields) {
      alert('You Reached the limits');
      return;
    }

    let $newContent = $('.row:first').clone().appendTo($container);
    $newContent.find(':input').val('');
  });

  $container.on("click", ".delete", e => {
    e.preventDefault();
    $(e.target).closest('.row').remove();
  })

  $container.on('change', '.price', e => {
    $(e.target).closest('.row').find('.total').val(e.target.value);
  });
});
body {
  background-color: #CCC;
}

#niy {
  color: white;
}

#niy span {
  font-size: 16px;
  font-weight: bold;
}

label {
  width: 100px;
  display: inline-block;
}

.row:first-child .delete {
  display: none;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="container">
  <div class="row">
    <div class="col-lg-4 col-sm-6">
      <div class="mb-4">
        <label for="client_type">Service Type</label>
        <input type="text" class="form-control service" required name="service[]">
      </div>
    </div>
    <div class="col-lg-4 col-sm-6">
      <div class="mb-4">
        <label for="client_type">Price</label>
        <input type="text" class="form-control price" required name="price[]">
      </div>
    </div>
    <div class="col-lg-4 col-sm-6">
      <div class="mb-4">
        <label for="client_type">Total</label>
        <input type="text" class="form-control total" required name="total[]">
      </div>
    </div>
    <a href="#" class="delete">Delete</a>
  </div>
</div>
<a id="niy" class="btn btn-warning">
  Add New Service Field  
  <span>+ </span>
</a>

The main issue in your code is because you only bind the change event which updates the value of the fields when the page first loads. This ignores all the fields which are added dynamically. To fix this use delegated event handlers - exactly as you are for the .delete button.

That being said, it's worth noting that there's several other issues which need to be addressed:

  • Don't repeat the same id attribute value in the DOM. They need to be unique. Also, don't use id at all in content which can be repeated dynamically. Use class attributes instead.
  • Don't use inline styling with the style attribute. It's bad practice to put one type of code in another, eg. CSS in your HTML, or HTML in your JS. In this case use an external stylesheet.
  • Similarly, don't put HTML in your JS. Clone existing content instead of dumping a lot of HTML in the JS. In your original, if you changed the HTML template, then you'd need to also remember to update the JS file too. Using cloning avoids this problem.
  • Don't double-wrap your jQuery objects. Eg. add_button is already a jQuery object, you don't need to use $(add_button). It's worth prefixing variable names that hold jQuery objects with $ for this reason.
  • Don't use global variables where possible. They're bad practice for a variety of reasons, not least of which is that they lead to more length and harder to maintain code. A better approach in this case is to retrieve the number of elements already existing in the DOM and compare that to the known limit.

With all that said, here's a working demo:

jQuery($ => {
  var max_fields = 10;
  var $container = $(".container");
  var $add_button = $("#niy");

  $add_button.on('click', e => {
    e.preventDefault();

    if ($('.row').length >= max_fields) {
      alert('You Reached the limits');
      return;
    }

    let $newContent = $('.row:first').clone().appendTo($container);
    $newContent.find(':input').val('');
  });

  $container.on("click", ".delete", e => {
    e.preventDefault();
    $(e.target).closest('.row').remove();
  })

  $container.on('change', '.price', e => {
    $(e.target).closest('.row').find('.total').val(e.target.value);
  });
});
body {
  background-color: #CCC;
}

#niy {
  color: white;
}

#niy span {
  font-size: 16px;
  font-weight: bold;
}

label {
  width: 100px;
  display: inline-block;
}

.row:first-child .delete {
  display: none;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="container">
  <div class="row">
    <div class="col-lg-4 col-sm-6">
      <div class="mb-4">
        <label for="client_type">Service Type</label>
        <input type="text" class="form-control service" required name="service[]">
      </div>
    </div>
    <div class="col-lg-4 col-sm-6">
      <div class="mb-4">
        <label for="client_type">Price</label>
        <input type="text" class="form-control price" required name="price[]">
      </div>
    </div>
    <div class="col-lg-4 col-sm-6">
      <div class="mb-4">
        <label for="client_type">Total</label>
        <input type="text" class="form-control total" required name="total[]">
      </div>
    </div>
    <a href="#" class="delete">Delete</a>
  </div>
</div>
<a id="niy" class="btn btn-warning">
  Add New Service Field  
  <span>+ </span>
</a>

墨洒年华 2025-02-19 00:55:30

尝试以下片段下一次,您会发现运行时输入更新总计。这会促进用户体验。

$(document).ready(function() {
    var max_fields = 10;
    var wrapper = $(".container1");
    var add_button = $("#niy");

    var x = 1;
    $(add_button).click(function(e) {
        e.preventDefault();
        if (x < max_fields)
        {
            x++;
            $(wrapper).append('<div class="col-lg-4 col-sm-6"><div class="mb-4"><label for="service_type'+x+'">Service Type</label><input type="text" class="form-control service_type" data-id="'+x+'" id="service_type'+x+'" required name="service[]"></div></div><div class="col-lg-4 col-sm-6"><div class="mb-4"><label for="price_type'+x+'">Price</label><input type="text" class="form-control price_type" data-id="'+x+'" id="price_type'+x+'" required name="price[]"></div></div><div class="col-lg-4 col-sm-6"><div class="mb-4"><label for="total_type'+x+'">Total</label><input type="text" class="form-control" data-id="'+x+'" id="total_type'+x+'" readonly name="total[]"></div></div>'); 
        }
        else
        {
            alert('You Reached the limits')
        }
    });
    $(wrapper).on("click", ".delete", function(e) {
        e.preventDefault();
        $(this).parent('div').remove();
    })
});

$(document).on('input', '.service_type, .price_type', function(){
    var id = $(this).attr('data-id');
    if(id > 0)
    {
        var service_type = parseFloat($('#service_type'+id).val()) || 0;
        var price_type = parseFloat($('#price_type'+id).val()) || 0;
        var total_type = service_type + price_type;
        $('#total_type'+id).val(total_type.toFixed(2));
    }
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="row container1">
    <div class="col-lg-4 col-sm-6">
        <!-- Form -->
        <div class="mb-4">
            <label for="service_type1">Service Type</label>
            <input type="text" class="form-control service_type" id="service_type1" data-id="1" required name="service[]">
        </div>
    </div>
    <div class="col-lg-4 col-sm-6">
        <!-- Form -->
        <div class="mb-4">
            <label for="price_type1">Price</label>
            <input type="text" class="form-control price_type" id="price_type1" data-id="1" required name="price[]">
        </div>
    </div>
    <div class="col-lg-4 col-sm-6">
        <!-- Form -->
        <div class="mb-4">
            <label for="total_type1">Total</label>
            <input type="text" class="form-control" id="total_type1" data-id="1" readonly name="total[]">
        </div>
    </div>
</div>
<a id="niy" class="btn btn-warning">Add New Service Field  
    <span style="font-size:16px; font-weight:bold;">+ </span>
</a>

try below snippet once, you will find runtime oninput updating totals. That imrpoves user experience.

$(document).ready(function() {
    var max_fields = 10;
    var wrapper = $(".container1");
    var add_button = $("#niy");

    var x = 1;
    $(add_button).click(function(e) {
        e.preventDefault();
        if (x < max_fields)
        {
            x++;
            $(wrapper).append('<div class="col-lg-4 col-sm-6"><div class="mb-4"><label for="service_type'+x+'">Service Type</label><input type="text" class="form-control service_type" data-id="'+x+'" id="service_type'+x+'" required name="service[]"></div></div><div class="col-lg-4 col-sm-6"><div class="mb-4"><label for="price_type'+x+'">Price</label><input type="text" class="form-control price_type" data-id="'+x+'" id="price_type'+x+'" required name="price[]"></div></div><div class="col-lg-4 col-sm-6"><div class="mb-4"><label for="total_type'+x+'">Total</label><input type="text" class="form-control" data-id="'+x+'" id="total_type'+x+'" readonly name="total[]"></div></div>'); 
        }
        else
        {
            alert('You Reached the limits')
        }
    });
    $(wrapper).on("click", ".delete", function(e) {
        e.preventDefault();
        $(this).parent('div').remove();
    })
});

$(document).on('input', '.service_type, .price_type', function(){
    var id = $(this).attr('data-id');
    if(id > 0)
    {
        var service_type = parseFloat($('#service_type'+id).val()) || 0;
        var price_type = parseFloat($('#price_type'+id).val()) || 0;
        var total_type = service_type + price_type;
        $('#total_type'+id).val(total_type.toFixed(2));
    }
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="row container1">
    <div class="col-lg-4 col-sm-6">
        <!-- Form -->
        <div class="mb-4">
            <label for="service_type1">Service Type</label>
            <input type="text" class="form-control service_type" id="service_type1" data-id="1" required name="service[]">
        </div>
    </div>
    <div class="col-lg-4 col-sm-6">
        <!-- Form -->
        <div class="mb-4">
            <label for="price_type1">Price</label>
            <input type="text" class="form-control price_type" id="price_type1" data-id="1" required name="price[]">
        </div>
    </div>
    <div class="col-lg-4 col-sm-6">
        <!-- Form -->
        <div class="mb-4">
            <label for="total_type1">Total</label>
            <input type="text" class="form-control" id="total_type1" data-id="1" readonly name="total[]">
        </div>
    </div>
</div>
<a id="niy" class="btn btn-warning">Add New Service Field  
    <span style="font-size:16px; font-weight:bold;">+ </span>
</a>

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文