JohnnnCarlo
JohnnnCarlo

Reputation: 1

How to get the value of the user input to href it?

I want to get the value of the input to make it as an HREF, for example, the user input is 192.168.1.1, I want to redirect to that input as the button is clicked so I can go directly to that IP address here is my code:

function displayCam()
{
    var ip = document.getElementById('ipadd');
    document.getElementById('camView').innerHTML = ip.value;
}
<h1>Input IP Address</h1>
<label for="ipadd">Enter IP Address:</label>
<input type='text' id='ipadd' />
<input type='button' onclick='displayCam()' value='Submit' />   
<div id="camView"> </div>

Upvotes: 0

Views: 1778

Answers (3)

Manoj Kumar
Manoj Kumar

Reputation: 322

You can do like this:

Put anchor tag inside the div and set href dynamically on button click

<script>
function displayCam()
{
    var ip = document.getElementById('ipadd');
    document.getElementById('camView').innerHTML = ip.value;
    document.getElementById('camView').href="http://"+ip.value;

    //Or to open in new tab on submit button directly 
    var url="http://"+ip.value;
    window.open(url)
}
</script>

<h1>Input IP Address</h1>
<label for="ipadd">Enter IP Address:</label>
    <input type='text' id='ipadd' />
    <input type='button' onclick='displayCam()' value='Submit' />

<div><a href="" id="camView" target="_blank" ></a></div>

Upvotes: 0

Christopher Bradshaw
Christopher Bradshaw

Reputation: 2775

To redirect to the ip address they added, you could modify displayCam to look like this:

function displayCam()
{
    var ip = document.getElementById('ipadd');
    document.getElementById('camView').innerHTML = ip.value;
    if (ip.value.indexOf('://') === -1) {
        ip.value = "http://" + ip.value; // Use http by default
    }
    window.location.href = ip.value;
}

Upvotes: 2

TiemenV
TiemenV

Reputation: 21

Use window.location.href = ip.value;

Upvotes: 2

Related Questions