3

I'm trying to output the values of multiple input-fields into a single div. But I simply can't get it to work. It will only output one of the input-fields into the div at a time.

This is my jquery:

var $output = $('#output-content-here');
  $('input').keypress( function() {
  $($output).text(this.value);
});

I have made a jsiddle to show you what i mean: http://jsfiddle.net/A7UbK/1/

Thanks.

1
  • 4
    A general piece of advice: Never double wrap a jQuery object (as in $($output), $output already being a jQuery object). It accomplishes nothing, but adds run-time. Commented Jul 10, 2014 at 9:38

3 Answers 3

2

Try the following code using .map()

var $output = $('#output-content-here');

$('input').keyup(function () {
    $output.html(function () {
        return $('input').map(function () {
            return this.value
        }).get();
    })
});

Demo

Note : $output already contains jQuery object.

Sign up to request clarification or add additional context in comments.

Comments

1

Try,

var $output = $('#output-content-here');

$('input').keyup( function() {
    $output.html($('input').map(function(){
        return this.value + ((this.value.length)?"<br>":"");
    }).get().join(''));
});

DEMO

2 Comments

+1 although it should be using keyup, not keypress, otherwise the character from the current event is not shown: jsfiddle.net/A7UbK/7
@RoryMcCrossan yeah was updating it.. Anyway thanks for the encouragement..!
0

As other answers display, you can map the values each time into the div element.

Personally I think a tidier method would be to have 3 elements nested inside the div, 1 for each input, and apply the value directly to each relevant element.

This means you're only updating the field which has been edited, not the entire div html.

Name<input id="name" type="text" name="name" /> <br />
Besked<input id="message" type="text" name="message" /> <br /> 
Number<input id="number" type="text" name="number" /> <br /> 

<div id="output-content-here">
    <span class="name"></span>
    <span class="message"></span>
    <span class="number"></span>
</div>

var $output = $('#output-content-here');

$('input').keyup( function() {    
    $output.find("." + this.id).text(this.value);
});

http://jsfiddle.net/A7UbK/13/

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.