2
\$\begingroup\$

I want to implement jquery.alphanumeric in HTML pattern, so I used a jQuery plugin from here. Can this be shortened or improved?

<input type="text" char-allow="$#*" class="alpha">
<input type="text" char-allow="+-" class="numeric">
<input type="text" char-allow="&" class="alphanumeric">

<script>
    function setAlphaNumeric(){
        $(".numeric").each(function(){
            var a = $(this).attr("char-allow"); $(this).numeric({allow:a});
        });
        $(".alpha").each(function(){
            var a = $(this).attr("char-allow"); $(this).alpha({allow:a});
        });
        $(".alphanumeric").each(function(){
            var a = $(this).attr("char-allow"); $(this).alphanumeric({allow:a});
        });
    }

$(function(){

setAlphaNumeric();

});
</script>
\$\endgroup\$
1
  • \$\begingroup\$ Apart from suggestions in below answers, I'll suggest 1. Use data-* custom attributes 2. Use pattern attribute. Ex for alpha <input type="text" pattern="[a-zA-Z$#*]+" /> \$\endgroup\$
    – Tushar
    Commented Dec 26, 2016 at 3:05

1 Answer 1

2
\$\begingroup\$

It could be shortened to:

function setAlphaNumeric() {
  $(".numeric, .alpha, .alphanumeric").each(function() {
    $(this)[this.className]({
      allow: $(this).attr("char-allow")
    });
  });
}

$(setAlphaNumeric);
\$\endgroup\$
0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.