Ir para conteúdo

POWERED BY:

Arquivado

Este tópico foi arquivado e está fechado para novas respostas.

Bruno 33

Criar checkbox em cada dia do mês no calendário

Recommended Posts

Tenho este código que cria o calendário:

 

<script>
var Calendar = function(o) {
  //Store div id
  this.divId = o.ParentID;

  // Days of week, starting on Sunday
  this.DaysOfWeek = o.DaysOfWeek;

  console.log("this.DaysOfWeek == ", this.DaysOfWeek)

  // Months, stating on January
  this.Months = o.Months;

  console.log("this.Months == ", this.Months)

  // Set the current month, year
  var d = new Date();

  console.log("d == ", d)

  this.CurrentMonth = d.getMonth();

  console.log("this.CurrentMonth == ", this.CurrentMonth);

  this.CurrentYear = d.getFullYear();

  console.log("this.CurrentYear == ", this.CurrentYear);

  var f=o.Format;

  console.log("o == ", o);

  console.log("f == ", f);

  //this.f = typeof(f) == 'string' ? f.charAt(0).toUpperCase() : 'M';

  if(typeof(f) == 'string') {
    this.f  = f.charAt(0).toUpperCase();
  } else {
    this.f = 'M';
  }

  console.log("this.f == ", this.f);
};

// Goes to next month
Calendar.prototype.nextMonth = function() {
  console.log("Calendar.prototype.nextMonth = function() {");

  if ( this.CurrentMonth == 11 ) {
    console.log("this.CurrentMonth == ", this.CurrentMonth);

    this.CurrentMonth = 0;

    console.log("this.CurrentMonth == ", this.CurrentMonth);

    console.log("this.CurrentYear == ", this.CurrentYear);

    this.CurrentYear = this.CurrentYear + 1;

    console.log("this.CurrentYear == ", this.CurrentYear);
  } else {
    console.log("this.CurrentMonth == ", this.CurrentMonth);

    this.CurrentMonth = this.CurrentMonth + 1;

    console.log("this.CurrentMonth + 1 == ", this.CurrentMonth);
  }

  this.showCurrent();
};

// Goes to previous month
Calendar.prototype.previousMonth = function() {
  console.log("Calendar.prototype.previousMonth = function() {");

  if ( this.CurrentMonth == 0 ) {
    console.log("this.CurrentMonth == ", this.CurrentMonth);

    this.CurrentMonth = 11;

    console.log("this.CurrentMonth == ", this.CurrentMonth);

    console.log("this.CurrentYear == ", this.CurrentYear);

    this.CurrentYear = this.CurrentYear - 1;

    console.log("this.CurrentYear == ", this.CurrentYear);
  } else {
    console.log("this.CurrentMonth == ", this.CurrentMonth);

    this.CurrentMonth = this.CurrentMonth - 1;

    console.log("this.CurrentMonth - 1 == ", this.CurrentMonth);
  }

  this.showCurrent();
};

// 
Calendar.prototype.previousYear = function() {
  console.log(" ");

  console.log("Calendar.prototype.previousYear = function() {");

  console.log("this.CurrentYear == " + this.CurrentYear);

  this.CurrentYear = this.CurrentYear - 1;

  console.log("this.CurrentYear - 1 i.e. this.CurrentYear == " + this.CurrentYear);

  this.showCurrent();
}

// 
Calendar.prototype.nextYear = function() {
  console.log(" ");

  console.log("Calendar.prototype.nextYear = function() {");

  console.log("this.CurrentYear == " + this.CurrentYear);

  this.CurrentYear = this.CurrentYear + 1;

  console.log("this.CurrentYear - 1 i.e. this.CurrentYear == " + this.CurrentYear);

  this.showCurrent();
}              

// Show current month
Calendar.prototype.showCurrent = function() {
  console.log(" ");

  console.log("Calendar.prototype.showCurrent = function() {");

  console.log("this.CurrentYear == ", this.CurrentYear);

  console.log("this.CurrentMonth == ", this.CurrentMonth);

  this.Calendar(this.CurrentYear, this.CurrentMonth);
};

// Show month (year, month)
Calendar.prototype.Calendar = function(y,m) {
  console.log(" ");

  console.log("Calendar.prototype.Calendar = function(y,m){");

  typeof(y) == 'number' ? this.CurrentYear = y : null;

  console.log("this.CurrentYear == ", this.CurrentYear);

  typeof(y) == 'number' ? this.CurrentMonth = m : null;

  console.log("this.CurrentMonth == ", this.CurrentMonth);

  // 1st day of the selected month
  var firstDayOfCurrentMonth = new Date(y, m, 1).getDay();

  console.log("firstDayOfCurrentMonth == ", firstDayOfCurrentMonth);

  // Last date of the selected month
  var lastDateOfCurrentMonth = new Date(y, m+1, 0).getDate();

  console.log("lastDateOfCurrentMonth == ", lastDateOfCurrentMonth);

  // Last day of the previous month
  console.log("m == ", m);

  var lastDateOfLastMonth = m == 0 ? new Date(y-1, 11, 0).getDate() : new Date(y, m, 0).getDate();

  console.log("lastDateOfLastMonth == ", lastDateOfLastMonth);

  console.log("Print selected month and year.");

  // Write selected month and year. This HTML goes into <div id="year"></div>
  //var yearhtml = '<span class="yearspan">' + y + '</span>';

  // Write selected month and year. This HTML goes into <div id="month"></div>
  //var monthhtml = '<span class="monthspan">' + this.Months[m] + '</span>';

  // Write selected month and year. This HTML goes into <div id="month"></div>
  var monthandyearhtml = '<span id="monthandyearspan">' + this.Months[m] + ' - ' + y + '</span>';

  console.log("monthandyearhtml == " + monthandyearhtml);

  var html = '<table>';

  // Write the header of the days of the week
  html += '<tr>';

  console.log(" ");

  console.log("Write the header of the days of the week");

  for(var i=0; i < 7;i++) {
    console.log("i == ", i);

    console.log("this.DaysOfWeek[i] == ", this.DaysOfWeek[i]);

    html += '<th class="daysheader">' + this.DaysOfWeek[i] + '</th>';
  }

  html += '</tr>';

  console.log("Before conditional operator this.f == ", this.f);

  //this.f = 'X';

  var p = dm = this.f == 'M' ? 1 : firstDayOfCurrentMonth == 0 ? -5 : 2;

  /*var p, dm;

  if(this.f =='M') {
    dm = 1;

    p = dm;
  } else {
    if(firstDayOfCurrentMonth == 0) {
      firstDayOfCurrentMonth == -5;
    } else {
      firstDayOfCurrentMonth == 2;
    }
  }*/

  console.log("After conditional operator");

  console.log("this.f == ", this.f);

  console.log("p == ", p);

  console.log("dm == ", dm);

  console.log("firstDayOfCurrentMonth == ", firstDayOfCurrentMonth);

  var cellvalue;

  for (var d, i=0, z0=0; z0<6; z0++) {
    html += '<tr>';

    console.log("Inside 1st for loop - d == " + d + " | i == " + i + " | z0 == " + z0);

    for (var z0a = 0; z0a < 7; z0a++) {
      console.log("Inside 2nd for loop");

      console.log("z0a == " + z0a);

      d = i + dm - firstDayOfCurrentMonth;

      console.log("d outside if statm == " + d);

      // Dates from prev month
      if (d < 1){
        console.log("d < 1");

        console.log("p before p++ == " + p);

        cellvalue = lastDateOfLastMonth - firstDayOfCurrentMonth + p++;

        console.log("p after p++ == " + p);

        console.log("cellvalue == " + cellvalue);

        html += '<td id="prevmonthdates">' + 
              '<span id="cellvaluespan">' + (cellvalue) + '</span><br/>' 
              
            '</td>';

      // Dates from next month
      } else if ( d > lastDateOfCurrentMonth){
        console.log("d > lastDateOfCurrentMonth");

        console.log("p before p++ == " + p);

        html += '<td id="nextmonthdates">' + (p++) + '</td>';

        console.log("p after p++ == " + p);

      // Current month dates
      } else {
        html += '<td id="currentmonthdates">' + (d) + '</td>';
        
        console.log("d inside else { == " + d);

        p = 1;

        console.log("p inside } else { == " + p);
      }
      
      if (i % 7 == 6 && d >= lastDateOfCurrentMonth) {
        console.log("INSIDE if (i % 7 == 6 && d >= lastDateOfCurrentMonth) {");

        console.log("i == " + i);

        console.log("d == " + d);

        console.log("z0 == " + z0);

        z0 = 10; // no more rows
      }

      console.log("i before i++ == " + i);

      i++;

      console.log("i after i++ == " + i);            
    }

    html += '</tr>';
  }

  // Closes table
  html += '</table>';

  // Write HTML to the div
  //document.getElementById("year").innerHTML = yearhtml;

  //document.getElementById("month").innerHTML = monthhtml;

  document.getElementById("monthandyear").innerHTML = monthandyearhtml;

  document.getElementById(this.divId).innerHTML = html;
};

// On Load of the window
window.onload = function() {
  
  // Start calendar
  var c = new Calendar({
    ParentID:"divcalendartable",

    DaysOfWeek:[
    'Segunda',
    'Terça',
    'Quarta',
    'Quinta',
    'Sexta',
    'Sábado',
    'Domingo'
    ],

    Months:['Janeiro', 'Fevereiro', 'Março', 'Abril', 'Maio', 'Junho', 'Julho', 'Agosto', 'Setembro', 'Outubro', 'Novembro', 'Dezembro' ],

    Format:'dd/mm/yyyy'
  });
  

  c.showCurrent();
  
  // Bind next and previous button clicks
  getId('btnPrev').onclick = function(){
    c.previousMonth();
  };

  getId('btnPrevYr').onclick = function(){
    c.previousYear();
  };

  getId('btnNext').onclick = function(){
    c.nextMonth();
  };

  getId('btnNextYr').onclick = function(){
    c.nextYear();
  };                        
}

// Get element by id
function getId(id) {
  return document.getElementById(id);
}
</script>

 

Mostro o resultado na imagem:

 

teste.thumb.png.5647382405700235b35b87657d67e00c.png

 

Pretendo agora criar 4 checkbox em cada dia do mês no calendário e inserir numa tabela da base de dados. Alguém tem uma ideia como o posso fazer? Também mostro o que pretendo na imagem abaixo:

1122111.thumb.png.76be1d4c7024a4fd6ed46e7ae4a49810.png

Compartilhar este post


Link para o post
Compartilhar em outros sites

Movido: PHP -> HTML e CSS.

 

Apesar de construir seu calendário com JavaScript, sua dúvida parece ser HTML.

Compartilhar este post


Link para o post
Compartilhar em outros sites
13 horas atrás, Maujor disse:

Poste a marcação HTML

Só tenho esse código... onde criar o calendário como mostro na imagem. Agora dentro desse código pretendia criar as checkbox e colocar  a inserir numa tabela da base de dados

Compartilhar este post


Link para o post
Compartilhar em outros sites

  • Conteúdo Similar

    • Por daemon
      Boa tarde,
       
      Eu tenho uma rotina que faz uma leitura do arquivo .xml de vários sites.

      Eu consigo pegar o tópico e a descrição, e mostrar a imagem que esta na pagina do link.
      Para isso utilizo esta função:
      function getPreviewImage($url) { // Obter o conteúdo da página $html = file_get_contents($url); // Criar um novo objeto DOMDocument $doc = new DOMDocument(); @$doc->loadHTML($html); // Procurar pela tag meta og:image $tags = $doc->getElementsByTagName('meta'); foreach ($tags as $tag) { if ($tag->getAttribute('property') == 'og:image') { return $tag->getAttribute('content'); } } // Se não encontrar og:image, procurar pela primeira imagem na página $tags = $doc->getElementsByTagName('img'); if ($tags->length > 0) { return $tags->item(0)->getAttribute('src'); } // Se não encontrar nenhuma imagem, retornar null return null; } // Uso: $url = "https://example.com/article"; $imageUrl = getPreviewImage($url); if ($imageUrl) { echo "<img src='$imageUrl' alt='Preview'>"; } else { echo "Nenhuma imagem encontrada"; }  
      Mas estou com um problema, esta funcão funciona quando coloco em uma pagina de teste.php. Preciso mostrar em uma página inicial diversas fotos de todos os links. (No caso acima só funciona 1).
    • Por violin101
      Caros amigos, saudações.
       
      Por favor, me permita tirar uma dúvida com os amigos.

      Tenho um Formulário onde o Usuário digita todos os Dados necessários.

      Minha dúvida:
      --> como faço após o usuário digitar os dados e salvar, o Sistema chamar uma Modal ou mensagem perguntando se deseja imprimir agora ?

      Grato,
       
      Cesar
    • Por Carcleo
      Tenho uma abela de usuarios e uma tabela de administradores e clientes.
      Gostaria de uma ajuda para implementar um cadastro
       
      users -> name, login, passord (pronta) admins -> user_id, registratiom, etc.. client -> user_id, registratiom, etc...
      Queria ajuda para extender de user as classes Admin e Client
      Olhem como estáAdmin
      <?php namespace App\Models; use Illuminate\Database\Eloquent\Factories\HasFactory; use Illuminate\Database\Eloquent\Model; class Admin extends User {     use HasFactory;            protected $fillable = [         'name',         'email',         'password',         'registration'     ];      private string $registration;     public function create(         string $name,          string $email,          string $password,         string $registration     )     {         //parent::create(['name'=>$name, 'email'=>$email, 'password'=>$password]);         parent::$name = $name;         parent::$email = $email;         parent::$password = $password;         $this->registration = $registration;     } } User
      <?php namespace App\Models; // use Illuminate\Contracts\Auth\MustVerifyEmail; use Illuminate\Database\Eloquent\Factories\HasFactory; use Illuminate\Foundation\Auth\User as Authenticatable; use Illuminate\Notifications\Notifiable; use Illuminate\Database\Eloquent\Relations\BelongsToMany; class User extends Authenticatable {     /** @use HasFactory<\Database\Factories\UserFactory> */     use HasFactory, Notifiable;     static string $name;     static string $email;     static string $password;     /**      * The attributes that are mass assignable.      *      * @var list<string>      */     protected $fillable = [         'name',         'email',         'password',     ];          /**      * The attributes that should be hidden for serialization.      *      * @var list<string>      */     protected $hidden = [         'remember_token',     ];     /**      * Get the attributes that should be cast.      *      * @return array<string, string>      */     protected function casts(): array     {         return [             'email_verified_at' => 'datetime',             'password' => 'hashed',         ];     }          public function roles() : BelongsToMany {         return $this->belongsToMany(Role::class);     }       public function hasHole(Array $roleName): bool     {                 foreach ($this->roles as $role) {             if ($role->name === $roleName) {                 return true;             }         }         return false;     }         public function hasHoles(Array $rolesName): bool     {                 foreach ($this->roles as $role) {             foreach ($rolesName as $rolee) {             if ($role->name === $rolee) {                 return true;             }          }         }         return false;     }         public function hasAbility(string $ability): bool     {         foreach ($this->roles as $role) {             if ($role->abilities->contains('name', $ability)) {                 return true;             }         }         return false;     }     } Como gravar um Admin na tabela admins sendo que ele é um User por extensão?
      Tentei assim mas é claro que está errado...
      public function store(Request $request, Admin $adminModel) {         $dados = $request->validate([             "name" => "required",             "email" => "required|email",             "password" => "required",             "registration" => "required"         ]);         $dados["password"] =  Hash::make($dados["password"]);                  $admin = Admin::where("registration",  $dados["registration"])->first();                  if ($admin)              return                    redirect()->route("admin.new")                             ->withErrors([                                 'fail' => 'Administrador já cadastrados<br>, favor verificar!'                   ]);                            $newAdmin = $adminModel->create(                                    $dados['name'],                                    $dados['email'],                                    $dados['password'],                                    $dados['registration']                                 );         dd($newAdmin);         $adminModel->save();         //$adminModel::create($admin);                  return redirect()->route("admin.new")->with("success",'Cadastrado com sucesso');     }  
    • Por violin101
      Caros amigos, saudações.
       
      Gostaria de tirar uma dúvida com os amigos, referente a PDV.
       
      Estou escrevendo um Sistema com Ponto de Vendas, a minha dúvida é o seguinte, referente ao procedimento mais correto.

      Conforme o caixa vai efetuando a venda, o Sistema de PDV já realiza:
      a baixa direto dos produtos no estoque
      ou
      somente após concretizar a venda o sistema baixa os produtos do estoque ?
       
      Grato,
       
      Cesar
       
    • Por violin101
      Caros amigos do grupo, saudações e um feliz 2025.
       
      Estou com uma pequena dúvida referente a Teclas de Atalho.

      Quando o Caps Lock está ativado o Comando da Tecla de Atalho não funciona.
      ou seja:
      se estiver para letra minúscula ====> funciona
      se estiver para letra maiúscula ====> não funciona
       
      Como consigo evitar essa falha, tanto para Letra Maiúscula quanto Minúscula ?

      o Código está assim:
      document.addEventListener( 'keydown', evt => { if (!evt.ctrlKey || evt.key !== 'r' ) return;// Não é Ctrl+r, portanto interrompemos o script evt.preventDefault(); });  
      Grato,
       
      Cesar
×

Informação importante

Ao usar o fórum, você concorda com nossos Termos e condições.