I think there is more that is needed here. Can someone please comment on it?
What I need is to add some common functions to check if an element exists.
// Common functions
$(document).ready(function() {
/*
Function for creating different styling checkbox, radio input, and select
*/
// Create pretty checkboxes and inputs
if ($('.iCheck').length){
$('.iCheck').iCheck({
checkboxClass: 'icheckbox_minimal-blue',
radioClass: 'iradio_minimal-blue',
increaseArea: '20%' // optional
});
}
// Create pretty selects and multiselect
if(!$("html").hasClass("ie8")){
if ($('select').length){
$('select').attr('data-width', '100%').selectpicker();
}
};
/*
Preloader
*/
var targetPreloader = $('[data-overlay-text]');
targetPreloader.click(function() {
var text = $(this).attr("data-overlay-text");
$('.preloader-text').text(text);
$('.preloader-window').show().fadeIn();
});
/*
Fix for showing SVG
*/
svgeezy.init('nothing', 'png');
/*
Form validation using Jquery validate
*/
$('form').validate({
highlight: function(element) {
$(element).closest('.form-group').addClass('has-error');
},
unhighlight: function(element) {
$(element).closest('.form-group').removeClass('has-error');
},
errorElement: 'span',
errorClass: 'help-block',
errorPlacement: function(error, element) {
if(element.parent('.input-group').length) {
error.insertAfter(element.parent());
} else {
error.insertAfter(element);
}
}
});
});
2 Answers 2
You shouldn't even need to do a check for element exists before calling a jQuery method. All internal methods, and any plugin that follows good practices, just won't do anything at all if there are no elements in the set. So you could just simplify that part of the code down to (without the if
):
$('.iCheck').iCheck({
checkboxClass: 'icheckbox_minimal-blue',
radioClass: 'iradio_minimal-blue',
increaseArea: '20%' // optional
});
-
\$\begingroup\$ Try firebug it get error \$\endgroup\$Miomir Dancevic– Miomir Dancevic2014年11月18日 11:37:08 +00:00Commented Nov 18, 2014 at 11:37
-
\$\begingroup\$ Wait - what is the iCheck plugin here? \$\endgroup\$Scimonster– Scimonster2014年11月18日 11:42:36 +00:00Commented Nov 18, 2014 at 11:42
-
\$\begingroup\$ It changes the styling of checkbox and radio buttons, the problem is what if i dont have inouts on page \$\endgroup\$Miomir Dancevic– Miomir Dancevic2014年11月18日 11:45:02 +00:00Commented Nov 18, 2014 at 11:45
-
\$\begingroup\$ This plugin? \$\endgroup\$Scimonster– Scimonster2014年11月18日 11:46:09 +00:00Commented Nov 18, 2014 at 11:46
-
\$\begingroup\$ I dont know why is this question in needed \$\endgroup\$Miomir Dancevic– Miomir Dancevic2014年11月18日 11:48:47 +00:00Commented Nov 18, 2014 at 11:48
I had a similar question myself, and after reading this question from SO, I have reached the conclusion that the check you have used is probably just about as good as it gets, though that question does have other suggestions.
if ($('select')) { }
and ummif ($('.iCheck').hasOwnProperty('iCheck') { }
\$\endgroup\$