最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - How can I make a link direct to an input field? - Stack Overflow

programmeradmin3浏览0评论

Using html (and possibly javascript = but I would prefer not) , I would like to jump from a link in one of my pages to a textbox somewhere near the button, focusing on that section. How can I do that?

Using html (and possibly javascript = but I would prefer not) , I would like to jump from a link in one of my pages to a textbox somewhere near the button, focusing on that section. How can I do that?

Share Improve this question asked Jan 15, 2012 at 19:21 YuvalYuval 5147 silver badges17 bronze badges
Add a ment  | 

4 Answers 4

Reset to default 3

Given an input that looks like:

<input id="myInput" type="text" value="" />

You could make your link automatically jump to that textbox by making the href attribute point to a hash url:

<a id="myLink" href="#myInput">Show me the textbox!</a>

And wire in javascript(with jQuery in this example) to focus on the textbox when the link is clicked:

$(document).ready(function() {
    $("#myLink").click(function(){
        $("#myInput").focus();
    });
});

You want to focus on a textbox on click of an element?

var d = document;
d.getElementById("myLink").onclick = function() {
    d.getElementById("myTextInput").focus();
};

Demo.

Assuming your textbox has an id attribute, your link can point to its id with a hash, and the onclick can focus it:

<a href='#textboxid' onclick='document.getElementById("textboxid").focus();'>Click me</a>

When the link is clicked, the page will jump to the textbox's position by the #textboxid hash, and its focus() method is called to focus it.

<a href="#myinput">Input Link</a>

<input type="text" value="Text Input" id="myinput" />

With HTML using the above code, you'll only be able to jump to the input field.

发布评论

评论列表(0)

  1. 暂无评论