简体   繁体   中英

General script: selecting the input element for which keypress event is fired, without actually passing the ID etc

I am writing a general Jquery script for validation and I am stack at selecting the element for which the keypress event is fired, without actually passing the ID element #elementid specified in the below code.--> var element = **pick the object**// $('input[type=number][validate=something]'); .

  • Note that the below code pickup all the input field of number type and attribute value of validation as something .
  • get the value of maxlength of the field for which keypress event has occured.
  • avoid java script function call inside input.
  • write a general script that could be applicable for all page and not pick element by id attribute.

Sample JS below

<!DOCTYPE html>
<html>
<head>
  <title>Validation</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
</head>
<body>
        <input validate="something"  type="number" maxlength="9"  />
    <input validate="something" type="number" maxlength="9"  />

<script>
$('input[type=number][validate=something]').on('keypress', function(evt,obj) {
                var element =**pick the object**// $('input[type=number][validate=SSN]');
                var len = element.val().length + 1;
                var max = element.attr("maxlength");

                if (!(len <= max)) {
                    // some code
                }
});
</script>
</body>
</html>

The element you've hooked the event on is available within the handler as this ; to wrap it in an jQuery object, use $() :

var element = $(this);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM