65

This is for jQuery Mobile. Not all regular jQuery answers will work.

I can't get my buttons to disable in jQuery Mobile.

jQuery Mobile says to use

$('input').button('disable');   

But I get an error message in Firebug:

uncaught exception: cannot call methods on button prior to initialization; attempted to call method 'disable'.

It's in the document ready section of my page so I dont know how it's not initialized yet.

I've tried calling the button directly by its id but that doesn't work.

I've tried:

$('button').attr("disabled", "disabled");

Doesn't work.

I also have a switch command that will enable one button based on what the value is. I've got that part to where its routing to right "case" statements, but the enable/disable buttons thing in jQuery mobile is not working.

code: http://pastebin.com/HGSbpAHQ

naugtur
  • 16,827
  • 5
  • 70
  • 113
swg1cor14
  • 1,682
  • 6
  • 25
  • 46

12 Answers12

110

UPDATE:

Since this question still gets a lot of hits I'm also adding the current jQM Docs on how to disable the button:

Updated Examples:

enable enable a disabled form button

$('[type="submit"]').button('enable');  

disable disable a form button

$('[type="submit"]').button('disable'); 

refresh update the form button
If you manipulate a form button via JavaScript, you must call the refresh method on it to update the visual styling.

$('[type="submit"]').button('refresh');

Original Post Below:

Live Example: http://jsfiddle.net/XRjh2/2/

UPDATE:

Using @naugtur example below: http://jsfiddle.net/XRjh2/16/

UPDATE #2:

Link button example:

JS

var clicked = false;

$('#myButton').click(function() {
    if(clicked === false) {
        $(this).addClass('ui-disabled');
        clicked = true;
        alert('Button is now disabled');
    } 
});

$('#enableButton').click(function() {
    $('#myButton').removeClass('ui-disabled');
    clicked = false; 
});

HTML

<div data-role="page" id="home">
    <div data-role="content">

        <a href="#" data-role="button" id="myButton">Click button</a>
        <a href="#" data-role="button" id="enableButton">Enable button</a>

    </div>
</div>

NOTE: - http://jquerymobile.com/demos/1.0rc2/docs/buttons/buttons-types.html

Links styled like buttons have all the same visual options as true form-based buttons below, but there are a few important differences. Link-based buttons aren't part of the button plugin and only just use the underlying buttonMarkup plugin to generate the button styles so the form button methods (enable, disable, refresh) aren't supported. If you need to disable a link-based button (or any element), it's possible to apply the disabled class ui-disabled yourself with JavaScript to achieve the same effect.

Phill Pafford
  • 83,471
  • 91
  • 263
  • 383
  • ur running that example with just jquery. it doesnt work on my application with jquery mobile – swg1cor14 May 03 '11 at 20:53
  • 1
    the example I give is using the jQM framework and does disable the button, See button2. If you could post a little more code as to exactly how you're trying to create and disable the button that would sure help in helping give you a good answer – Phill Pafford May 03 '11 at 21:00
  • It doesn't work if the button is type="submit". Otherwise it works perfect, thanks. – Jack Nov 25 '11 at 10:13
  • 2
    @JacobusR Here is the updated jQM Docs: http://jquerymobile.com/demos/1.0/docs/buttons/buttons-methods.html $('[type='submit']').button('disable'); – Phill Pafford Nov 25 '11 at 15:53
  • Wonder why they couldn't add this to the other buttons too. They could store the clicked state in a data attribute. Anyway thanks! – msanjay Nov 20 '12 at 10:21
  • PS: (...they could store the clicked state in a data attribute...) or better still just checked hasClass('ui-disabled') – msanjay Nov 20 '12 at 10:30
10

uncaught exception: cannot call methods on button prior to initialization; attempted to call method 'disable'.

this means that you are trying to call it on an element that is not handled as a button, because no .button method was called on it. Therefore your problem MUST be the selector.

You are selecting all inputs $('input'), so it tries to call the method disable from button widget namespace not only on buttons, but on text inputs too.

$('button').attr("disabled", "disabled"); will not work with jQuery Mobile, because you modify the button that is hiden and replaced by a markup that jQuery Mobile generates.

You HAVE TO use jQueryMobile's method of disabling the button with a correct selector like:

$('div#DT1S input[type=button]').button('disable');
naugtur
  • 16,827
  • 5
  • 70
  • 113
4

If I'm reading this question correctly, you may be missing that a jQuery mobile "button" widget is not the same thing as an HTML button element. I think this boils down to you can't call $('input').button('disable') unless you have previously called $('input').button(); to initialize a jQuery Mobile button widget on your input.

Of course, you may not want to be using jQuery button widget functionality, in which case Alexander's answer should set you right.

RwwL
  • 3,298
  • 1
  • 23
  • 24
  • Hmmm... maybe irrelevant as it seems jQuery mobile calls .button automatically if you used data-role="button" in your markup (did you?) – RwwL May 03 '11 at 20:15
  • Is the `data-role="button"` also relevant in normal html pages (not only mobile)? Which version? – sumid Nov 08 '12 at 00:37
  • 1
    Sumid, not sure I understand your question, but if this helps: data-role="button" is a convention used by jQuery Mobile to flag elements to be auto-initialized as button controls (as defined by that library). There is nothing stopping you from using that data attribute on "normal html pages" however you'd like. It is not apparently used the same way in the full jQuery UI library. http://jqueryui.com/button/ – RwwL Dec 05 '12 at 14:17
  • Ok. That answers my question. Thanks. – sumid Dec 05 '12 at 19:37
4

What seems to be needed is to actually define the button as a button widget.

I had the same problem (in beta 1)

I did

$("#submitButton").button();

in my window ready handler, after that it worked to do as it is said in the docs, i.e.:

$("#submitButton").button('disable'); 

I guess this has to do with that jqm is converting the markup, but isnt actually instatiating a real button widget for buttons and link buttons.

3

I created a widget that can completely disable or present a read-only view of the content on your page. It disables all buttons, anchors, removes all click events, etc., and can re-enable them all back again. It even supports all jQuery UI widgets as well. I created it for an application I wrote at work. You're free to use it.

Check it out at ( http://www.dougestep.com/dme/jquery-disabler-widget ).

dgestep
  • 131
  • 5
2

Based on my findings...

This Javascript error occurs when you execute button() on an element with a selector and try to use a function/method of button() with a different selector on the same element.

For example, here is the HTML:

<input type="submit" name="continue" id="mybuttonid" class="mybuttonclass" value="Continue" />

So you execute button() on it:

jQuery(document).ready(function() { jQuery('.mybuttonclass').button(); });

Then you try to disable it, this time not using the class as you initiated it but rather using the ID, then you'll get the error as this thread is titled:

jQuery(document).ready(function() { jQuery('#mybuttonid').button('option', 'disabled', true); });

So rather use the class again as you initiated it, that'll resolve the problem.

contrid
  • 950
  • 9
  • 18
2

Try one of the statements below:

$('input[type=submit]').attr('disabled','disabled');

or

$('input[type=button]').attr('disabled','disabled');

UPDATE

To target a particular button, given the HTML you provided:

$('div#DT1S input[type=button]').attr('disabled','disabled');

http://jsfiddle.net/kZcd8/

Alex
  • 34,899
  • 5
  • 77
  • 90
  • Given the code you provided in the comment it does - check the jsfiddle link provided http://jsfiddle.net/kZcd8/ – Alex May 03 '11 at 20:51
2
  $(document).ready(function () {
        // Set button disabled

        $('#save_info').button("disable");


        $(".name").bind("change", function (event, ui) {

            var edit = $("#your_name").val();
            var edit_surname = $("#your_surname").val();
            console.log(edit);

            if (edit != ''&& edit_surname!='') {
                //name.addClass('hightlight');
                $('#save_info').button("enable");
                console.log("enable");

                return false;
            } else {

                $('#save_info').button("disable");

                console.log("disable");
            }

        });


    <ul data-role="listview" data-inset="true" data-split-icon="gear" data-split-theme="d">
        <li>
            <input type="text" name="your_name" id="your_name" class="name" value="" placeholder="Frist Name" /></li>
        <li>
            <input type="text" name="your_surname" id="your_surname"  class="name" value="" placeholder="Last Name" /></li>
        <li>
            <button data-icon="info" href="" data-role="submit" data-inline="true" id="save_info">
            Save</button>

This one work for me you might need to workout the logic, of disable -enable

Yene Mulatu
  • 2,226
  • 1
  • 17
  • 13
0

For disabling a button add css class disabled to it . write

$("button").addClass('disabled')
ofskyMohsen
  • 1,121
  • 1
  • 12
  • 26
0

For jQuery Mobile 1.4.5:

for anchor buttons, the CSS class is: ui-state-disabled, and for input buttons it is just enough to toggle the disabled attribute.

function toggleDisableButtons() {
  $("#link-1").toggleClass("ui-state-disabled", !$("#link-1").hasClass("ui-state-disabled"));
  $("#button-1").attr("disabled") ? $("#button-1").removeAttr("disabled") : $("#button-1").attr("disabled","");
}
<!DOCTYPE html>
<html>
<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1, user-scalable=no">
  <link rel="stylesheet" href="https://code.jquery.com/mobile/1.4.5/jquery.mobile-1.4.5.css">
  <script src="https://code.jquery.com/jquery-1.11.2.min.js"></script>
  <script src="https://code.jquery.com/mobile/1.4.5/jquery.mobile-1.4.5.js"></script>
</head>
<body>
<div data-role="page" id="page-1">
  <div role="main" class="ui-content">
    <button class="ui-btn" onclick="toggleDisableButtons();">Toggle disabled</button>
    <a id="link-1" href="#" class="ui-btn ui-state-disabled">Anchor</a>
    <button id="button-1" disabled="">Button</button>
    
  </div>
</div>
</body>
</html>

BTW, for input buttons, there is an alternate method:

Enable:

$(".class").prop("disabled", false).removeClass("ui-state-disabled");

Disable:

$(".class").prop("disabled", true).addClass("ui-state-disabled");
deblocker
  • 7,629
  • 2
  • 24
  • 59
0

For link button,

Calling .button('enable') method only gives effect, but functionally don't.

But I have a trick. We could use HTML5 data- attribute to save/swap value of href and onclick.

see:

http://jsbin.com/ukewu3/74/

source code mode:

http://jsbin.com/ukewu3/74/edit

Vikas
  • 24,082
  • 37
  • 117
  • 159
0

You are getting that error probably because the element is not within the DOM yet. $(document).ready(); will not work. Try adding your code to a pageinit event handler.

Here is a working example:

<!DOCTYPE html> 
<html> 
<head>
    <title>Button Disable</title> 
    <meta name="viewport" content="width=device-width, initial-scale=1" />
    <link rel="stylesheet" href="http://code.jquery.com/mobile/1.0/jquery.mobile-1.0.min.css" />
    <script type="text/javascript" src="http://code.jquery.com/jquery-1.6.4.min.js"></script>
    <script type="text/javascript" src="http://code.jquery.com/mobile/1.0/jquery.mobile-1.0.min.js"></script>
</head> 
<body>
    <div id="MyPageId" data-role="page">
        <div data-role="header">
            <h1>Button Disable</h1>
        </div>
        <div data-role="content">
            <button id="button1" type="button" onclick="javascript:alert('#button1 clicked');">Button 1</button>
            <button id="button2" type="button" onclick="javascript:alert('#button2 clicked');">Button 2</button>
        </div>
        <div data-role="footer">
            <p>footer</p>
        </div>
    </div>
    <script type="text/javascript">//<![CDATA[
        $('#MyPageId').bind("pageinit", function (event, data) {
            $("#button1").button("disable");
        });
    //]]></script>
</body>
</html>

Hope that helps someone

robnardo
  • 921
  • 11
  • 27