Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

163
Visualizações
Use data-attribute in javascript to alter elements width

I am still new, so please forgive me if this question is too trivial or the issue has already been discussed. I didnt find anything specific, which led me to open a new question. That said, here is how it goes:

Im passing values from my database into data-attributes in order to use them in javascript to alter the width of certain elements (i.e. graphs). The element that should be altered according to the retrieved value is a p-Tag (together with others it sits inside a foreach):

<span class="fdpg-nut-vline"><p class="fdpg-nut-graph" id="graph" data-somedat="<?php echo "'" . $value['Nu_Val'] . "%'" ?>"></p></span>

The value of the data-attribute with the name "somedat" I want to use in js, like so:

var somevar = document.getElementById('graph').getAttribute("data-somedat");
document.getElementById("graph").style.width = somevar;

What I did?

  • I checked whether the format of the value is right. I therefore set a 'static' variable var somevartest = '20%'; and used it in the code above. It worked and the graph changed accordingly.
  • I checked if the value is passed into the data-attribute: (1) in the sourcode (its there!) and afterwards included an alert which shows me the value in the right format aswell (i.e. 'x%').

What is it that Im not getting? How can I solve my problem?

about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

0

The proper way to pass data from PHP to JavaScript is using a JSON string.

PHP:

<?php
$arr = get_from_database_as_array(...);

// at end of page before your scripts:
echo "<script>";
echo "var data = " . json_encode($arr, true) . ";";
echo "</script>";

HTML:

<script>
  console.log(data); 
  document.getElementById("elem1").style.width = data["elem1"] + "px";
  document.getElementById("elem2").style.width = data["elem2"] + "px";
  // and so on.
</script>

about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda