jqueryjquery-uiinherited-widget

jquery ui inherite button widget


I'm trying to create a new widget based on the button widget and would like to know how to modify the button style of an existing jquery ui button if it already is created or create a new jquery button if it doesn't. How would I check if it's already been created and if it has how do I modify the style for example?

For example modifying an existing jquery button... I want to be able to access buttonElement

this.buttonElement.removeClass('ui-corner-all');

but it doesn't work.

but this works on existing jquery button...

this.element.on('click', function(){...});

I know I can use

_create: function(){ this_super();}

to create a new button and I can access the buttonElement easily... but as I stated earlier if the button already exists it creates 2 jquery buttons. like this...

<span class="ui-button-text"><span class="ui-button-text">Yes</span></span>

when it should only be <span class="ui-button-text">Yes</span>.

I hope I was able to explain what I want to do and the problems I'm running into... sorry I'm just a casual programmer at best.

Edit to add example code: HTML:

<label for="testcb" >Yes</label>
<input type="checkbox" id="testcb" name="testcb"/>

JS:

var checkbox=$('body').find(':checkbox');
checkbox.each(function(){
  $(this).button();
})

Jquery ui widget:

$.widget( "new.checkbox", $.ui.button,{
  _create: function(){
    this._super();
  }
})

Result: adds double which has for effect of doubling styles applied to the button

<span class="ui-button-text">
  <span class="ui-button-text">Yes</span>
</span>

I know I can simply add $('#testcb').button('destroy'); but I'd like to be able to do that in the widget by detecting if the element already has or not ui.button added. If it is already created I'd like to modify the testcb element. I also know that buttonElement is the value that ui.button creates that can be modified but I can't 'get' to it from my widget.

Hope this clears things up.


Solution

  • widget() Returns: jQuery

    Returns a jQuery object containing the element visually representing the button. This method does not accept any arguments.

    See More: https://api.jqueryui.com/button/#method-widget

    You can modify the Widget this way.

    $(function() {
      $("input:checkbox").each(function() {
        $(this).button();
        var b = $(this).button("widget");
        b.removeClass("ui-corner-all");
      });
    });
    <link rel="stylesheet" href="//code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css">
    <script src="https://code.jquery.com/jquery-1.12.4.js"></script>
    <script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script>
    <label for="testcb">Yes</label>
    <input type="checkbox" id="testcb" name="testcb" />