简体   繁体   中英

How do I dynamically focus on input element at run time

I want to dynamically focus on input element at run time. I will pass input name runtime and then it should focus the input accordingly.

This is code for input element

<input type="text" id="txtNameOfEmp" data-bind="event: { blur: ValidateName.bind($data,txtNameOfEmp) } " />

Then in my view model i am trying to focus as below

    self.ValidateName = function (val) {
        var inputName = val.id;

            // some logic for validation
            alert("Name is not valid");
            $("'#" + inputName + "'").focus()

    };

I get error

JavaScript runtime error: Syntax error, unrecognized expression: '#txtNameOfEmp'

How to focus dynamically?

Update1

I have also tried below but it doesnt give error but doesnt set any focus as well

$(inputName).focus();

You've got too many quotes. You don't need any as you've wrapped your id in a variable.

Try this:

$("#" + inputName).focus()

Man... there is a mistake in your code as I see it:

remove the single quotes:

use $("#"+inputName).focus();

尝试这个:

  $(inputName).focus();

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