0

I have the following form line:

<input class="form_input" type="text" id="Fname" placeholder="First Name" minlength="2" maxlength="30" onkeyup="restrict('name')" />

And the associated JavaScript code:

function restrict(elem) {
    var tf = $('#' + elem)
    var rx = new RegExp()
    if (elem === 'email') {
        rx = /[^a-z0-9@_.-]/gi
    } else if (elem === 'username') {
        rx = /[^a-z0-9]/gi
    } else if (elem === 'phone') {
        rx = /[0-9()-]/gi
    } else if (elem === 'address') {
        rx = /[^a-z0-9_.,-]/gi
    } else if (elem === 'city') {
        rx = /[^a-z.-]/gi
    } else if (elem === 'name') {
        rx = /[^a-z.-]/gi
    }
    tf.val(tf.val().replace(rx, ''))
}

When I try and run the code I get the following error and I can't seem to figure out why after reviewing it many times...

TypeError: tf.val(...) is undefined

Yet everything is defined, so I'm really puzzled.

Thanks for any help! :)

0

3 Answers 3

2

id="Fname" ... onkeyup="restrict('name')"

function restrict(elem) {
    var tf = $('#' + elem)

There is no element with id name.


I suggest you also look at pattern attribute on your input for validation: https://developer.mozilla.org/en-US/docs/Web/HTML/Element/input#Attributes

Sign up to request clarification or add additional context in comments.

Comments

0

Your input has an id of "Fname", not "name". Change its id to name to fix the issue.

<input class="form_input" type="text" id="name" placeholder="First Name" minlength="2" maxlength="30" onkeyup="restrict('name')"/>

Comments

0

You need to call the function like restrict(this.id)

Comments

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.