tags:

views:

37531

answers:

5

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?

+20  A: 

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?

Falco Foxburr
Thanks for that. From your code I was able to tell what went wrong. It was a whitespace problem (I had the actual text inside the anchor tag on a separate line).
Kevin Pang
+6  A: 

Just to note that prefixing the tagName in a selector is slower than just using the id. In your case jQuery will get all the inputs rather than just using the getElementById. Just use $('#textbox')

redsquare
This answer would likely be better as a comment on the question.
icktoofay
+1  A: 

Following redsquare: You should not use in href attribute javascript code like "javascript:void();" - it is wrong. Better use for example href="#" and then in Your event handler as a last command: "return false;". And even better - use in href correct link - if user have javascript disabled, web browser follows the link - in this case Your webpage should reload with input filled with value of that link.

Falco Foxburr
A: 

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

$("#textbox").get(0).value = "blah"

+3  A: 

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

$("#textbox").val('Blah');

max
I believe the person that asked the question already knew that, as you can see that in his code.
icktoofay