How to insert variable in html generated by javascript

1

The problem I have is the following. I have a code that generates multiple html results for me. But I need a detail that I could not implement. The code is as follows:

$('#avaliacoes').append('\<div class=\'estrelas\'><input type=\'radio\' id=\'cm_star-empty\' name=\'fb\' value\'\'/>

From another code, I get a result variable from a foreach. Her name is result .Name

The only thing I need is to insert this variable and concatenate with the value of the attribute of the input tag.

How can I do this using append above?

    
asked by anonymous 01.06.2016 / 19:47

2 answers

3

Your HTML has some errors ... but you can do it like this:

var resultado = [{
    Nome: 'Ana'
}, {
    Nome: 'Maria'
}];
var html = resultado.reduce(function(string, pessoa) {
    return string + [
    '<div class=\'estrelas\'><input type=\'radio\' id=\'cm_star-empty\' name=\'fb_', 
    pessoa.Nome, 
    '\' value=\'\'/></div>'
    ].join('');
}, '');
$('#avaliacoes').append(html);

What will happen:

<div class="estrelas"><input type="radio" id="cm_star-empty" name="fb_Ana" value=""></div>
<div class="estrelas"><input type="radio" id="cm_star-empty" name="fb_Maria" value=""></div>

jsFiddle: link

Corrected the lack of = in value and lack of </div> . If you make this string start with quotation marks, instead of quotes, you no longer need to escape HTML.

    
01.06.2016 / 19:56
0

In my opinion, avoid mixing html with javascript ...

var resultado = [{
  Nome: 'Ana'
}, {
  Nome: 'Maria'
}];
var divClone = null;
var children = null
resultado.forEach(function(pessoa) {
  divClone = $('#divClone').clone();
  children = $(divClone).children();
  children[0].name = 'fb_' + pessoa.Nome;
  divClone[0].children = children;
  divClone[0].id = '';
  $(divClone).removeClass('hide');
  $('#avaliacoes').append(divClone);
});
.hide {
  display: none
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.3/jquery.min.js"></script><divid="avaliacoes">
  <div class='estrelas hide' id='divClone'>
    <input type='radio' id='cm_star-empty' name="" value="" />
  </div>
</div>

Follow the example in JSFIDDLE: link

    
01.06.2016 / 20:53