Thiago Vinic
Thiago Vinic

Reputation: 15

how to clone div value to input

I need to copy a value from a "Div" to an "input" by clicking the button.

the function is copying the whole div html value, contrary to what i need, i want to copy only the text.

view example: https://jsfiddle.net/fg79vypb/

$('#copy').on('click', function() {
      $('#message').val($('<div/>').append($('#whatsapp').clone()).html());
    });
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

    <button id="copy">Get order on WhatsApp</button>
    <div id="whatsapp" style="    position: fixed;     width: 200px;     height: auto;     bottom: 40px;     right: 40px;     background-color: #e0ffe7;     border-radius: 10px; padding-left: 10px;     border-top-width: 10px;     padding-top: 10px;     padding-bottom: 10px;"><span class="simpleCart_total">R$ 18.00</span> (<span class="simpleCart_quantity" id="simpleCart_quantity">1</span> items)
     <br><br>
    <div class="simpleCart_items"><div class="cartHeaders"><div class="itemName">Name</div><div class="itemPrice">Price</div><div class="itemQuantity">Quantity</div><div class="item"></div></div><div class="itemContainer"><div class="itemName">Product name 1</div><div class="itemPrice">R$ 18.00</div><div class="itemQuantity">1</div><div class="item"> </div></div></div>
    <a class="simpleCart_empty" href="javascript:;">clean cart</a>
    <br><br>
    <a class="simpleCart_checkout" href="javascript:;">go to checkout</a></div>
    <input id="message" type="text" >

I would like to get only the text value, and is displaying all html code.

Upvotes: 0

Views: 247

Answers (2)

Ryan Wilson
Ryan Wilson

Reputation: 10765

Here is an example of how to capture all item names and their prices and place them into an array using JQuery. You can then decide what you want to do with them from there:

let items = []; //Declare an array which will hold all items selected by user
let valueForTextbox = "";
//Iterate each name and grab it's corresponding price:
$('.itemName').each(function(){
   //Check for the header row, so we don't place titles into the array
   if($(this).text() !== 'Name'){
       items.push({ ItemName: $(this).text(), ItemPrice: $(this).next('.itemPrice').text() });
   }
});

 //Display each item's name and price
 items.forEach(function(item){
   //Concat the item names and item prices
   valueForTextbox += item.ItemName + " " + item.ItemPrice + " ");
});

 //Set the textbox value
 $('#message').val(valueForTextbox);
 //You can then format each item to whatever you need from here

Upvotes: 0

William Gunawan
William Gunawan

Reputation: 750

This code will do what you want. Just copy text not html code

$('#copy').on('click', function() { 
  $('#message').val($('#whatsapp').text());
});

Upvotes: 1

Related Questions