5

For instance, I know that it is possible to do something in Javascript that allows users to update text based on user text input:

<script type="text/javascript">
function changeText2(){
var userInput = document.getElementById('userInput').value;
document.getElementById('boldStuff2').innerHTML = userInput;
}
</script>
<p>Welcome to the site <b id='boldStuff2'>dude</b> </p> 
<input type='text' id='userInput' value='Enter Text Here' />
<input type='button' onclick='changeText2()' value='Change Text'/>

View the above code in action at: tizag.com/javascriptT/javascript-innerHTML.php

However, instead of the above code, I would like to know if it's possible to do something similar for a url link. Below I've placed a step by step example of what I would like to happen upon the user inputing text:

  1. Original Link: http://www.google.com/search?q=

  2. User Input in Text Field: espn

  3. User clicks button to submit text in text field

  4. Final Link: http://www.google.com/search?q=espn

Thanks for your help...BTW...if you can't tell I'm a bit of a novice so detail is appreciated.

Doug
  • 51
  • 1
  • 1
  • 2
  • As of "3. User clicks button to submit text in text field" and "4. Final Link" Does that mean, instead of a single click, the user has to two clicks at different positions, to trigger a search? – feeela Aug 17 '11 at 18:46
  • 1
    If you don't need to change the content of the "submit button", you would probably be better off just using a form. http://jsfiddle.net/X2FkH/1/ – circusbred Aug 17 '11 at 18:48

7 Answers7

11

Here's one in plain JS that updates as you type:

<a id="reflectedlink" href="http://www.google.com/search">http://www.google.com/search</a>
<input id="searchterm"/>

<script type="text/javascript">
    var link= document.getElementById('reflectedlink');
    var input= document.getElementById('searchterm');
    input.onchange=input.onkeyup= function() {
        link.search= '?q='+encodeURIComponent(input.value);
        link.firstChild.data= link.href;
    };
</script>

Note:

  • no inline event handler attributes (they are best avoided);

  • assigning both keyup and change, to try to get keyboard updates as they happen and ensure that all other updates get caught eventually;

  • the use of encodeURIComponent(), necessary in case the search term has any non-ASCII or URL-special characters in;

  • setting the search property of a Location (link) object to avoid having to write out the whole URL again;

  • setting the data of the Text node inside the link to reflect the full URL afterwards. Don't set innerHTML from user input as it may have HTML-special characters like & and < in.

bobince
  • 528,062
  • 107
  • 651
  • 834
  • oh ho ho, he scores with the input.onchange=input.onkeyup – Loktar Aug 17 '11 at 18:45
  • @bobince - a good 1-up on your part ^_^. I did not add the onkeyup to my answer, but that was a good add on :-D – Naftali Aug 17 '11 at 18:46
  • You rock man +1 for exactly what I was looking to do. I was trying to do the same only not for google but a custom search for other similar OpenSearch formatted URLS. I checked the reflected link URL to mine, then updated the link.search= to be more then the ?=. I was trying to mimic the behavior of "search engines" in Google Chrome Browser on a website. Thanks! – Blake Russo Feb 19 '17 at 21:42
  • @bobince Thanks for this example! How can I make it so that there is no `?` injected by the code? For example, I just want to add `/10` to the end of a URL, not `?/10` – dimitrieh Jun 21 '20 at 14:48
4

#1: you need some forms
#2: you need to catch when the form is submitted
#3: based on the form's submission change the url

Here is a demo: http://jsfiddle.net/maniator/K3D2v/show/
here is the code: http://jsfiddle.net/maniator/K3D2v/embedded/

HTML:

<form id="theForm">
    <input id='subj'/>
    <input type='submit'/>
</form>

JS:

var theForm = document.getElementById('theForm');
var theInput = document.getElementById('subj');

theForm.onsubmit = function(e){
    location = "http://jsfiddle.net/maniator/K3D2v/show/#" 
                              + encodeURIComponent(theInput.value);
    return false;
}
Naftali
  • 144,921
  • 39
  • 244
  • 303
  • 1
    You don't need a form. It adds nothing but extra bandwidth. – Craig M Aug 17 '11 at 18:53
  • @CraigM You need a form if you want server-side support. – Raynos Aug 17 '11 at 18:56
  • There's no server side component to this question, hence you don't need the form. – Craig M Aug 17 '11 at 19:00
  • @CraigM -- and if the user has javascript disabled -- \*poof\* the form does not work anymore (when there is no `form` tags)... – Naftali Aug 17 '11 at 19:01
  • Then you can't update the href of a link dynamically which is what he wants to do. Are you really going to submit back to the server and rerender an entire page to update a single link? I don't think so. If you do, you're making very bad design choices. – Craig M Aug 17 '11 at 19:08
  • 2
    Bad design choices? No, you're being commendably conscientious. Progressive enhancement demands you make it work without script first, then smooth it up with client-side niceness afterwards. Whether it makes sense practically to do so in this case, or whether it's excessive/pointless, depends on what the ultimate aim of the code is... not enough information in the question to guess that bit! – bobince Aug 17 '11 at 19:20
1

This is the solution I deviced in a matter of seconds:

<input type="text" name="prog_site" id="prog_site" value="http://www.edit-me.com" />
<a href="#" onclick="this.href=document.getElementById('prog_site').value" target="_blank">Open URL</a>

No complex javascript, no extra quotes nor functions required. Simply edit the ID tag to your needs and it works perfectly.

andreszs
  • 2,896
  • 3
  • 26
  • 34
1

I'd suggest using a cross browser library such as jQuery rather than straight JavaScript. With jQuery, you'd add a click handler for your button, grab the value of the input, build your URL, and set window.location to go to the new url

jsFiddle

HTML

<input type="text" id="q" />
<input type="button" id="submit" value="submit" />

JavaScript

$(function () {
    $('#submit').click(function() {
        var url = "http://www.google.com/search?q=";
        url += $('#q').val();
        window.location = url;
    });
});
Craig M
  • 5,598
  • 4
  • 32
  • 43
  • 1
    I have to agree with @Neal on this one, question wasn't even tagged jQuery. – Loktar Aug 17 '11 at 18:40
  • @Craig -- also try to use form.submit not input.click ... or else the form will be submitted. – Naftali Aug 17 '11 at 18:40
  • There's a very good reason to use jQuery. As his application grows, he'll undoubtedly get to the point where he needs to write some code that performs differently cross browser. Start with jQuery (or Zepto if jQuery is too big for your taste) and you don't have a mishmash of native DOM manipulation code mixed in with jQuery code. There's no reason to create a form as in your example. You've just created excessive markup. – Craig M Aug 17 '11 at 18:54
  • 1
    I don't feel jQuery is a bad solution here. It's easy to use for newbies, as this guy likely is, and it's cross browser compatible. Basically substitute any modern dom manipulating library and do something similar. I don't see any need to submit the value unless they want to store that data. Therefore I don't really see a need for a form or submit button here. A simple button and some script should accomplish the task/ – Hcabnettek Aug 17 '11 at 18:58
1

You could try this;

<script type="text/javascript">
function changeText2(){
    var userInput = document.getElementById('userInput').value;
    var lnk = document.getElementById('lnk');
    lnk.href = "http://www.google.com?q=" + userInput;
    lnk.innerHTML = lnk.href;
}
</script>
Here is a link : <a href="" id=lnk>nothing here yet</a> <br>
<input type='text' id='userInput' value='Enter Search String Here' />
<input type='button' onclick='changeText2()' value='Change Link'/>

Check it out here

Soren
  • 14,402
  • 4
  • 41
  • 67
0

I think this might be useful:

.btn {
    border: none;
    outline: 0;
    display: inline-block;
    padding: 10px 25px;
    color: black;
    background-color: #ddd;
    text-align: center;
    cursor: pointer;
}
              
.btn:hover {
    background-color: #555;
    color: white;
}

.textinput {
  line-height: 2.5em;
}
<!DOCTYPE html>
<html>
  <head>
    <link rel='stylesheet' href='https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css' integrity='sha384-Gn5384xqQ1aoWXA+058RXPxPg6fy4IWvTNh0E263XmFcJlSAwiGgFAW/dAiS6JXm' crossorigin='anonymous'>
  </head>
  <body>
    <form action='#' method='post'>
      <label for='ytid'>Please enter your YouTube Video ID:</label>
      <br>
      <br>
      <iframe
        href='#'
        width='287.5'
        height='250'
        frameborder='0'
        allow='accelerometer; autoplay; encrypted-media; gyroscope; picture-in-picture'
        allowfullscreen
        src='https://www.youtube.com/embed/'
        id='ytvid'
      ></iframe>
      <br>
      <br>
      <input
        type='text'
        class='textinput'
        size='50'
        id='ytid'
        name='ytid'
        placeholder='m4jmapVMaQA'
        minlength='1'
        maxlength='11'
        onchange='document.getElementById("ytvid").src = "https://www.youtube.com/embed/" + this.value'
      >
      <br>
      <br>
      <button type='submit' class='btn'>Generate Subtitles &raquo;</button>
    </form>
  </body>
</html>

WARNING: This code snippet might not run well in Stack Overflow.

This way, the video updates every time there is a change in the text input.

I'm actually making a YouTube Video subtitle generator, so I just copy pasted my code here.

Pyzard
  • 451
  • 3
  • 14
0
<a href="www.google.com/search?q=" id="link">www.google.com/search?q=</a><br>
<input type="text" id="userInput" value="Enter your text here"><br>
<input type="button" onclick="changeText2()" value="change text">
<script>
function changeText2()
{
    var input=document.getElementById('userInput').value;//gets the value entered by user
    
    //changing the href of tag <a> by concatenatinng string "www.google.com/search?q=" and input (user input)
    document.getElementById("link").href = "www.google.com/search?q="+input;
    
    //changing the text from "www.google.com/search?q="  to "www.google.com/search?q=" + user input
    document.getElementById("link").innerHTML = "www.google.com/search?q="+input;
}

Clicking the button calls the function changeText2. Which performs the task.