Skip to content
Advertisement

How to get last value of an array input text in JS?

This is my code from controller where I used looping to show this.

<input type="hidden" class="notif_date" value="'.$created_at.'">

the sample data of this are multiple dates: 2019-05-28 13:45:45

Now I’m trying the get the last date that will be shown using JavaScript.

Currently I have this code:

var last_date =  document.getElementsByClassName("notif_date");
console.log(last_date);

But this only gets the array of input types

enter image description here

So I tried to use last() and place like this console.log(last_date.last()); and this gives me an error like this

Uncaught TypeError: last_date.last is not a function

How can I get the last value of date using JavaScript?

Advertisement

Answer

To get last element you can use following code

let elements = document.getElementsByClassName("notif_date");
console.log(elements[elements.length-1]);

This code will provide you the correct output which you want.

Edited

If you want to get value of last element then use this:-

console.log(elements[elements.length-1].val());

Note: But you can’t get value directly from document.getElementsByClassName("notif_date"). Because this return multiple object of multiple class elements.

But if you want to get value of all the elements then you need to loop this.

User contributions licensed under: CC BY-SA
4 People found this is helpful
Advertisement