I have jQuery code that refreshes a button set:
$("#myRadio").buttonset('refresh');
But I found a use case where it's being called prior to this line:
$("#myRadio").buttonset();
And then blowing up because its not initialized. I wanted to see if there is a way to determine if this buttonset() initialization has happened so I can check before calling refersh:
Something like:
if($("#myRadio").buttonsetIsInitialized())
{
$("#myRadio").buttonset('refresh');
}
What is the correct way to do this check?
You could do it same way as you described in your OP by adding new method buttonsetIsInitialized()
to the jQuery object :
$.fn.buttonsetIsInitialized = function () {
return this.hasClass('ui-buttonset');
};
This method will check if the class ui-buttonset
(that the instantiation add to element) is present in element class list.
if($("#myRadio").buttonsetIsInitialized()){
$("#myRadio").buttonset('refresh');
}
Hope this helps.
Not initialized case:
$.fn.buttonsetIsInitialized = function () {
return this.hasClass('ui-buttonset');
};
if( $("#myRadio").buttonsetIsInitialized() ){
console.log('Refresh element');
}else{
console.log('Not initialized');
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jqueryui/1.8.18/jquery-ui.min.js"></script>
<link href="https://code.jquery.com/ui/1.8.20/themes/base/jquery-ui.css" rel="stylesheet"/>
<div id="myRadio">
<input id="first" type="radio" value="1" name="steps"/><label for="first">First</label>
<input id="second" type="radio" value="2" name="steps"/><label for="second">Second</label>
</div>
Initialized case:
$('#myRadio').buttonset(); //Initilized
$.fn.buttonsetIsInitialized = function () {
return this.hasClass('ui-buttonset');
};
if( $("#myRadio").buttonsetIsInitialized() ){
console.log('refresh element');
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jqueryui/1.8.18/jquery-ui.min.js"></script>
<link href="https://code.jquery.com/ui/1.8.20/themes/base/jquery-ui.css" rel="stylesheet"/>
<div id="myRadio">
<input id="first" type="radio" value="1" name="steps"/><label for="first">First</label>
<input id="second" type="radio" value="2" name="steps"/><label for="second">Second</label>
</div>