i have text field in users can enter numerical field numerical operators. following set of examples valid input
1. > 3 2. >= 3 3. < 3 4. <= 3 5. <> 3 (not) 6. 3 5 (range) 7. <> 3 5 (not range) i've following logic works. iterate through each regex on keyup. wanna know there more elegant , better way this?
function myfunction() { var x, text; // value of input field id="numb" x = document.getelementbyid("numb").value; var arrregex = new array("^>=\\d+$", "^<=\\d+$", "^>\\d+$", "^<\\d+$", "^\\d+$", "^<> \\d+$", "^<> \\d+ \\d+$", "^\\d+ \\d+$"); c = false; (i = 0; < arrregex.length; i++) { var regex = new regexp(arrregex[i]); if (regex.test(x)) { c = true; } } if (c == true) { document.getelementbyid("numb").style.backgroundcolor = "green"; } else { document.getelementbyid("numb").style.backgroundcolor = "red"; } }
you can set regexp value of pattern attribute @ <input> element, use css :invalid style background property of element; toggle classname @ element @ input, focus events if element .value.length === 0 or :not(:focus) @ css, set background unset !important, else remove classname apply css :valid, :invalid styles
input:invalid { background: red; } input:valid { background: green; } input:not(:focus), .clear { background: unset !important; } <input pattern="^(|>=\d+$|<=\d+$|>\d+$|<\d+$|\d+$|<> \d+$|<> \d+ \d+$|\d+ \d+)$"> <script> var input = document.queryselector("input[pattern]") input.onfocus = input.oninput = function() { this.classlist.toggle("clear", this.value.length === 0) } </script>
Comments
Post a Comment