Showing posts with label jQuery. Show all posts
Showing posts with label jQuery. Show all posts

Localize jQuery Validate

May 20, 2015
Here is a code snippet on how to localize the custom error messages for the jQuery Validation Plugin, assuming I have already imported the proper libraries.

I have created a separate function in my script to set the proper error messages.

function addCustomMessages(){
    $("#inputName").rules("add", {
        messages: {
            required: errorRequired,
            minlength: errorMinLength
        }
    });
}

where errorRequired and errorMinLength are global variables that holds the localized messages.

The function will be called every time the language is changed.

$("#languageSelector").change(function(){
 // code here to get the translations
 addCustomMessages(); // code that will load the messages for the jQuery validation plugin
});

Works like magic. :)

I'll try to add a fiddle next time to further clarify.

Other helpful links:


Read more ...

JQuery: Send Post Data and Redirect

Mar 2, 2015
Basically, what I wanted to do is to send data from one page to another page.
Apparently, I don't have any form to submit and I don't want it to appear on the URL, either.

Here's one simple solution:


var form = $("<form action='" + url + '' method='post'>" +
  "       <input type='hidden' name='id' id='id' value='" + id + "'/>" +
  "       <input type='hidden' name='username' id='username' value='" + username + "'/>" +
  "</form>");
$('body').append(form);
form.submit();


where id and username are variables holding the data you want to send to another page, and url is the page you want to pass the data to.

Any other alternate solution?

Please feel free to leave your message on the comments section.

Read more ...

Bootstrap: Modal Dialog Box

Sep 12, 2014
I had a post before about how to create a modal dialog box using native CSS and Javascript (no libraries).

This time, I will make one using Bootstrap.

Required:

You may download the files or just place the following code inside your <head> tag.

<script src="//ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<link href="//maxcdn.bootstrapcdn.com/bootstrap/3.2.0/css/bootstrap.min.css" rel="stylesheet">
<script src="//maxcdn.bootstrapcdn.com/bootstrap/3.2.0/js/bootstrap.min.js"></script>

Next, we create our modal dialog box.

<div class="modal fade" id="modalDialog" role="dialog">
  <div class="modal-dialog">
 <div class="modal-content">
   <div class="modal-header">
  <button type="button" class="close" data-dismiss="modal"><span aria-hidden="true">&times;</span><span class="sr-only">Close</span></button>
  <h4 class="modal-title">[Modal title]</h4>
   </div>
   <div class="modal-body">
  <h1>[Modal Body]</h1>
  <p>Lorem ipsum dolor</p>
  <a href="">Lorem ipsum dolor</a>
  <ul>
   <li>Lorem ipsum dolor</li>
   <li>Lorem ipsum dolor</li>
  </ul>
  <ol>
   <li>Lorem ipsum dolor</li>
   <li>Lorem ipsum dolor</li>
  </ol>
   </div>
   <div class="modal-footer">
  <button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
  <button type="button" class="btn btn-primary">Save</button>
   </div>
 </div>
  </div>
</div>

We then create the button that would allow the modal to appear.

<button class="btn btn-primary btn-lg" data-toggle="modal" data-target="#modalDialog">
 Show Modal
</button>

FIDDLE

Did this work for you?
Any better solutions?

Please feel free to drop a message on the comments section.
Read more ...

jQuery: Start Date and End Date

Aug 21, 2014
We commonly see on websites some input fields that would require us to enter a date range.
This means we should be able to select a start date and end date.
Of course, start date should always be before the end date and the end date should always be later than the start date.

Being a Tech Noob, I have no idea how to do this, especially since web programming isn't really my forte.

Fortunately, a lot of helpful tips can be found online!
Here's one.

We need the following:

  1. jQuery Library
  2. jQuery UI
  3. jQuery CSS
HTML

<input type="text" id="start_date">
<input type="text" id="end_date">

Javascript



$(function() {
 $("#start_date").datepicker({
  onSelect: function(selected){
   $("#end_date").datepicker("option","minDate", selected)
        }

 });
 $("#end_date").datepicker({
  onSelect: function(selected) {
   $("#start_date").datepicker("option","maxDate", selected)
        }

 });
});

FIDDLE

Let me know if you have other better ways in mind. (:
Read more ...

jQuery: Simple Click Game with Interval

Mar 12, 2014
Here's another simple game using HTML5 and Javascript.

The following are the requirements of the game:

  • The game starts when the "ENTER" key is pressed.
  • A "monster" will be displayed in random location of the canvas per set milliseconds.
  • Hit - when the monster is clicked.
  • Miss - when the monster is missed - only during click
  • Monster turns yellow when hit.
  • Monster turns red when hit.
  • The game is over when there are already five (5) misses.
  • The top score is recorded - this will reset on every page load, though.
index.html
<!DOCTYPE html>
<html lang="en">
<head>
 <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js" type="text/javascript"></script>
</head>
<body>
 
 <canvas id="canvas" width="450" height="450"></canvas>
 <script src="pop.js" type="text/javascript"></script>
</body>
</html>

pop.js
$(document).ready(function()
{
 // canvas
 var canvas = document.getElementById("canvas");
 var ctx = canvas.getContext("2d");
 var w = canvas.width;
 var h = canvas.height;
 
 // monster
 var locX;
 var locY;
 var monsterSize = 50;
 var monSpaceX; // space occupied by monster in X
 var monSpaceY; // space occupied by monster in Y
 
 // colors
 var bgColor = "white";
 var strokeColor = "black";
 var monsterColor = "blue";
 var monsterHitColor;
 
 // other variables
 var text; // label on canvas
 var topScore = 0;
 var topText;
 var hitScore; // number of hits
 var isHit;
 var missLimit;
 var interval;
 var msec = 700;
 var play; // game is ongoing
 
 init();
 
 // ** ----- FUNCTIONS ----- **
 
 // initialize
 function init()
 {
  // initialize variables
  hitScore = 0;
  missScore = 0;
  missLimit = 5;
  text = "Click ENTER key to play.";
  topText = "Top Score: " + topScore;
  play = false;
  window.clearInterval(interval);
  
  // draw canvas
        paintCanvas();
 }
 
 // draw canvas
 function paintCanvas()
 {
  // format canvas by setting BG color and border
  ctx.fillStyle = bgColor;
  ctx.fillRect(0, 0, w, h);
  ctx.strokeStyle = strokeColor;
  ctx.strokeRect(0, 0, w, h); 
  
  setLabel();
 }
 
 // draw monster
 function placeMonster()
 {
  // set score label
  text = "Score: " + hitScore + "; Chance left: " + missLimit;
  
  setLocation(); // random location
  paintCanvas(); // draw canvas to cover past monsters
    
  // monster
  ctx.fillStyle = monsterColor;
  ctx.fillRect(locX, locY, monsterSize, monsterSize);
  
 }
 
 // paint monster to indicate it is hit or not
 function paintMonsterHit()
 {
  ctx.fillStyle = monsterHitColor;
        ctx.fillRect(locX, locY, monsterSize, monsterSize); 
 }
 
 // place label on canvas
 function setLabel()
 {
  // set top score label above
  ctx.fillStyle = strokeColor;
  ctx.fillText(topText, 5, 10);
  
  // set label below
  ctx.fillStyle = strokeColor;
  ctx.fillText(text, 5, h - 5);
 }
 
 // randomly generate location to where monster will be placed
 function setLocation()
 {
  locX = Math.floor((Math.random() * (w - monsterSize)) + 0);
  locY = Math.floor((Math.random() * (h -monsterSize)) + 0);
  
  getMonsterSpace();
 }
 
 // get the coordinates of the space occupied by monster
 function getMonsterSpace()
 {
  monSpaceX = locX + monsterSize;
  monSpaceY = locY + monsterSize;
 }
 
 // check if monster is hit or missed
 function isMonsterHit()
 {
  if(isHit)
   hitScore++;
  else
   missLimit--;
 }
 
 // check if game is over or not
 function checkGameOver()
 {
  if(missLimit == 0)
  {
   alert('Game Over. Score: ' + hitScore);
   if(hitScore > topScore)
   {
    alert('Congratulations! New Top Score!');
    topScore = hitScore;
   }
   init();
  }
 }
 
 // ** ----- EVENTS ----- **
 
 $(document).click(function()
 {
  if(play)
  {
   if(event.x >= locX && event.x <= monSpaceX && event.y >= locY && event.y <= monSpaceY)
   {
    monsterHitColor = "yellow";
    isHit = true;
   }
   else
   {
    monsterHitColor = "red";
    isHit = false;
   }
   
   paintMonsterHit();
   isMonsterHit();
   checkGameOver(); // check if game is over
  }
 });
 
 $(document).keydown(function(e)
 {
  if(!play)
  {
   var key = e.which;
   
   if(key == '13')
   {
    interval = window.setInterval(placeMonster, msec);
    play = true;
   }
  }
 });
 
});

Improvements in the future:
  • A miss should also be counted when user fails to do a click every time a monster appears.
  • Use image for monster.
NOTE: Only works for Google Chrome. :/

Read more ...

jQuery: Simple Colored Cell Game

Mar 7, 2014
So I decided to learn new stuffs *since I am not a web-person or anything*.

The goal would be to create a simple game that does the following:

  • At the start of the game, there is a blue-colored cell in the middle of the canvas.
  • On every left-click, the cell increases in size.
  • If an arrow key is pressed, the cell changes color and moves to that direction.
  • If the enter key is pressed, the game is reset.
Though it's just a really simple game, I find this a challenge. *I'm the Tech Noob after all. ;)

I've shared the codes below. Hopefully this helps beginners like myself. ;)

index.html
<!DOCTYPE html>
<html lang="en">
<head>
 <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js" type="text/javascript"></script>
</head>
<body>
 
 <canvas id="canvas" width="450" height="450"></canvas>
 <script src="cell.js" type="text/javascript"></script>
</body>
</html>

cell.js
$(document).ready(function(){
 
 // canvas stuff
 var canvas = document.getElementById("canvas");
 var ctx = canvas.getContext("2d");
 var w = canvas.width;
 var h = canvas.height;
 var locX; // location in X
 var locY; // location in Y
 var pxX; // pixel size in X
 var pxY; // pixel size in Y
 var cellColor;
 var BGColor;
 var strokeColor;
 
 function init()
 {
  // set default color
  BGColor = "white";
  cellColor = "blue";
  strokeColor = "black";
  
  // set default pixel size
  pxX = 10;
  pxY = 10;
   
  // set default location (center of canvas)
  locX = (w - pxX) / 2;
  locY = (h - pxY) / 2;
  
  paint();  
 }
 
 init();

 function paint()
 {
  // paint background
  ctx.fillStyle = BGColor;
  ctx.fillRect(0, 0, w, h);
  ctx.strokeStyle = strokeColor;
  ctx.strokeRect(0, 0, w, h);
  
  // paint cell
  ctx.fillStyle = cellColor;
  ctx.fillRect(locX, locY, pxX, pxY);
  ctx.strokeStyle = strokeColor;
  ctx.strokeRect(locX, locY, pxX, pxY);
 }
 
 $(document).click(function()
 { 
  // add one pixel for x and y on every click
  pxX++;
  pxY++;
    
  paint();
 })
 
 $(document).keydown(function(e)
 {
  var key = e.which;
  
  if(key == "37") // left
  {
   locX--;
   cellColor = "red";
  }
  else if(key == "38") // up
  {
   locY--;
   cellColor = "blue";
  }
  else if(key == "39") // right
  {
   locX++;
   cellColor = "yellow";
  }
  else if(key == "40") // down
  {
   locY++;
   cellColor = "green";
  }
  else if(key == "13") // enter
   init();
  
  paint();
 })
 
})
Read more ...