Vincent
Vincent

Reputation: 325

Activate submit button on valid form with jQuery Mobile

I read a lot of documentation about jQuery Mobile, buttons and forms, but I have did not understanding everything. So, I want to deactivate a submit button until form responses are not valid.

Here is my working code...

$(document).ready(function() 
{
    /* $('#submit').button('enable') */ /* Console says "Uncaught TypeError: Object [object Object] has no method 'button'" */
    $('#submit').attr("disabled", true);
    /* Do stuff */
    $('#form').live('keyup change', function()
    {
    if (isEmailValid && isTextValid)
    {
        /* $('#submit').attr("disabled", false); */ /* Button is not enable */
        $('#submit').button('enable');
    }
    });
})
...
<div class="content-primary">
    <form id="form">
    <button data-theme="a" id="submit" type="submit">Submit</button>
    </form>
</div>

My code is working in Chrome, Firefox and Internet Explorer, but I do not understand the logic: I turn off and turn on submit differently!

Is my solution however the right one?

Thanks for your help.

Cheers,

V.

Upvotes: 0

Views: 2371

Answers (1)

Jasper
Jasper

Reputation: 75993

You can use the jQuery Mobile button() function to enable and disable the submit button widget:

$(document).delegate('[data-role="page"]', 'pageinit', function () {
    var $submit = $(this).find('#submit'),
        $text   = $(this).find('input[type="text"]');
    $text.bind('keyup', function () {
        if (this.value == '') {
            $submit.button('disable');
        } else {
            $submit.button('enable');
        }
    }).trigger('keyup');
});

Here is a demo: http://jsfiddle.net/tewV6/

Also, you want to get away from using the document.ready event handler when using jQuery Mobile. Instead use pageinit targeted at the data-role="page" elements like in my example above.

Upvotes: 3

Related Questions