How to concatenate a string and an integer value in javascript?

Asked

Viewed 1,522 times

2

Well, I have 15 similar lines in my code and the only thing that changes is the id of the elements that end in an increasing and different integer...

I tried to replace these lines using a loop, but every time I try to run the code nothing happens. I used the console.log and the variable is normal. But still print an error message saying that style cannot be set on a null element: Uncaught TypeError: Cannot read property 'style' of null

`

    <script>
    function showSeason(obj) {

        /*document.getElementById('episodes_temp1').style.display="none";
        document.getElementById('episodes_temp2').style.display="none";
        document.getElementById('episodes_temp3').style.display="none";
        document.getElementById('episodes_temp4').style.display="none";*/

        for(i = 1; i < 5; i++) {
            document.getElementById('episodes_temp' + i).style.display="none";
        }


        //essa parte eu tbm queria por em um loop, mas nao tenho ideia de como fazer
        //como serao diversos itens criar 50 cases nao seria uma boa escolha :(
        switch (obj.id) {
          case 'temporada_1':
          document.getElementById('episodes_temp1').style.display="block";
          break
          case 'temporada_2':
          document.getElementById('episodes_temp2').style.display="block";
          break
          case 'temporada_3':
          document.getElementById('episodes_temp3').style.display="block";
          break
          case 'temporada_4':
          document.getElementById('episodes_temp4').style.display="block";
          break
        }
    }

    </script>
</head>

<body>
    <?php

        echo "<p></p>";
        for($i = 1; $i < 5; $i++) {
            echo "<button type='button' id='temporada_$i' onclick='showSeason(this)'> Temporada $i </button>";
        }                           

        for($x = 1; $x < 5; $x++) {
            echo "<div id='episodes_temp$x' style='display:none;'>";
                for($i = 1; $i < 50; $i++) { //50 é um valor de teste, pretendo puxar do banco da dados;
                    echo "item $i";
                }   
            echo "</div>";
        }                                                       

    ?>
</body>

` I think I could tbm replace the swith by:

for(i = 1; i < 5; i++) { if("temporada_" + i == obj.id) { document.getElementById('episodes_temp' + i).style.display="block"; break; } }

  • 2

    This happens because in fact you do not have in DOM any element with ids 'divAba' + i, you can be sure, review this. Also, it would be appropriate to post the part of your HTML, after all we can not guess the rest of your code.

  • @felipsmartins, in fact to the getElementById is a function, which takes as an argument a string, and at the time of concatenation, the argument is returned with the i, no problem. As you can see in this example: https://jsfiddle.net/SamirChaves/xcxj3skp/ . I think the problem is the rest of the code.

  • 2

    @Samirbraga I understood what he is trying to do. And that is precisely why his question is missing details. The error message Cannot read property is precisely because of getElementById returns null for not finding in DOM an element with the ID you are looking for. - By the way, I am also from Fortaleza.

  • First person around here I see around here... rsrs... Yeah, I agree, waiting for new details Naine...

  • @Naine, where is this script? It may be being loaded before the element in question. Try to place it at the end of your document, so it will be loaded after all elements have been redeveloped.

  • i edited the post and put the link to the code I’m using I used the pq Pastebin I thought it got too big for here :( http://pastebin.com/bB26SDEK

Show 1 more comment

1 answer

2


From what I saw in your code, the problem is in the structuring:

Your script has a function that, at least to what you have shown, is declared but is not called. Possible solutions:

Add function to attribute onload of body:

 <body onload="mostrar_abas(obj)" >

Use the method window.onload

window.onload = mostrar_abas;

or

window.onload = function(){
    //conteúdo da função aqui
}

Or move the tag script of your head and put it at the end of body, so it will be loaded after all elements have been rendered.

As your function has as argument an object, you will do the same thing but specifying it;

In your case you have elemtnos that are created dynamicamento, I am, be it the time of your rederization in the DOM will be different from the others, including the loading of scripts. What I recommend to you:

Call off attribute function onclick and use Jquery, like this:

Simplest Mode WITH JQUERY - Update

Add a class to all Buttons who have a id='temporada_$i' such as, for example, class="temporadas", and add a class to all divs with id of episodes such as, for example, class="episodes". This will be very simple, since you are using the loop. So your code can come down to this:

$(document).on('click', '.temporadas', function() {
  $('.episodes').hide(); //Esconde todos as div de episódios
  var idNum = $(this).attr('id').match(/[0-9]+$/);// captura o número do botão que foi clicado
  $('#episodes_temp'+idNum).show(); //mostra somente o  div de episódios correspondente ao botão
})

In the above function the event is passed to the document and the elemnto in question is specified only after it is dynamically created.

  • http://pastebin.com/BEBsG3Kx is about that. I apologize if my code is outside the standards I really don’t know how I’m doing, it’s my first attempt at making a website, I was thrown that challenge and I entered that last week, knowing nothing of web programming -'

  • 1

    @Naine, you don’t have to apologize, trying is what leads us to learn ;). I imagine now you know what the problem is, I’ll take one more look and let you know...

  • 2

    @Naine Did you link jquery? If not, just add it to your head: <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>

  • 1

    Running the same function via console (F12) occurs as expected? Copy and paste on the console and click on such button.

  • 1

    @Naine Look here: http://pastebin.com/jktwFaL6

Browser other questions tagged

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