1

My sample code

<div class="my_class_1">
    <input type="text" name="name_1[]" value="1" />
    <input type="text" name="name_1[]" value="2" />
</div>
<div class="my_class_2">
    <input type="text" name="name_1[]" value="3" />
    <input type="text" name="name_1[]" value="4" />
</div>

<div class="my_class_3">
    <input type="text" name="name_1[]" value="5" />
    <input type="text" name="name_1[]" value="6" />
</div>

Here textbox with name_1 will get added dynamically inside any div my_class_1/ my_class_2 / my_class_3 while adding new input type i wanted to fetch previous value and added to new textbox For ex If i'm adding new textbox for div class my_class_1 the new textbox value should be 2 like this

<input type="text" name="name_1[]" value="2" />

when i'm adding new textbox for div class my_class_2 the new textbox value should be 4 like this

<input type="text" name="name_1[]" value="4" />

I tried some methds in javascript

<script>
let lastElement = document.getElementsByName("name_1[]");
let leng1 = lastElement.length;
lastValue = (typeof lastElement[lastElement-1] == 'undefined') ?  0 : lastElement[lastElement - 1].value;
</script>

This always returning me the last value

Can anyone help me on this Thank you in advance

2
  • Why you are not saving your desired value on any kind of hidden input field then try to get it by js Commented Mar 8, 2020 at 8:25
  • yes,i can keep, but even user has provision to change value of textbox and adding one more new textbox, this time i need to refresh my hidden filed for last user updated value Commented Mar 8, 2020 at 8:40

1 Answer 1

1

With document.querySelector() you can select a single element with CSS selectors. So what you could do is select the container in which the input is that you want to select and use the :last-of-type pseudo selector to select the last input that has the criteria you are searching for. This allows to always select the last input in the correct position.

let lastElement = document.querySelector('.my_class_2 input[name="name_1[]"]:last-of-type');
let lastValue = lastElement.value;
console.log(lastElement, lastValue);
<div class="my_class_1">
    <input type="text" name="name_1[]" value="1" />
    <input type="text" name="name_1[]" value="2" />
</div>
<div class="my_class_2">
    <input type="text" name="name_1[]" value="3" />
    <input type="text" name="name_1[]" value="4" />
</div>

<div class="my_class_3">
    <input type="text" name="name_1[]" value="5" />
    <input type="text" name="name_1[]" value="6" />
</div>

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.