Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I set a textbox's value using an anchor with jQuery?

Tags:

jquery

I have a textbox whose value I want to set based on the inner text of an anchor tag. In other words, when someone clicks on this anchor:

<a href="javascript:void();" class="clickable">Blah</a>

I want my textbox to populate with the text "Blah". Here is the code I am currently using:

<script type="text/javascript">
    $(document).ready(function(){
        $("a.clickable").click(function(event){
            $("input#textbox").val($(this).html());
        });  
    });
</script>

And in my html there is a list of anchor tags with the class "clickable" and one textbox with the id "textbox".

I've substituted the code above with code to just show a javascript alert with $(this).html() and it seems to show the correct value. I have also changed the $(this).html() to be a hardcoded string and it setes the textbox value correctly. But when I combine them the textbox simply clears out. What am I doing wrong?

like image 968
Kevin Pang Avatar asked Sep 10 '25 07:09

Kevin Pang


2 Answers

I wrote this code snippet and it works fine:

<a href="#" class="clickable">Blah</a>
<input id="textbox">
<script type="text/javascript">
    $(document).ready(function(){
        $("a.clickable").click(function(event){
            event.preventDefault();
            $("input#textbox").val($(this).html());
        });  
    });
</script>

Maybe you forgot to give a class name "clickable" to your links?

like image 151
Falco Foxburr Avatar answered Sep 12 '25 21:09

Falco Foxburr


To assign value of a text box whose id is ёtextboxё in jQuery please do the following

$("#textbox").val('Blah');
like image 30
max Avatar answered Sep 12 '25 21:09

max