Disable button while form is not valid

Asked

Viewed 2,049 times

0

I need to disable one button to be saved when all fields are validated, the following code: button is always being disabled, but would add a condition to change only if it has been valid in the client layer?

 $('input[type=submit]').click(function (e) {

        //if ( $('#FormCadastro').valid()) {

            $(this).attr('disabled', true);
            $(this).attr('value', 'Salvando');
            $('#btnsalvar').submit();

    });

<form action="" method="post" enctype="multipart/form-data">

  div class="editor-field">
            @Html.TextAreaFor(model => model.DescricaoDaNaoConformidade, new { style = "width: 400px; height:120px;" })
            @Html.ValidationMessageFor(model => model.DescricaoDaNaoConformidade)
        </div>
  <input  type="submit" value="Salvar E Concluir" name="action:Concluir" />

</form>
  • Your question is not clear. You want the button to be activated only after all form fields are validated?

  • From what I understand you want every time some field is changed it validate and enable the button or not, correct?

  • @Rodrigogomesdias The user is double-clicking on the button when saving what causes duplicate information, I want when click save and the fields are valid to release the button and when you first click block the save button.

1 answer

2

Well, if you really want to do it that way, you need to check if the form is valid for each user interaction. If only inputs in your form, you can use the event blur jQuery. You can get the elements by anything, class, type, etc.

A simple example would be like this:

$('input').blur(function () {
   verificarForm();
});
        
function verificarForm(){
  var valid = $("#MyForm").valid();
	if(valid){
        $('#btnSalvar').prop("disabled", false);
    }
}
button:disabled {
    background: red;
}
.invalid {
    background: red;
    color: white;
}
.error {
    color: red;
}
<script type="text/javascript" src="//code.jquery.com/jquery-2.1.0.js"></script>
<link rel="stylesheet" type="text/css" href="/css/result-light.css">
<script type="text/javascript" src="https://ajax.aspnetcdn.com/ajax/jquery.validate/1.9/jquery.validate.js"></script>
 

  
<form id="MyForm" novalidate="novalidate">
    <div>
        <label for="name">Name:</label>
        <input type="text" name="name" id="name" required="" data-required-message="Name is required." class="valid">
    </div>
    <div>
        <label for="email">Email:</label>
        <input type="email" name="email" id="email" required="" data-required-message="Email is required." data-type-message="You must provide a valid email address." class="valid"><label for="email" generated="true" class="error" style="display: none;">Please enter a valid email address.</label>
    </div>
    <div>
       <button id="btnSalvar" disabled="disabled">Salvar</button>
    </div>
</form>

Example in Jsfiddle.

Remembering that the way I did is checking only the inputs. If you have textarea, checkbox, selects, among other elements, should also treat them.
And just to reinforce, don’t forget the ModelState.isValid() in your controller. Client-only validation is very dangerous as it is easy to manipulate.

Editing

To not have more than one request and duplicate the data saved, you can check if the model is valid, if you have you lock the button.
Would look this way:

    $('#btnSalvar').on('click', function (e) {
            var button = $('#btnSalvar');

            button.prop('disabled', true);

            var valid = $("#MyForm").valid();
            console.log(valid);
            if (!valid) {

                e.preventDefault();
                button.prop('disabled', false);
            } else {
                $('#MyForm').submit();
            }
        });
button:disabled {
    background: red;
}
.invalid {
    background: red;
    color: white;
}
.error {
    color: red;
}
<script type="text/javascript" src="//code.jquery.com/jquery-2.1.0.js"></script>
<link rel="stylesheet" type="text/css" href="/css/result-light.css">
<script type="text/javascript" src="https://ajax.aspnetcdn.com/ajax/jquery.validate/1.9/jquery.validate.js"></script>
 

  
<form id="MyForm" novalidate="novalidate">
    <div>
        <label for="name">Name:</label>
        <input type="text" name="name" id="name" required="" data-required-message="Name is required." class="valid">
    </div>
    <div>
        <label for="email">Email:</label>
        <input type="email" name="email" id="email" required="" data-required-message="Email is required." data-type-message="You must provide a valid email address." class="valid"><label for="email" generated="true" class="error" style="display: none;">Please enter a valid email address.</label>
    </div>
    <div>
       <button id="btnSalvar">Salvar</button>
    </div>
</form>

Source: Disabling the Submit button after one click

  • Can I do to check only when he clicks the button? I can do the validation in Submit event however the event is not triggered if the button is disabled after calling. By I want to block multiple click on the same button.

  • To do it the way you want, you cannot disable the button, or you will have to make a way to call the validation (to enable the button) before, leaving the validation in submit and in the fields. I particularly see no need to disable the button by blocking the form and thank the user to fill in correctly, no need to change the button.

  • my problem is not to make the user fill right but to block the user to click several times on the same button. So I want to block the button when being clicked the first time.

  • @Zica Why can’t you click more than once? By clicking more it’s saving 2x in the bank?

  • that’s right. Had case saved twice in the database.

  • @Zica I edited the answer, see if it fits you now.

  • not yet, this way is not done bind with the MVC controller. When disables the button it does not bind.

  • @Zica I am not changing the controller bind. The controller will only be called if the form is valid, otherwise nothing is done.

  • I expressed myself wrong, it validated the form yet does not fall into the controller.

  • @Zica It was my mistake. I changed the answer, see if it improved.

  • did not work yet, when I disable the button and do subimit it does not fall into the controller.

  • @Zica Missed the else. I tested the code here and now you’re doing what you want, or at least what I understand is what you want.

  • worked now, I think I understand a problem I have and related to having 2 buttons with different actions for the same form I am using Actionnameselectorattribute, in this example it does not send correct action so it is not working for me.

  • @Zica In this case, open another specific question with this problem, that I help you there too

Show 9 more comments

Browser other questions tagged

You are not signed in. Login or sign up in order to post.