Aadhavan G S
Aadhavan G S

Reputation: 95

Copy the value of 2 divs to a single output div

I have two text boxes, one has an id and the other has a class. I need to copy the values in both of the text boxes to a single div when the button is clicked. I have attempted this but only the second box's value is copied.

HTML

<input type="text" id="test1" value="Hello World"/>
<input type="text" class="test2" value="Hello World Jquery"/>
<input type="submit" value="Select" id="button"/>
<div id="output"></div>

Javascript

$(document).ready(function(){   
    $('#button').click(function(){
        $('#output').text($("#test1").val());   //assigns value to your div
        $('#output').text($(".test2").val());
    });   
});

Upvotes: 2

Views: 72

Answers (4)

Nishith Kant Chaturvedi
Nishith Kant Chaturvedi

Reputation: 4769

Value placed in div by clicking on button places test1 's value on div but replaced by next value (".test2").val();

use this fiddle

$(document).ready(function(){   
$('#button').click(function(){
$('#output').text($("#test1").val()+$(".test2").val());    

});   
});

Upvotes: 0

JGV
JGV

Reputation: 5187

Here is a possible solution:

You can use the append functionality in jquery as shown below,

$(document).ready(function(){   
$('#button').click(function(){
    var output = $('#output');
    output.empty();
    output.append($("#test1").val());   //assigns value to your div
    output.append($(".test2").val());
});   
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" id="test1" value="Hello World"/>
<input type="text" class="test2" value="Hello World Jquery"/>
<input type="submit" value="Select" id="button"/>
<div id="output"></div>

Upvotes: 1

Ayush
Ayush

Reputation: 311

jQuery text overwrites the value everytime you use it. So a solution is to store the value in some variable first and then write it

$(document).ready(function(){
    $('#button').click(function(){ 
        var value = $("#test1").val() + $(".test2").val();
        $('#output').text(value); //assigns value to your div 
    });
});

Upvotes: 3

guradio
guradio

Reputation: 15555

Demo

$(document).ready(function () {
    $('#button').click(function () {
        $('#output').text($("#test1").val()+$(".test2").val()); //assigns value to your div

    });
});

In your code you are reassigning again the value of the div that is why only one is showing combine them by using + so both value will appear

Upvotes: 1

Related Questions