Disable Buttons in jQuery Mobile

JqueryJquery Mobile

Jquery Problem Overview


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

Jquery Solutions


Solution 1 - Jquery

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.

Solution 2 - Jquery

> 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');

Solution 3 - Jquery

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.

Solution 4 - Jquery

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.

Solution 5 - Jquery

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 ).

Solution 6 - Jquery

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/

Solution 7 - Jquery

  $(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

Solution 8 - Jquery

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.

Solution 9 - Jquery

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

Solution 10 - Jquery

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

Solution 11 - Jquery

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

$("button").addClass('disabled')

Solution 12 - Jquery

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");

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
Questionswg1cor14View Question on Stackoverflow
Solution 1 - JqueryPhill PaffordView Answer on Stackoverflow
Solution 2 - JquerynaugturView Answer on Stackoverflow
Solution 3 - JqueryRwwLView Answer on Stackoverflow
Solution 4 - JqueryJörgen LindellView Answer on Stackoverflow
Solution 5 - JquerydgestepView Answer on Stackoverflow
Solution 6 - JqueryAlexView Answer on Stackoverflow
Solution 7 - JqueryYene MulatuView Answer on Stackoverflow
Solution 8 - JquerycontridView Answer on Stackoverflow
Solution 9 - JqueryVikasView Answer on Stackoverflow
Solution 10 - JqueryrobnardoView Answer on Stackoverflow
Solution 11 - JqueryofskyMohsenView Answer on Stackoverflow
Solution 12 - JquerydeblockerView Answer on Stackoverflow