Passing value of a variable in Array?

0

I have the following variable:

var prodadicional = $(this).attr('data-adicionais');

It returns two string values that are: Hamburger and Bacon. How do I place them within a array ?

I tried to pass inside array and count with length but only returns value 1, being that it has two values.

var dadosarrayAdicional = [prodadicional];
var teste = prodadicional.length;
    
asked by anonymous 14.07.2017 / 15:27

1 answer

1
Se está vindo como string você pode fazer de dois jeitos que são a mesma coisa:

$('.btn-comida').on('click',function(){
  var prodadicional = $(this).data('adicionais').split(' e ');
  $('#total').val(prodadicional.length);
  var ul = $('ul');
  ul.append('<li>'+prodadicional[0]+'</li>');
  ul.append('<li>'+prodadicional[1]+'</li>');
  
})
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet"/>
<script src="https://code.jquery.com/jquery-3.2.1.js"></script><divclass="form-group">
 
  <button class="btn btn-primary btn-comida" data-adicionais="Hambúrguer e Bacon">Hambúrguer e Bacon</button>  
</div>

<div class="form-group">
  <label for="total">Total de itens</label>
  <input class="form-control col-lg-1" id="total"> 
</div>



<ul>
</ul>
  

Or

$('.btn-comida').on('click', function(){
  var prodadicional = $(this).data('adicionais').split(' e ');
  $('#total').val(prodadicional.length);
  $.each(prodadicional, function(i, prod){
     
      var li = "<li>"+ prodadicional[i] + '</li>';
      $('ul').append(li);
  })
})
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet"/>
<script src="https://code.jquery.com/jquery-3.2.1.js"></script><divclass="form-group">
 
  <button class="btn btn-primary btn-comida" data-adicionais="Hambúrguer e Bacon">Hambúrguer e Bacon</button>
</div>
<div class="form-group">
  <label for="total">Total de itens</label>
  <input class="form-control col-lg-1" id="total"> 
</div>
<ul>
</ul>
    
14.07.2017 / 16:00