Veeraraghavan N
Veeraraghavan N

Reputation: 849

Dynamic generation of a Hyperlink in html

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

Upvotes: 0

Views: 12800

Answers (2)

Jukka K. Korpela
Jukka K. Korpela

Reputation: 201836

<form action="" method="">
  <a href="http://www.example.com?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 becomes % encoded and will thus be passed as part of the value, instead of being treated as a parameter separator).

Upvotes: 0

Manatok
Manatok

Reputation: 5706

<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.com?name='+value;
}

Upvotes: 2

Related Questions