2

Basically I want to know that how to build code snippet so that when a user input text and click on the submit button. Automatically add https:// as prefix and .com as suffix and build a valid urls using javascript. And that result should be visible right below the form.

Can anyone help me

2
  • Provide some code what you've tried so far, explain the point where you've got stuck and need help. Commented Jun 24, 2021 at 5:07
  • Most of the time you don't want to generate an URL but verify an entered URL by a complicated regex or simply like this. Commented Jun 24, 2021 at 10:42

2 Answers 2

1

Try this out, it take input and covert it to a link by adding https:// and .com

To see it working here just type input as: stackoverflow. If you want to test it with other sites, copy and use the code locally.

function urlMaker(){
  var linkVal=document.getElementById("inputText").value;
  var href =  document.getElementById('aLink').href="https://"+linkVal+".com";
  document.getElementById("aLink").innerHTML = href;
 }
<input name="inputTxt" type="text" id="inputText">
<button onclick="urlMaker()">Get Link</button>
<br><br>
<a href="#" id="aLink"></a>

Sign up to request clarification or add additional context in comments.

Comments

0

Yes, it is possible, you just add a keyup or change event listener on the input, and concatenate the text from the input with what you need. Here's an example:

// HTML
<div class="container">
    <input type="url" id="url-maker" />
    <p class="url-output"></p>
</div>
// JS
const urlInput = document.getElementById('url-maker');
const urlOutput = document.querySelector('.url-output');

urlInput.addEventListener('keyup', (event) => {
    let urlText = event.target.value;
    if (!urlText.includes('https://')) {
        urlText = `https://${urlText}`;
    }
    if (!urlText.includes('.')) {
        urlText = `${urlText}.com`;
    }
    urlOutput.innerText = urlText;
});

However, you do need to properly validate the strings and also keep in mind that domains end in other extensions than .com! What I've showed you is just a basic example!

2 Comments

How to toggle output. No output is showing have submit button in it na??
You don't need a submit if you have keyup or change events in order to preview your URL, it will automatically appear under the input while you type, or if you leave the input field (if you use the change event). But you could add a button and change the event to click instead of keyup. You only need a submit button to send data to the server. Here's a preview on CodePen!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.