I try to enable button when press a-z/A-Z/0-9 or other special character keys that time enable button on Key up event.
click on button then disable button. but when I press other keys like ctrl, alt function Etc key that time why button enable.
i need that time disable button using reglex without keycode in jquery. not change event other only put keyup event.
<div class="settings_tab">
<input type="text" id="myInput1">
<button type="button" id="myButton" disabled>Submit</button>
</div>
<script type="text/javascript">
$(document).on('keyup', '#myInput1', function (e) {
var value = $(this).val();
const regex = /^[ A-Za-z0-9_@./#&+-]*$/;
const isMatch = regex.test(value);
if (isMatch) {
$('#myButton').prop('disabled', false);
} else {
$('#myButton').prop('disabled', true);
}
});
$('#myButton').on('click',function () {
$('#myButton').prop('disabled', true);
});
2
Answers
Pressing on control keys such as
ctrl
/alt
also triggers thekeyup
event. In your case, your regex is using*
which means matching 0 or more characters, so an empty string matched too. I have modified it to use+
instead which means matching 1 or more characters./^[ A-Za-z0-9_@./#&+-]*$/
: Match 0 or more characters inside the square bracket[]
/^[ A-Za-z0-9_@./#&+-]+$/
: Match 1 or more characters inside the square bracket[]
In this code, first to check for non-alphanumeric keys by checking the keyCode property of the event object. We disable the button if the key pressed is Ctrl (keyCode 17), Alt (keyCode 18).
Try below snippet