Search code examples
javascriptjqueryhtmlhref

Copy the a href value to a textbox onclick


I'm trying to copy the value (the displayed name) of the link onClick to the textbox. Is it possible ?

The following is my sloppy attempt to make it work -

<div class="service_list">
    <ul style="list-style-type:square; display:none;" id="ullist">
        <li><a href="#" class="service1">Service 1</a>

        </li>
        <li><a href="#" class="service2">Service 2</a>

        </li>
    </ul>
</div>
<input type="text" id="textbox" />
<br />
<table>
    <tr>
        <td>
            <div class="button">    <a href="#" download="servicename.txt" class="button" id="button">Download</a>

            </div>
        </td>
        <td>
            <div class="list">  <a href="#" class="list" id="list">List of Services</a>

            </div>
        </td>
    </tr>
</table>

Here is the JS -

var link_selected = document.querySelector('.service_list'); //edited
var input_field = document.getElementById("input");
link_selected.onclick = function (e) {
    var selected = document.querySelector('.service_list').value; //edited
    input_field.value = selected;
};

here is the JSFiddle for the same : https://jsfiddle.net/aishwarya26/rebpb5h2/


Solution

  • You can add a click handler to each link in the #ullist element then set teh value of the text box

    var text = document.getElementById('textbox');
    var anchor = document.querySelector('#button');
    
    var links = document.querySelectorAll('#ullist a');
    for(var  i = 0;i< links.length;i++){
        links[i].onclick = function(){
            text.value = this.textContent || this.innerText
        }
    }
    

    Demo: Fiddle


    Using jQuery

    jQuery(function($){
        var $text = $('#textbox');
        $('#ullist a').click(function () {
            $text.val($(this).text());
        });
    
        $('#button').click(function (e) {
            var textbox_text = $text.val();
            var textbox_file = new Blob([textbox_text], {
                "type": "application/bat"
            });
    
            this.href = URL.createObjectURL(textbox_file);
            this.download = "servicename.txt";
        });
    
        $('#list').click(function (e) {
            $('#ullist').toggle();
        });
    })
    

    Demo: Fiddle