Javascript
jQuery – Reverse Each
0There may be some situations where you need to step through dom elements in reverse order, in this case the following code should help you:
jQuery(jQuery('div.child').get().reverse()).each(function(i) {
//do stuff
});
Example html:
<div class="parent">
<div class="child">A</div>
<div class="child">B</div>
<div class="child">C</div>
</div>
jQuery – Reset Select Options
3If you need to reset select options try the following:
var select = jQuery('#someSelect');
select.val(jQuery('options:first', select).val());
Regardless of the first option being blank or not, this will reset the currently selected option to first option. In my opinion it’s always good practice to have a blank first option so the user can easily see it has been reset.
Javascript – JQuery – Check if Form Inputs were Selected
0If you have a list of checkboxes or radio buttons and want to see if any of them were selected, JQuery makes it simple:
if (!(jQuery("input[@name=<input_name>]:checked").length)) {
alert('Please select something!');
return false;
}
return true;
Simply replace <input_name> with the name of your checkboxes/radio buttons. Calling code example:
<form action="someFile.php" method="post" onSubmit="return validateCheckboxes();">
<input type="checkbox" id="checkbox_id_1" name="checkboxIds[]" value="1"/>
<input type="checkbox" id="checkbox_id_2" name="checkboxIds[]" value="2"/>
<input type="checkbox" id="checkbox_id_3" name="checkboxIds[]" value="3"/>
So the final javascript would like like:
function validateCheckboxes()
{
if (!(jQuery("input[@name=checkboxIds]:checked").length)) {
alert('Please select something!');
return false;
}
}
return true;
You can also use specific dom ids, but if you are iterating over a list and echoing out checkboxes/radio buttons I wouldn’t recommend it, as demonstrated above you can hook into multiple inputs by using name.
