views:

138

answers:

4

I have this structure on form,

<input type="test" value="" id="username" />

<span class="input-value">John Smith</span>

<a href="#" class="fill-input">Fill Input</a>

when user click on the Fill Input ,

the data from span which has class input-value will be added to value, after clicking a tag the code should be look like this,

 <input type="test" value="john Smith" id="username" />

    <span class="input-value">John Smith</span>

    <a href="#" class="fill-input">Fill Input</a>

there are many forms element/input on the single page.

A: 
$('a.fill-input').click(function() {
    $('#username').val($('.input-value.').text());
});
Coronatus
Need to be said that this is jQuery code. Get jQuery at http://jquery.com. Get started at http://docs.jquery.com/Downloading_jQuery. jQuery documentation is at http://api.jquery.com.EDIT: Since this was tagged jQuery the author is likely to know jQuery, but i'm letting the information persist.
jwandborg
The question is tagged as jQuery. Pointless comment.
Coronatus
A: 

This should suffice for all inputs that you have so structured. It doesn't depend on the names of the elements. Note that prevAll returns the elements in reverse order so you need to look for the first input, not the last in the preceding inputs.

$('.fill-input').click( function() {
    var $input = $(this).prevAll('input[type=test]:first');
    var $value = $(this).prev('span.input-value');
    $input.val($value.text());
});
tvanfosson
+1  A: 

You can do it like this:

$('a.fill-input').click(function() {
   $(this).prevAll("input:first").val($(this).prev(".input-value").text());
});

Instead of looking only for the classes, this looks for the span and input just before the button you clicked...this means it works no matter how many of these you have on the page.

Unlike your example though, the value will be John Smith, with the same casing as it has in the span, if you actually want lower case, change .text() to .text().toLowerCase().

Nick Craver
A: 

try:

$('a.fill-input').click(function(e){
  $('#username').val($('span.input-value').text());
   e.preventDefault();
   return false;
});
jerjer