Kyle Brandt
Kyle Brandt

Reputation: 28387

Fill in Input Field by Clicking Link with JQuery

How might someone fill in an input field with some text using jquery by clicking that text?

The text is generated dynamically so the value is not know ahead of time.

For example with:

<input id="a_input_id" type="text">
<a href="#" class="special_field_link">@r.SpecialField<a>

When someone clicks that link the text field with be populated with the value of @r.SpecialField

Upvotes: 2

Views: 14131

Answers (3)

Chandu
Chandu

Reputation: 82893

Try this:

$(".special_field_link").click(function(){
 $("#a_input_id").val($(this).text());
});

Upvotes: 2

Amr Elgarhy
Amr Elgarhy

Reputation: 68902

HTML:

<input id="a_input_id" type="text">
<a href="#" class="special_field_link">@r.SpecialField<a>

JS:

$(function(){
    $('.special_field_link').live('click', function() {
        $("#a_input_id").val($(this).html());
    });
});

Also, you can use .text() instead of .html() as listed in this answer: Fill in Input Field by Clicking Link with JQuery

Running Sample: http://fiddle.jshell.net/s8nUh/

Upvotes: 9

Josiah Ruddell
Josiah Ruddell

Reputation: 29831

$('a.special_field_link').live('click', function(e){
    $('#a_input_id').val(this.innerHTML);
    return false; // to prevent default
});

Upvotes: 1

Related Questions