How to set up smartphones and PCs. Informational portal

JavaScript - How to make a button active and inactive depending on conditions.

So today I needed to make one feature in my new project. The project is large enough to explain what and how and therefore I will talk about the very essence of this “feature”.

The task was to allow the admin to delete users from the database. So we set the search parameters and the php script gives us a list of users. Opposite each user is a square checkbox (checkbox) switch, so that you can select and delete.

But not everything is so simple. The task was to make the “delete” button inactive, and become active only at the moment when at least one checkbox is selected. Naturally, JavaScript monsters will say, yes, there are two fingers on the asphalt. But I am not a JS monster, and I resort to programming in this language only when I want something like that, for convenience.

So, as a decent person, I got into the network, and Yandex and Google and all sorts of portals there stuffed a lot of different code into my browser from which my brain still blinded exactly what I needed. As it turned out, there are really no normal (working) examples on the network, and therefore, so that another person like me does not blow his brain, I decided to post a working example of JavaScript code.

The HTML implementation, I think, is not difficult to understand, but still I will add it:

1 - One
2 - Two
3 - Three
10 - Ten

So what is the main problem I am facing. It turns out that you can “turn off” the button as you like, i.e. by accessing the submit element in any available form:

submit.disabled = true;

However, it is impossible to enable (replace with false) in a similar way, and that is why I have already dug up such a construction:

Document.form_del.elements["submit"].disabled = true;

And here, if we replace true with false, then the button turns on and off. And finally, I will decipher this line of code:

In the current document in the form named “form_del”, the element with the name “submit” (and in our example this name is the button) has the “disabled” property, so we turn it on “true” or turn it off “false”. That. by enabling this property we will make our button inactive, and by disabling the property, our button will become active again.

Dear site visitors who ask questions like "How to attach your shopping cart to the site?" etc. I do not make ready-made solutions, I describe the implementation logic, for each individual site you will need to add certain things in any case, so if you really need to fasten or attach something, I provide paid and free services for consulting and finalizing sites. Write to the feedback form at the top of the page, I will answer everyone.


Disabled submit button (DISABLED attribute)

Sometimes on the site it is necessary to make a form into which the user enters some data. There can be any number of fields in the form, but there are always mandatory fields. How to check if the user has filled in the required field or not. There are two ways:

  1. Check in the handler, i.e. the user fills in the required fields, submits the form, and then the handler checks the required fields, and if any field is not filled, it returns the user back. Everything is simple, however, a mechanism is needed to transfer the values ​​​​of already filled fields back to the form, which can be implemented using sessions, but this is not very convenient.
  2. Validation by JavaScript methods - everything is much simpler (in terms of how the form itself works). We set each field an onchange event or any other event that responds to the user's action (well, not onmouseover of course, although it can probably be done even funny ...), after which the function we wrote will check if the required fields are filled in and allow or disable the submit button.

The first option is more related to the PHP section, so it will not be considered for now. Let's consider the second one in more detail. The first thing we need is the form itself:







As you can see, the Submit button has a disabled attribute set to disabled. Also, each form field has an onchange event that calls the EnableButton() function. What is this function? Let's say the required fields are field1 and field3, then the EnableButton() function would look like this:

function EnableButton()
{
with(document.forms.form1)
{
if(field1.value!=""&&field2.value!='')
{
disable_button.disabled= false;
}
else
{
disable_button.disabled= true;
}
}
}

Unfortunately, I haven't found a JavaScript analogue of the PHP empty() function, so the field values ​​have to be compared with an empty string. Another thing worth paying attention to is the with statement (document.forms.form1). For those unfamiliar with JavaScript, the parenthesized expression of the with statement will be added to all objects, which can significantly shorten the function entry. Without with EnableButton() it would look like this:

function EnableButton()
{
if(document.forms.form1.field1.value!=""&& document.forms.form1.field2.value!='')
{
false;
}
else
{
document.forms.form1.disable_button.disabled= true;
}
}

Agree - quite cumbersome.
As a further note, the disabled attribute can be used on any form element. An example is filling in information about the company - legal and postal address. Two fields for two addresses, however, you can add a checkbox (- matches the legal one), marking which, the user will indicate that the postal address field does not need to be processed and you can add the disabled attribute to it.

) the question was raised about whether it would be good for the buttons of the form sent to the server to set the disabled = "disabled" property.

However, so far they have not figured out why this is necessary and how to do it anyway. It would seem that it could be simpler and what you can talk about here at all, but no - in fact, everything turned out to be not so trivial. Immediately, I note that the following reasoning applies to both types of forms: both sent via regular SUBMIT and using AJAX.

Why you need to make buttons inactive

  1. To make it obvious to the user that he has already clicked on the button and that the form is being submitted
  2. So that the server is not loaded with unnecessary requests, and to reduce the likelihood of any error
It is clear that you can prevent unnecessary clicks by hanging a special visualization that says that the request is accepted and the form is submitted (the simplest example is to show some kind of animated gif). However, the buttons will still remain clickable, and the most impatient users will not take advantage of this opportunity. At the same time, the form will no longer be able to respond to these additional clicks (the animated gif is already spinning), and the user's frustration will only increase.

It is also clear that unnecessary requests can be prevented by adding some class="form_is_loading" to the form, and checking for the presence of this class at every submission. But why do these checks when you can do without them by simply making the button inactive?

How to make buttons inactive

This simple variant proposed in the above-mentioned topics turns out to be insufficient and unworkable.

Why is it not enough to just make the pressed button inactive:

  1. Submit forms can also occur by pressing Enter. Therefore, the processing of buttons must be hung up on the onsubmit event of the form itself. Also, a form can have multiple buttons, and it would make sense to make them all inactive, not just the button that was pressed.
  2. If, after submitting the form, we return to the page with the form again (using the “Back” button in the browser), then caching will work: we will encounter inactive buttons and will not be able to submit the form again - without forcing a page reload with the loss of all previously filled fields (Return to search form from the search results page here is a lively example).
  3. If the form has several buttons (for example, "Publish" and "Cancel"), then we will not be able to tell the server which button was pressed: an inactive button does not send its name and value - even if we make it inactive on the onsubmit event
So, the script for creating inactive buttons

Briefly, the scenario is as follows.

  1. Buttons are made inactive by the onsubmit event of the form
  2. We return the buttons to the active state before leaving the page by the window.onunload event
  3. Each form button on the onclick event must create a hidden field of the same name, through which it will pass its value to the server
And then follows a more detailed script with code layout.

//// html file //////////////////////////////////////////// //////////////////////////

//// js file //////////////////////////////////////////// /////////////////////////////

The topic of today's article will be the filling form, namely it, a little validation. To be more precise, this is not really validation, because there will be no check for the correctness of the input. This method makes the submit button inactive until the required fields in the form are filled.

Blocking the submit button until the fields are filled is achieved with jQuery. A small script will help us, which will carry out our plans. Let's make such a form with an inactive button.

Including the jQuery library

The first step is to connect to the header before closing head or in the basement before closing body libraries jQuery.

Here you need to be very careful, sometimes the library has already been connected before and re-connecting it will lead to a conflict and inoperability of the script. So, in cases of not working, try not to connect this library or change the connection location.

Submit Button Script

Function checkParams() ( var name = $("#name").val(); var email = $("#email").val(); var phone = $("#phone").val(); if(name.length != 0 && email.length != 0 && phone.length != 0) ( $("#submit").removeAttr("disabled"); ) else ( $("#submit"). attr("disabled", "disabled"); ) )

In lines 2,3,4 we set our fields, namely their ID in the future form and assign them names for the script to work. As he said, there are three of them, so if necessary, you can remove the extra ones or add the ones you need.

The 6th line sets the parameters by the number of characters in the fields. This code contains the parameter != 0 , that is, if there is nothing in the field, it does not unlock the button, if at least one character is entered, this field is considered filled. And as you can see, we have three fields and each has the same parameter.

If you need to set a different minimum number of characters, then you need to change the code a little. If you simply replace "0" with the desired number, it will not work. For everything to work, you need to replace:

!= 0 to >=7

That is, we set the parameter to allow sending if the field is greater than 7 characters. That is, the button is not activated until the field where the specified parameter is 7 or more characters long. Let's set the following parameters. For the name there are 2 characters, for mail - 5 and number 7. The finished 6th line of the script looks like this:

If(name.length >=2 && email.length >=5 && phone.length >=7) (

For those who are interested in the question - And how to specify the maximum number of characters?. Answer: in HTML code, in the field input write the attribute

maxlength="15"

which sets a limit of 15 characters. Just enter your number.

The 7th and 9th lines contain the ID of our future button - "Submit" from the form, which will be unlocked if the conditions are met. In this case, this is #submit.

HTML code

Now let's insert a simple form with three fields. Our form will submit name, email and phone number. You can also use your own form.




For everything to work, firstly - you need to add an event to the required fields -

onkeyup="checkParams()"

which runs our script.

Secondly, add the disabled attribute to the button, which will be canceled by the script when the required fields are filled.

Third at the margins input there must be an ID, which is also indicated in the script, as I said above.

That's the whole way. It is not complicated, although the article turned out to be not small. If you carefully read and understand everything, then you should not have any difficulties.

This method helped me when creating forms that use ajax and send a letter without reloading the page, regardless of whether the fields are filled. That is, if a person starts simply pressing the button, then empty letters will go, otherwise the button is blocked and does not allow this to be done.

That's all, thanks for your attention. 🙂

Top Related Articles