Search code examples
javascripthtmlhyperlinkhrefgetelementbyid

Create a URL hyperlink (href) using getElementById from user Input


Is there a way I can create a hyperlink or Link based from getElementById from user inputs?

This is my code for user inputs:

<input type="text" class="form-control" id="first_name" name="first_name" placeholder="First Name">
<input type="text" class="form-control" id="last_name" name="last_name" placeholder="Last Name">
<br><button type="button" onClick="generateURLX();">Generate URL</button></br>

This is the part where I determine those id in a function

<script>
function generateURLX()
{
var partx = document.getElementById('first_name').value;
var party = document.getElementById('last_name').value;
var urlx = "https://example.com/"+partx+"/"+party+".html";
document.getElementById('resultx').innerHTML = urlx;
</script>

And this is where I display the hyperlink:


<span id="resultx"></span>

I tried using <a href but I failed on making a hyperlink for that specific id=resultx which is basically based from var urlx

<a href="#resultx"></a>

Solution

  • All right, you computed the value of urlx right?

    What you need is an identifier for the hyperlink you want to address, then you can use something like this:

    HTML

        <a id="linkx" href=""><;/a>
    

    CODE

        document.getElemebtById("linkx").href = urlx;
    

    And it should work ok.