How to insert a javascript generated html variable

Asked

Viewed 298 times

1

The problem I have is this. I have a code that generates several html results for me. I just need a detail I couldn’t 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 variable resulting from a foreach. Its name is result[i]. Name

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

How can I do this using the append above?

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);

that will give:

<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: https://jsfiddle.net/d9fycaz2/1

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

  • 1

    All right, vlw Sergio!

  • 1

    @Great dichrist. Now when I looked at the answer again I modified it by another way I like it even more. So it won’t call $('#avaliacoes') times more needlessly.

  • @Sergio O return + [..., what it does for sure. I can’t test it now but I’m curious

  • @Miguel the function Array.reduce needs the callback to return. On this line I am returning the string accumulated with the new one that builds it with an Aray and a .join('') at the end to concatenate.

0

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

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>
<div id="avaliacoes">
  <div class='estrelas hide' id='divClone'>
    <input type='radio' id='cm_star-empty' name="" value="" />
  </div>
</div>

Follow the example in JSFIDDLE : https://jsfiddle.net/d9fycaz2/7/

Browser other questions tagged

You are not signed in. Login or sign up in order to post.