示例输入字段:
From number
的第一个值设置为default = 1。
1st From: 1 | To: 10 | Price: 100 | + Add more fields +
当我在To number
上输入10并点击添加更多字段时,我的表单应该是:
1st From: 1 | To: 10 | Price: 100 |
2nd From: 11 | To: (null) | Price: (null) | - Remove - + Add more fields +
我想要的是什么:
当我将第一个To number
字段更改为11时,它会自动将第二个From number
更改为12,如:
1st From: 1 | To: 11 | Price: 100 |
2nd From: 12 | To: (null) | Price: (null) | - Remove - + Add more fields +
代码:
HTML
<form action="" method="post" class="input_fields_wrap">
<button class="add_field_button">Add More Fields</button>
<br>
<div>
From:
<input type="text" readonly="" name="from[]" class="from" value="1"> To:
<input type="text" name="to[]" class="to" value="2"> Price:
<input type="text" name="price[]" class="price">
</div>
</form>
的javascript
$(document).ready(function() {
var max_fields = 10; //maximum input boxes allowed
var wrapper = $(".input_fields_wrap"); //Fields wrapper
var add_button = $(".add_field_button"); //Add button ID
var x = 1; //initlal text box count
$(add_button).click(function(e) { //on add input button click
e.preventDefault();
if (x < max_fields) { //max input box allowed
var lastTo = parseInt($('.to:last').val(), 10);
x++; //text box increment
$(wrapper).append('<div>From: <input type="text" name="from[]" class="from" value="' + (lastTo + 1) + '"> To: <input type="text" name="to[]" class="to"> Price: <input type="text" name="price[]" class="price"><a href="#" class="remove_field">Remove</a></div>'); //add input box
}
});
$(wrapper).on("click", ".remove_field", function(e) { //user click on remove text
e.preventDefault();
$(this).parent('div').remove();
x--;
});
});
我的代码jsfiddle。
答案 0 :(得分:1)
您可以按照以下方式实现:
向所有input event
添加to inputs
并相应地更改下一个from fields
的值:
$('.input_fields_wrap').on('input','input[name="to[]"]',function(e){
var _this=$(this);
var fromFields=_this.closest('div').nextAll('div').find('input[name="from[]"]');
//get all the next from fields which is after current to field
$.each($(fromFields),function(){
$(this).val(parseInt(_this.val())+1);
})
})
<强> DEMO 强>
注意 - 这不是一个完整的解决方案,但您可以根据自己的要求进行修改。
答案 1 :(得分:1)