How to concatenate HTML into PHP

Question:

<options += '<option value="' + j[i].CodCidade + '">' + j[i].NomeCidade + '</option>';

I have this code and I want to add one more attribute after the CityName, if anyone can help I appreciate it.

The code is HTML generated by JavaScript.

I have a select cidades and I want to add in the tag option , after the NomeCidade , the ValorTarifa that is received in the same select city ​​through the CodCidade .

The problem is: how to put the ValorTarifa in the same option?

It worked with the example that Baccon posted, thanks to everyone soon I'll be back with more questions.

Answer:

In JS

You can use either concat or + :

 options.concat( '<option value="', j[i].CodCidade, '">',
                 j[i].NomeCidade, ' ', j[i].ValorTarifa, '</option>' );

Concat can be interesting in this case, as you can use it with several parameters, and it has the predictability of being treated as a string. See in operation:

 var options = ''; var i; var j = [ { 'CodCidade':1, 'NomeCidade': 'Taubate' , 'ValorTarifa':'19,90' }, { 'CodCidade':2, 'NomeCidade': 'Campinas', 'ValorTarifa':'25,00' }, { 'CodCidade':3, 'NomeCidade': 'Queluz' , 'ValorTarifa':'46,50' } ]; for ( i = 0; i < 3; i++ ) { options = options.concat( '<option value="', j[i].CodCidade,'">', j[i].NomeCidade, ' ', j[i].ValorTarifa, '</option>' ); } document.body.innerHTML += '<select>' + options + '</select>';

Using += and + also works in this case. You just have to be careful with interpretation problems when mixing numbers and strings.

 var options = ''; var i; var j = [ { 'CodCidade':1, 'NomeCidade': 'Taubate' , 'ValorTarifa':'19,90' }, { 'CodCidade':2, 'NomeCidade': 'Campinas', 'ValorTarifa':'25,00' }, { 'CodCidade':3, 'NomeCidade': 'Queluz' , 'ValorTarifa':'46,50' } ]; for ( i = 0; i < 3; i++ ) { options += '<option value="' + j[i].CodCidade + '">' + j[i].NomeCidade + ' ' + j[i].ValorTarifa + '</option>'; } document.body.innerHTML += '<select>' + options + '</select>';

original answer, before the comments and question update by the author:

In PHP

PHP's concatenation operator is the .

$options .= '<option value="'.$j[$i]['$CodCidade'].'">'.$j[$i]['NomeCidade'].'</option>';

Note that in your example, it was already being used here: j[i].CodCidade , probably by mistake.

Didn't you mean this: j[i]['CodCidade'] or even this: j[i]->CodCidade ? Also, if it's PHP, the prefixes that indicate variable were missing: $j[$i] etc…

Scroll to Top