Home > Back-end >  Unable to use html code in javascript tag
Unable to use html code in javascript tag

Time:10-10

I am working with Javascript and jquery,Actually i am getting response as javascript variable and i want to use html (star rating) according to rating but whenever i try to use html code in javascript my "<td>" showing blank,Here is my code,Where i am wrong ?

function createTable(result,sno){
          sno = Number(sno);
       $('#postsList tbody').empty();
       for(index in result){
          var rating = result[index].average_rating; // getting rating(between 1 to 5)  
          if(rating=="0")
          {
              var rating ="<div class='stars>";
                "<span class='fa fa-star'></span>"; 
               "<span class='fa fa-star'></span>";
                "<span class='fa fa-star'></span>";
                "<span class='fa fa-star'></span>";
                "<span class='fa fa-star'></span>";
              "</div>";
          }
          if(rating=="1")
          {
             .....
          }
          and so on...
          
          var tr = "<tr>";
          tr  = "<td>"  sno  "</td>";
           tr  = "<td>"  rating  "</td>";
          tr  = "</tr>";
          $('#postsList tbody').append(tr); 
}
      }
});
 </script>

CodePudding user response:

Your code

var rating ="<div class='stars>";
                "<span class='fa fa-star'></span>"; 
               "<span class='fa fa-star'></span>";
                "<span class='fa fa-star'></span>";
                "<span class='fa fa-star'></span>";
                "<span class='fa fa-star'></span>";
              "</div>";

literally only sets your rating var to <div class='stars>. Change it to:

var rating ="<div class='stars'>";
rating  = "<span class='fa fa-star'></span>"; 
rating  = "<span class='fa fa-star'></span>";
rating  = "<span class='fa fa-star'></span>";
rating  = "<span class='fa fa-star'></span>";
rating  = "<span class='fa fa-star'></span>";
rating  = "</div>";

to also add the <span>s and the closing </div>.

It might also be a good idea to name that rating to something like ratingDiv to not overwrite your actual rating value.

Edit: also added a missing closing ' to <div class='stars'>

CodePudding user response:

you have did some mistake in your code. you should do like this.

var rating = "<div class='stars'>"   
"<span class='fa fa-star'></span>"  
"<span class='fa fa-star'></span>"   
"<span class='fa fa-star'></span>"  
"<span class='fa fa-star'></span>"  
"<span class='fa fa-star'></span>"  
"</div>";

  • Related