Disable a button if the text field is empty

Hey guys, I have a quick and easy question that I guess for you. I want to find out if I can create a real-time event that will check the value of a text field. I mean, if the text box is empty, the button will not be available for viewing. I think that besides checking, to do this in code anyway? So far, I'm stuck here:

if (YourName.Text = null) { SubmitButton.Enabled = "False"; } 

Where Yourname is the text box and SubmitButton is the button :)

+4
source share
4 answers

System.String provides a couple of handy features called IsNullOrEmpty and IsNullOrWhiteSpace that you can use to test for all types of strings that look empty for end users:

 if (string.IsNullOrWhiteSpace(YourName.Text)) { SubmitButton.Enabled = false; // <<== No double-quotes around false } else { // Don't forget to re-enable the button SubmitButton.Enabled = true; } 

This will disable the button even for a string consisting entirely of empty characters, which makes sense when you check the name.

The above is identical

 SubmitButton.Enabled = !string.IsNullOrWhiteSpace(YourName.Text); 

which is shorter than the version with if .

+5
source

Well, start by turning off the button. Add a TextChanged event to the text box. And each time check if the string is empty or not (use the @dasblinkenlight code in the TextChanged event handler.

+1
source

This uses the old JavaScript approach. You can use jquery, but if that’s all you want to do, it will be redundant. In the code below, the oninput event is oninput when the text is changed either from the keyboard or with the mouse / tap (you need to write everything, this should do it for you). Then javascript receives the contents of the text field, removes the previous and trailing spaces and sets the disabled attribute of the submit button to an empty text box with the qualification .length == 0 .

Note. If you do not want to disable text that only has a space change submit.disabled = (tb.value.trim().length == 0); before submit.disabled = (tb.value.length == 0); , which eliminates the call to the trim () method. The trim () method breaks previous and trailing spaces.

This approach eliminates the need for postback to enable or disable the submit button.

 <!doctype html> <!-- tested in firefox --> <html> <head> <title>Demo</title> <script type="text/javascript"> var enableInput = function() { var tb = document.getElementById("text_box"); var submit = document.getElementById("submit"); submit.disabled = (tb.value.trim().length == 0); }; </script> </head> <body> <form> <input type="text" id="text_box" name="test" oninput="enableInput();"></input><br/> <input id="submit" type="submit"></input> </form> </body> </html> 
+1
source
 SubmitButton.Enabled = YourName.Text.Length > 0; 
0
source

Source: https://habr.com/ru/post/1479006/


All Articles