简体   繁体   中英

How do I create a hyperlink inside an input text field in html?

I have an input text field in which the user can enter the name of a website. Is it possible for it to be hyperlinked so that once the field is saved, if the user clicks on it, it redirects to the website?

I use Django for the backend and Javascript and html for the front end.

An input field's value is stored as plain text, therefore you cannot include HTML (ie a link) and expect the HTML to be parsed and functioning.

You could simulate this behavior with JavaScript, however I would recommend against it. (You would add a click listener, your function would pull the value of the field, see if it is a valid URL, and then open up the location.)

I'm not going to write the code for this because it would be a terrible user experience. The standard behavior for an input field is that you click on it to edit the text. This is an assumption your users have, and they would therefore (a) not think to click on it because they don't expect it to be a link, and (b) click in it if they wanted to edit the text, only to be redirected and unable to edit the text.

Alternatively, you could add a small button next to the input, ie 'Open' or 'Test' or an external link icon.

Simply, if you are printing the URL for the user on their profile page, sure you can just print it as follows:

<a href='$url'>$url</a>

That's PHP but of course you can do this in any language. I'm not sure if this answers your question since you ask if it can be printed "inside" the field which isn't possible/doesn't make sense.

HOWEVER, think about security. Remember the user can enter any malicious URL into this field, so you need to be aware of who you are potentially linking this to on your website/application.

Useful resources:

URL HTML field: https://developer.mozilla.org/en-US/docs/Web/HTML/Element/input/url

Validate URL format with Django (does not check if malicious or not though): How can I check if a URL exists with Django's validators?

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