In this code snippet you will learn how to make enable and disable button validation based on user inputs using JQuery scripting.
The following is the HTML code I used for this code snippet.
HTML
- <!DOCTYPE html>
- <html>
-
- <head>
- </head>
- * All fields must have a value :
- <br />
- <br/> Field 1 :
- <input type="text" id="field1" name="field3" />
- <br>
- <br> Field 2 :
- <input type="text" id="field2" name="field2" />
- <br>
- <br> Field 3 :
- <input type="text" id="field3" name="field3" />
- <br />
- <br />
- <button id="add-fields" disabled>Click</button>
- </body>
-
- </html>
The following is the JQuery scripting I used for this code snippet.
JQuery
- <script>
- $(document).ready(function() {
- var elems = $('#field1, #field2, #field3');
- elems.on('keyup', function() {
- var hasValue = elems.filter(function() {
- return this.value.length
- }).length != elems.length;
- console.log(hasValue)
- $('#add-fields').prop("disabled", hasValue);
- });
- });
- </script>
Complete code
- <!DOCTYPE html>
- <html>
-
- <head>
- <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
- <script>
- $(document).ready(function() {
- var elems = $('#field1, #field2, #field3');
- elems.on('keyup', function() {
- var hasValue = elems.filter(function() {
- return this.value.length
- }).length != elems.length;
- console.log(hasValue)
- $('#add-fields').prop("disabled", hasValue);
- });
- });
- </script>
- </head>
-
- <body>
- * All fields must have a value :
- <br />
- <br/> Field 1 :
- <input type="text" id="field1" name="field3" />
- <br>
- <br> Field 2 :
- <input type="text" id="field2" name="field2" />
- <br>
- <br> Field 3 :
- <input type="text" id="field3" name="field3" />
- <br />
- <br />
- <button id="add-fields" disabled>Click</button>
- </body>
-
- </html>
Output
Conclusion
I hope you liked this code snippets. Thanks for reading provide your valuable comments.