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

javascript - Dynamic generation of a Hyperlink in html - Stack Overflow

programmeradmin0浏览0评论

I have a following scenario

<form action="" method="">
      < a href="XXXXX?name=">
      <textarea rows=3 columns=8 name=val><textarea>
</form>

The URL of the link tag should be dynamically generated based on the value of the textarea.

Could you suggest me how to go about this

I have a following scenario

<form action="" method="">
      < a href="XXXXX?name=">
      <textarea rows=3 columns=8 name=val><textarea>
</form>

The URL of the link tag should be dynamically generated based on the value of the textarea.

Could you suggest me how to go about this

Share Improve this question asked Mar 7, 2012 at 6:20 Veeraraghavan NVeeraraghavan N 8491 gold badge11 silver badges20 bronze badges 1
  • <textarea rows="3" columns="8" name="val" onchange="this.parentNode.getElementsByTagName('a').href='newLocation';"><textarea> – user1150525 Commented Mar 7, 2012 at 6:22
Add a ment  | 

2 Answers 2

Reset to default 2
<form action="" method="">
      <a id='link' href="">
      <textarea id="txt" rows="3" columns="8" name="val" onChange="updateLink()"><textarea>
</form>


function updateLink()
{
  value = document.getElementById('txt').value;
  document.getElementById('link').href = 'something.?name='+value;
}
<form action="" method="">
  <a href="http://www.example.?name=" id=link>link text</a>
  <textarea rows=3 columns=8 name=val id=val></textarea>
  <button type=button onclick="useValue()">Use it</button>
</form>
<script>
function useValue() {
  document.getElementById('link').href +=
   encodeURIComponent(document.getElementById('val').value);
}
</script>

First, you need to fix the HTML markup, closing elements properly and with some content in the link element. Then you need to decide how the operation is to be triggered; I have used the simple approach of a button (using e.g. onchange or unblur event handler is another possibility, but less intuitive). For easier reference in scripting, add id attributes to the relevant elements.

The script itself just picks up a value and appends (with +=) it to the href value of the link element, after performing % escaping with encodeURIComponent, as needed for robustness (e.g., to deal with the character “&” in input so that it bees % encoded and will thus be passed as part of the value, instead of being treated as a parameter separator).

发布评论

评论列表(0)

  1. 暂无评论