'how get all values of one class in jquery?
I am trying to get all values of a class input fields. but it is return only one fields value
Html code
<div id="mydiv">
<input class="seconds" type="text" value="40">
<input class="seconds" type="text" value="20">
<span class="countdown"></span>
</div>
Javascript code
<script src="{{ asset('js/vendor/jquery-3.1.0.min.js') }}"></script>
<script src="{{ asset('js/jquery.missofis-countdown.js') }}"></script>
<script>
var ek=$('.seconds').val();
console.log(ek);
$( '.countdown' ).countdown( {
from: ek, // 3 minutes (3*60)
to: 0, // stop at zero
movingUnit: 1000, // 1000 for 1 second increment/decrements
timerEnd: undefined,
outputPattern: '$day Day $hour : $minute : $second',
autostart: true,
});
</script>
I want to get values of both input fields having same class
Solution 1:[1]
Use map()
to create array of the values
var ek = $('.seconds').map((_,el) => el.value).get()
console.log(ek)
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="mydiv">
<input class="seconds" type="text" value="40">
<input class="seconds" type="text" value="20">
<span class="countdown"></span>
</div>
Solution 2:[2]
Attribute methods will only ever get the value of the first element.
To get multiple you have to iterate( loop ) over every element returned by the selector.
var ek=[];
$('.seconds').each(function() { ek.push($(this).val()); });
console.log(ek);
Timers:
Make sure you add as many countdown spans as you want timers in your html.
$( '.countdown' ).each(function(index) {
$(this).countdown( { from: ek[index], //
3 minutes (3*60)
to: 0, // stop at zero
movingUnit: 1000, // 1000 for 1 second increment/decrements
timerEnd: undefined,
outputPattern: '$day Day $hour : $minute : $second',
autostart: true, });
});
Note: I apologize for formatting. I'm on mobile.
Solution 3:[3]
A more simplistic approach is:
$('.loadedDate').map(function(){return this.value;}).get()
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | charlietfl |
Solution 2 | |
Solution 3 | Ch Usman |