onclick inside append

0

I try to do an onclick on an anchor inside an append and it does not work How can I solve this?

$(function(){


        var weekday= ["Sunday","Monday","Tuesday","Wednesday","Thursday","Friday","Saturday"];
        var months = ["January","February","March","April","May", "June", "July","August","September","October","November","December"];
        var d = new Date();
        var day = d.getDate();
        var month = d.getMonth();
        var year = d.getFullYear();

        function days(month,year) {
          //last day of month
          var lastDay = new Date(year,month + 1, 0).getDate();

          //first day of month
          var a = new Date("1 ,"+months[month]+","+year+"");

          //month string
          $("#date").html(months[month]+" "+year);

          var counter = 0;
          $("#days").html("<tr>");
            for(var i = 1; i < lastDay+1;i++,counter++){

              //blank space
              if(i == 1){
                for(var j = 0; j < a.getDay();j++,counter++){
                  $("#days").append("<td></td>");
                }
              }

              //new week
              if(counter%7 == 0){
                $("#days").append("</tr><tr>");
              }

              //display days
              $("#days").append("<td class='day_active'><a href='' onclick='dayClicked("+i+")'>"+i+"</a></td>");

            }
        };

        //dayClicked
        function dayClicked(day){
          alert("you have clicked day: "+day);
        }


        //left click
        $("#prev").on("click",function(){
          if(month == 0){
            year--;
            month = 12;
          }
          month--;
          days(month,year);
        });

        //right click
        $("#next").on("click",function(){
          if(month == 11 ){
            year++;
            month = -1;
          }
          month++;
          days(month,year);
        });

        days(month,year);

      });
.btn{
  cursor:pointer;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<span class="btn" id="prev">&lang;</span>
<span id="date"></span>
<span class="btn" id="next">&rang;</span>
<table>
    <tr id="weekdays">
      <td>Su</td>
      <td>Mo</td>
      <td>Tu</td>
      <td>We</td>
      <td>Th</td>
      <td>Fr</td>
      <td>Sa</td>
    </tr>
    <tbody id="days"></tbody>
</table>
    
asked by Cristian Hernandez 01.07.2017 в 17:29
source

4 answers

1

the code does not work because the click event is never binned for the anchor tag.

You can take advantage of the use of jquery (since you use it) by using the data- * attribute to assign the value of the day and by clicking on a class defined in the anchor take the value of the data- * attribute to solve your problem

$(function(){
    var weekday= ["Sunday","Monday","Tuesday","Wednesday","Thursday","Friday","Saturday"];
    var months = ["January","February","March","April","May", "June", "July","August","September","October","November","December"];
    var d = new Date();
    var day = d.getDate();
    var month = d.getMonth();
    var year = d.getFullYear();

    function days(month,year) {
      //last day of month
      var lastDay = new Date(year,month + 1, 0).getDate();

      //first day of month
      var a = new Date("1 ,"+months[month]+","+year+"");

      //month string
      $("#date").html(months[month]+" "+year);

      var counter = 0;
      $("#days").html("<tr>");
        for(var i = 1; i < lastDay+1;i++,counter++){

          //blank space
          if(i == 1){
            for(var j = 0; j < a.getDay();j++,counter++){
              $("#days").append("<td></td>");
            }
          }

          //new week
          if(counter%7 == 0){
            $("#days").append("</tr><tr>");
          }

          //display days
          $("#days").append("<td class='day_active'><a class='day-click' data-day="+ i +" href='#'>"+i+"</a></td>");

        }
    };

            //left click
    $("#prev").on("click",function(){
      if(month == 0){
        year--;
        month = 12;
      }
      month--;
      days(month,year);
    });

    //right click
    $("#next").on("click",function(){
      if(month == 11 ){
        year++;
        month = -1;
      }
      month++;
      days(month,year);
    });

    days(month,year);

    //dayClicked
    $('.day-click').click(function(){
      var day = $(this).attr('data-day');
        alert("you have clicked day: "+ day);
    });

  });

the example running HERE

Greetings

    
answered by 01.07.2017 в 18:11
0

What happens is that when defining the function dayClicked in $(function(){}) this can only be used during the execution of this function, once finished, dayClicked is no longer available to the methods onclick in your HTML You just have to put it out of this function, in a global scope and it will work.

$(function(){


        var weekday= ["Sunday","Monday","Tuesday","Wednesday","Thursday","Friday","Saturday"];
        var months = ["January","February","March","April","May", "June", "July","August","September","October","November","December"];
        var d = new Date();
        var day = d.getDate();
        var month = d.getMonth();
        var year = d.getFullYear();

        function days(month,year) {
          //last day of month
          var lastDay = new Date(year,month + 1, 0).getDate();

          //first day of month
          var a = new Date("1 ,"+months[month]+","+year+"");

          //month string
          $("#date").html(months[month]+" "+year);

          var counter = 0;
          $("#days").html("<tr>");
            for(var i = 1; i < lastDay+1;i++,counter++){

              //blank space
              if(i == 1){
                for(var j = 0; j < a.getDay();j++,counter++){
                  $("#days").append("<td></td>");
                }
              }

              //new week
              if(counter%7 == 0){
                $("#days").append("</tr><tr>");
              }

              //display days
              $("#days").append("<td class='day_active'><a href='' onclick='dayClicked("+i+")'>"+i+"</a></td>");

            }
        };

        //left click
        $("#prev").on("click",function(){
          if(month == 0){
            year--;
            month = 12;
          }
          month--;
          days(month,year);
        });

        //right click
        $("#next").on("click",function(){
          if(month == 11 ){
            year++;
            month = -1;
          }
          month++;
          days(month,year);
        });

        days(month,year);

      });
//dayClicked
function dayClicked(day){
  alert("you have clicked day: "+day);
}
.btn{
  cursor:pointer;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<span class="btn" id="prev">&lang;</span>
<span id="date"></span>
<span class="btn" id="next">&rang;</span>
<table>
    <tr id="weekdays">
      <td>Su</td>
      <td>Mo</td>
      <td>Tu</td>
      <td>We</td>
      <td>Th</td>
      <td>Fr</td>
      <td>Sa</td>
    </tr>
    <tbody id="days"></tbody>
</table>
    
answered by 01.07.2017 в 17:48
0

Avoid making an append with html code, it is better to create the elements separately and thus improve the performance of your script, admás you can better manage the events, for example let's see the line where the onclick event fails you

//display days
$("#days").append("<td class='day_active'><a href='' onclick='dayClicked("+i+")'>"+i+"</a></td>");

You should create the TD and the A separately as follows

var td;
var a;
//.....
function days(month,year) {
//....
td = $("<td>").addClass('day_active');

a = $("<a>").html(i).click( 
       //Mandas los parametros dentro de un objeto {param1:'valor' , param2:'valor'....}   
      { day:i }, 
      //Dentro de function los llamas como event.data.param1, event.data.param2, etc...
      function(event){ dayClicked(event.data.day); 
}); //fin del click
//Agregas el A dentro del TD
td.append(a);
//El TD se lo agregas a "#days" que debería ser un TR
$("#days").append(td);
//....
} // fin de days(month,year)

function dayClicked(day){ alert(day); }
    
answered by 03.07.2017 в 19:11
-1

Your problem is that the function dayClicked is not in the global context of the application ( window ) but in the context of the function that groups it.

Then when you click you have the error Uncaught ReferenceError: dayClicked is not defined

Solution

declare the function out of $(funciont() { })

O

declares an anonymous function with reference to the window context.

window.dayClicked = function(day)  {
    alert("you have clicked day: "+day);
}

$(function(){


        var weekday= ["Sunday","Monday","Tuesday","Wednesday","Thursday","Friday","Saturday"];
        var months = ["January","February","March","April","May", "June", "July","August","September","October","November","December"];
        var d = new Date();
        var day = d.getDate();
        var month = d.getMonth();
        var year = d.getFullYear();

        function days(month,year) {
          //last day of month
          var lastDay = new Date(year,month + 1, 0).getDate();

          //first day of month
          var a = new Date("1 ,"+months[month]+","+year+"");

          //month string
          $("#date").html(months[month]+" "+year);

          var counter = 0;
          $("#days").html("<tr>");
            for(var i = 1; i < lastDay+1;i++,counter++){

              //blank space
              if(i == 1){
                for(var j = 0; j < a.getDay();j++,counter++){
                  $("#days").append("<td></td>");
                }
              }

              //new week
              if(counter%7 == 0){
                $("#days").append("</tr><tr>");
              }

              //display days
              $("#days").append("<td class='day_active'><a href='' onclick='dayClicked("+i+")'>"+i+"</a></td>");

            }
        };

        window.dayClicked = function(day)  {
            alert("you have clicked day: "+day);
        }

        //left click
        $("#prev").on("click",function(){
          if(month == 0){
            year--;
            month = 12;
          }
          month--;
          days(month,year);
        });

        //right click
        $("#next").on("click",function(){
          if(month == 11 ){
            year++;
            month = -1;
          }
          month++;
          days(month,year);
        });

        days(month,year);

      });
.btn{
  cursor:pointer;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<span class="btn" id="prev">&lang;</span>
<span id="date"></span>
<span class="btn" id="next">&rang;</span>
<table>
    <tr id="weekdays">
      <td>Su</td>
      <td>Mo</td>
      <td>Tu</td>
      <td>We</td>
      <td>Th</td>
      <td>Fr</td>
      <td>Sa</td>
    </tr>
    <tbody id="days"></tbody>
</table>
    
answered by 01.07.2017 в 17:50