Ali Asger
Ali Asger

Reputation: 63

Passing object as a parameter on an onClick function

I want to pass an object to onclick function as parameter. Then I will call that parameter into the function and push into empty array. But I tried it all, it just push id, name etc. I want to pass laundryValue[i] whole array on onclick="getLaundryClick() as parameter.

    var laundryValue = [
        {id: 1, name: 'Sunglasses', price: 25},
        {id: 2, name: 'Jeans', price: 10},
        {id: 3, name: 'Shirts', price: 15},
        {id: 4, name: 'Cables', price: 20}
    ]
    
    var newLaundryValue = [];

    for (var i in laundryValue) {
        var wrap = laundryValue[i];
        document.getElementById('laundry-value').innerHTML += 
        '<li>' + 
            '<div class="laundry-name">' + laundryValue[i].name + '</div>' + 
            '<div class="laundry-price">' + laundryValue[i].price + '</div>' + 
            '<button class="laundry-btn" onclick="getLaundryClick(' + [wrap] + ')">' + 'Add' + '</button>' +  
        '</li>';
        
    }
    
    function getLaundryClick(wrap) {
        console.log(wrap)
    }

Upvotes: 5

Views: 6481

Answers (6)

Carsten Massmann
Carsten Massmann

Reputation: 28226

The above solutions with JSON.parse() will work. However, you can achieve the same thing with less effort:

const laundryValue = [
        {id: 1, name: 'Sunglasses', price: 25},
        {id: 2, name: 'Jeans', price: 10},
        {id: 3, name: 'Shirts', price: 15},
        {id: 4, name: 'Cables', price: 20} ];
 var newLaundryValue = [];

 document.getElementById('laundry-value').innerHTML = laundryValue.map((wrap,i)=>
        `<li><div class="laundry-name">${wrap.name}</div>
            <div class="laundry-price">${wrap.price}</div>
            <button class="laundry-btn" data-id="${i}">Add</button> 
         </li>`
 ).join('\n');
    
document.onclick=function(ev){ let el=ev.target; // global click handler ...
  if (el.classList.contains('laundry-btn')){let itm=laundryValue[el.dataset.id];
    newLaundryValue.push(itm)
    console.log(`added ${itm.name} to cart.`)
  } else if (el.classList.contains('cart'))
    console.log(JSON.stringify(newLaundryValue)); 
}
li div {display: inline-block; margin:4px 8px}
<div id="laundry-value"></div>
<hr><button class="cart">show cart</button>

Upvotes: 0

sonEtLumiere
sonEtLumiere

Reputation: 4572

You can create a class to create buttons dynamically from an array by this way: You can set the print method inside this class to access any value of any element of your array.

var laundryValue = [
        {id: 1, name: 'Sunglasses', price: 25},
        {id: 2, name: 'Jeans', price: 10},
        {id: 3, name: 'Shirts', price: 15},
        {id: 4, name: 'Cables', price: 20}
];
    
class ButtonToPress {
  constructor(obj) {
    this.obj = obj;

    const button = document.createElement('button');
    button.onclick = this.print.bind(this);
    button.innerText = this.obj.name;

    document.getElementById('laundry-value').appendChild(button);
  }

  print() {
    console.log(this.obj.name, this.obj.price);
  }
}


let buttons = [];
for (let i = 0; i < laundryValue.length; i++) {
  buttons[i] = new ButtonToPress(laundryValue[i]);
}
  <div id="laundry-value"></div>

Upvotes: 0

Praveen RL
Praveen RL

Reputation: 698

Try this, I wrote the complete code. Here I just used the laundaryValue array for looping and stored it in a variable, then binded on html.

<!DOCTYPE html>
<html>
<head>
    <title></title>
</head>
<body>

    <div id="laundry-value"></div>

    <button onclick="getLaundryClick()">Get Laundary</button>

    <script type="text/javascript">

        let  laundryValue = [
        {id: 1, name: 'Sunglasses', price: 25},
        {id: 2, name: 'Jeans', price: 10},
        {id: 3, name: 'Shirts', price: 15},
        {id: 4, name: 'Cables', price: 20}
    ]
    let loopData = '';

    function getLaundryClick(){
        for (let i = 0; i < laundryValue.length; i++) {
            let addObj = JSON.stringify(laundryValue[i]);

            loopData += 
                `
            <ul>
                <li>ID: ${laundryValue[i].id}</li>
                <li>Name: ${laundryValue[i].name}</li>
                <li>Price: ${laundryValue[i].price}</li>
                <li><button onclick='addObjectFunction(${JSON.stringify(laundryValue[i])})'>Add</button></li>
            </ul>
            `;
        }

        document.getElementById('laundry-value').innerHTML = loopData;
    }

    function addObjectFunction(params){
        console.log(params)
    }

    </script>

</body>
</html>

Upvotes: 0

Rohit Tagadiya
Rohit Tagadiya

Reputation: 3738

CASE 1

 var laundryValue = [
        {id: 1, name: 'Sunglasses', price: 25},
        {id: 2, name: 'Jeans', price: 10},
        {id: 3, name: 'Shirts', price: 15},
        {id: 4, name: 'Cables', price: 20}
    ]
    
    var newLaundryValue = [];

    for (var i in laundryValue) {
        var wrap = laundryValue[i];
        var data = JSON.parse(JSON.stringify(wrap));
        document.getElementById('laundry-value').innerHTML += 
        '<li>' + 
            '<div class="laundry-name">' + laundryValue[i].name + '</div>' + 
            '<div class="laundry-price">' + laundryValue[i].price + '</div>' + 
            '<button class="laundry-btn" onclick="getLaundryClick(JSON.parse(\'' 
   + JSON.stringify(wrap).replace(/'/g, '&apos;').replace(/"/g, '&quot;') + '\'))">' 
   + 'Add' + '</button>' +  
        '</li>';
        
    }
    
    function getLaundryClick(wrap) {
        console.log(wrap);
    }
 <div id="laundry-value"></div>

CASE 2

See working example..

var laundryValue = [
        {id: 1, name: 'Sunglasses', price: 25},
        {id: 2, name: 'Jeans', price: 10},
        {id: 3, name: 'Shirts', price: 15},
        {id: 4, name: 'Cables', price: 20}
];
    
class ButtonToPress {
  constructor(obj) {
    this.object = obj;

    const button = document.createElement('button');
    button.onclick = this.print.bind(this);
    button.innerText = this.object.name;

    document.getElementById('laundry-value').appendChild(button);
  }

  print() {
    console.log(this.object);
  }
}


let buttons = [];
for (let i = 0; i < laundryValue.length; i++) {
  buttons[i] = new ButtonToPress(laundryValue[i]);
}
button{
margin: 0 5px;
background: #0095ff;
border:none;
padding: 5px 10px;
border-radius: 5px;
}
<div id="laundry-value"></div>

Upvotes: -1

Karl L
Karl L

Reputation: 1725

Another option is just to play around with single and double quotes PAIR so it would not conflict as we are passing here a quoted string, we need to consider how it is rendered as in it's HTML form:

Working Simplified Version:

var laundryValue = [
        {id: 1, name: 'Sunglasses', price: 25},
        {id: 2, name: 'Jeans', price: 10},
        {id: 3, name: 'Shirts', price: 15},
        {id: 4, name: 'Cables', price: 20}
    ]
    
    var newLaundryValue = [];

    for (var i in laundryValue) {
        var wrap = laundryValue[i];
        
        wrap =  JSON.stringify(wrap)
       
        document.getElementById('laundry-value').innerHTML += 
        '<li>' + 
            '<div class="laundry-name">' + laundryValue[i].name + '</div>' + 
            '<div class="laundry-price">' + laundryValue[i].price + '</div>' + 
            '<button class="laundry-btn" onclick=\'getLaundryClick(' + wrap+' ) \'>' + 'Add' + '</button>' +  
        '</li>';
        
    }
    
    function getLaundryClick(wrap) {
        console.log(wrap)
    }
<div id="laundry-value">

</div>

Upvotes: 0

Unmitigated
Unmitigated

Reputation: 89432

You can use JSON.stringify to convert the object to a string and use JSON.parse in the onclick handler to convert it back.

'<button class="laundry-btn" onclick="getLaundryClick(JSON.parse(\'' 
   + JSON.stringify(wrap).replace(/'/g, '&apos;').replace(/"/g, '&quot;') + '\'))">' 
   + 'Add' + '</button>'

Upvotes: 6

Related Questions