JQuery does not find next element
I used the code that someone from another question provided me a few days ago, but I changed the HTML of my page and now it doesn't work, but I can't figure out why. The button needs to have the property disabled when the counter goes to 0 , but it doesn't. This is HTML
So it should create an element named stop
<td class="text-left my-timer" data-time="10">10</td>
<form method="POST">
<td><button type="submit" name="stop" class="btn btn-effect-ripple btn-square btn-danger">Stop</button></td>
<input type="text" name="aID" value="431" class="hidden">
</form>
This is the javascript code I was given. As you can see, once the timer is at 0, it will find the button and add a disabled property to it.
$(function(){
// loop over each element to activate
$('td.my-timer').each(function(){
// "this" inside "each" is current element
var $elem = $(this),
// get the time value stored in data-time attribute
sec = $elem.data('time');
// instance specific interval
var timer = setInterval(function() {
sec--;
var html = sec > 0 ? sec : "<b>Finished</b>";
$elem.html(html);
if( sec == 0){
clearInterval(timer);
$elem.next().find('submit').prop('disabled', true);
}
},1000);
});
});
source to share
submit
is not an HTML element. This is an attribute.
Your selector is wrong.
Use an attribute selector :
$elem.next().find('button[type="submit"]').prop('disabled', true);
// ^^^^^^^^^^^^^^^^^^^^^^
You can also use the :submit
pseudo selector like this:
Selects all elements of type submit.
$elem.next().find(':submit').prop('disabled', true);
// ^^^^^^^^^
source to share
Your html is not valid as form
it cannot be a child tr
, move the whole form as a child of the second element td
, then use : submit selector to find the submit button
$(function() {
// loop over each element to activate
$('td.my-timer').each(function() {
// "this" inside "each" is current element
var $elem = $(this),
// get the time value stored in data-time attribute
sec = $elem.data('time');
// instance specific interval
var timer = setInterval(function() {
sec--;
var html = sec > 0 ? sec : "<b>Finished</b>";
$elem.html(html);
if (sec == 0) {
clearInterval(timer);
$elem.next().find(':submit').prop('disabled', true);
}
}, 1000);
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table>
<td class="text-left my-timer" data-time="10">10</td>
<td>
<form method="POST">
<button type="submit" name="stop" class="btn btn-effect-ripple btn-square btn-danger">Stop</button>
<input type="text" name="aID" value="431" class="hidden" />
</form>
</td>
</table>
<td class="text-left my-timer" data-time="10">10</td>
<td>
<form method="POST">
<button type="submit" name="stop" class="btn btn-effect-ripple btn-square btn-danger">Stop</button>
<input type="text" name="aID" value="431" class="hidden"/>
</form>
</td>
source to share