As you can see I can dynamically create inputs via click of a button, I can remove them also by clicking the remove button and it will only delete the input next the remove button not every input. Taking this idea, I created an edit button and i am trying to edit input via another input. So far its almost working, when user click edit button the value of the closest input goes to the input that is on the very top of the page, I can change the value there , then click submit, the value of the initial input changed to the latest value i typed on the edit input (input on very top).
Problem: do these steps to see the problem
- Add 3 new inputs.
- Type 1 on the first input, 2 on second, 3 on 3rd
- Click edit on 3rd input, value goes to the top input then type 'c' on the top input and click submit, as you can see the value on the 3rd input changed to c, good so far.
- Now click edit on 2nd input and change the input to 'b' on the very top input and click submit. As you can see, instead of changing just the 2nd input now 2nd and 3rd input changed to 'b'.
I think its confusing the 'this' when more inputs are on the play. how can I fix this.
$(document).ready(function() {
var max_fields = 100; //maximum input boxes allowed
var wrapper = $(".input_fields_wrap"); //Fields wrapper
var add_button = $(".add_field_button"); //Add button ID
$(add_button).click(function(e) { //on add input button click
e.preventDefault();
if (wrapper.find("input").length < max_fields) {
//max input box allowed
$(wrapper).append('<div><input type="text" name="mytext[]"/><a href="#" class="remove_field">Remove</a><button class="edit-icon">Edit</button></div>'); //add input box
}
});
$(wrapper).on("click", ".remove_field", function(e) { //user click on remove text
e.preventDefault();
$(this).parent('div').remove();
})
$(wrapper).on('click', '.edit-icon', function(e) {
console.log($(this));
e.preventDefault();
//var remove_target = $(this).closest('div')
var target = $(this).closest('div').find('input');
var edit_name = target.val();
$('.editinput').val(edit_name);
$('.editinputsubmit').click(function() {
console.log("click working");
target.val($('.editinput').val());
})
});
});
<script src="https://code.jquery.com/jquery-3.3.1.min.js" integrity="sha256-FgpCb/KJQlLNfOu91ta32o/NMZxltwRo8QtmkMRdAu8=" crossorigin="anonymous"></script>
<div>
<input type="text" class="editinput">
<button class="editinputsubmit">submit</button>
</div>
<hr>
<div class="input_fields_wrap">
<button class="add_field_button">Add More Fields</button>
</div>