DilipAgarwal
DilipAgarwal

Reputation: 7

Enabling button on any value change in JSF form

I have multiple fields including text,checkbok box, drop-down etc in jsf form, which is showing values from DB.I would like the submit button to be disabled by default and to only be clickable if the user made changes to any of the fields in the form. Please help !!

Upvotes: 0

Views: 1797

Answers (2)

mrganser
mrganser

Reputation: 1113

For a simple form you can use this jQuery plugin that a user mentioned here.

Edit:

The plugin is quite simple to use, and powerful, because for example you will have your buttons disabled again if you revert changes inside an input field.

Just make sure that you include the js file:

<h:outputScript name="path/jquery.are-you-sure.js"/>

And for using it, you have to add the line:

$('#idofyourform').areYouSure();

After that, for enabling and disabling submit buttons you have to add:

//All disabled by default
$('#idofyourform').find('button[type="submit"]').attr('disabled', 'disabled');
//Enabled all when there are changes
$('#idofyourform').bind('dirty.areYouSure', function () {
    $(this).find('button[type="submit"]').removeAttr('disabled');
});
//Disable all when there aren't changes
$('#idofyourform').bind('clean.areYouSure', function () {
    $(this).find('button[type="submit"]').attr('disabled', 'disabled');
});

Both codes inside your document ready function.

Note that I used button[type="submit"], which is what p:commandButton renders by default. You can use input if it's your case.

NOTE: This plugin also adds an extra functionality the OP didn't ask for (the dialog check when you navigate without saving changes). You can disable this if you want by doing:

$('#idofyourform').areYouSure( {'silent':true} );

Upvotes: 1

Alexandre Lavoie
Alexandre Lavoie

Reputation: 8771

Not tested, but I would simply use something like this :

$(document).ready(function() {
    $('#formId input[type="submit"]').attr('disabled','disabled');
    $('#formId').change(function(){ $('#formId input[type="submit"]').removeAttr('disabled'); });
});

If you don't use any jQuery functions already in the view (any PrimeFaces ajax buttons for example), you might need to add :

<h:outputScript library="primefaces" name="jquery/jquery.js" />

Upvotes: 0

Related Questions