Tag Archives: javascript

How to unformat and save formatted numbers using accounting.js

Okay, so this is part 2 of the tutorial that I have written yesterday on the basic usage of accounting.js.

How to convert numbers to currency format using accounting.js

This time I’m going to show you how you can unformat those formatted numbers so that it can be stored in the database. I’m also going to show you how to save the data using ajax.

Since this is the second part of an existing tutorial. The requirements are still the same. You only need to install a database server like Wampserver if you want to have a database where you can save data.

We have a few changes on the markup. If you followed along in the first part its better if you just create a new file.

<p>
<label for="raw_num">Raw Number 1:</label>
     <input type="text" name="raw_num" id="raw_num">
</p>
<p>
     <label for="raw_num">Raw Number 2:</label>
     <input type="text" name="raw_num2" id="raw_num2">
</p>
<p>
     <label for="raw_num">Raw Number 3:</label>
     <input type="text" name="raw_num3" id="raw_num3">
</p>
<p>
     <label for="form_num">Formatted Number 1:</label>
     <input type="text" name="form_num" id="form_num" class="formnum">
</p>
<p>
     <label for="form_num">Formatted Number 2:</label>
     <input type="text" name="form_num2" id="form_num2" class="formnum">
</p>
<p>
     <label for="form_num">Formatted Number 3:</label>
     <input type="text" name="form_num3" id="form_num3" class="formnum">
</p>
<p>
     <input type="button" id="btn_save" value="save">
</p>

Does the markup suggests anything to you? To kill the question, yes were going to make use of arrays here in order to capture all the values in the text fields which has the formnum class. Formnum is short for formatted number.
As the name suggest, the one and only button in the markup is used for saving the data into the database.

Next is the script itself.
First, ensure that the user only gets to input numbers:

$('#raw_num, #raw_num2, #raw_num3').numeric();

Then format the raw numbers. Nothing new here, we just repeated what we did on the first tutorial.

$('#raw_num').keyup(function(){
	var raw_num = $(this).val();
	var form_num = accounting.formatMoney(raw_num);
	$('#form_num').val(form_num);
});
	
$('#raw_num2').keyup(function(){
	var raw_num = $(this).val();
	var form_num = accounting.formatMoney(raw_num);
	$('#form_num2').val(form_num);
	});
	
$('#raw_num3').keyup(function(){
	var raw_num = $(this).val();
	var form_num = accounting.formatMoney(raw_num);
	$('#form_num3').val(form_num);
});

Finally, the action to be performed when the user clicks on the save button. To explain things, on the 2nd line, we just declared an array called raw_num in which the unformatted numbers will be stored. On the 3rd line (Whitespaces isn’t considered a line), we loop through each of the elements which has a class of formnum. Then we used the unformat method of accounting.js to turn the number back to its raw form. Then on the 6th line, we called the jquery’s $.post function. The $.post function is a simpler version of the $.ajax function. Which only requires a minimum of 2 arguments, one is the php file that would talk to the server, and the second is the variable that you’re going to pass on to that php file. In this case we want the array of unformatted numbers to be the variable that’s going to be passed.

$('#btn_save').click(function(){
     var raw_num = [];
	
     $('.formnum').each(function(index){
	raw_num[index] = accounting.unformat($(this).val());
     });
	
     $.post('save.php',{'raw' : raw_num});
});

 

Maybe you’re wondering why do I still bother unformatting the number if there is already an unformatted version of that number. My answer would be yes, there’s really no purpose in formatting the number then unformatting it again if there exist a copy of the unformatted number.
But what if there’s none? What if the formatted version of the number should also be placed wherever the original number is.

And I almost forgot what the heck is save.php. Well save.php will be the one who talks to mysql. Saying: “could you please save this bunch of numbers into your database?“ Here’s what it contains. What we did here was to loop through the contents of $_POST[‘raw’]. ‘Raw’ is the name of the variable that we assigned in the javascript earlier.

<?php
require_once('randomconfig.php');

foreach($_POST['raw'] as $num){
	$db->query("INSERT INTO accounting_js SET numbers='$num'");
}
?>

 

Conclusion
Accounting.js is indeed a very nice tool for number formatting. But there are more features which aren’t discussed here, so you might as well check out the official site for more information regarding accounting.js.
Aside from accounting.js I also showed you how to loop through elements containing data, and save data into the database using jquery’s $.post method.

Remember inputted data using jquery cookies

I know what brings you here.
But before that, here’s what were going to do here:

  • Setting up client-side cookies using jquery
  • Using cookies to automatically fill up a form

 

Requirements

 

I decided to ditch the assumptions and proceed with the procedures right away. I figured that most of you doesn’t actually read it.

 

Procedure

As usual, do the housekeeping. Include those 2 files I mentioned in the requirements.

<script src="jq.js"></script>
<script src="jquery.cookie.js"></script>

Create the form:

<form name="x" action="formcookie.php" method="post">
<p>
Remember input?
<input type="checkbox" name="rem" id="rem">
</p>
<p>
name:
<input type="text" name="name" id="name">
</p>
<p>
course:
<input type="text" name="course" id="course">
</p>
<input type="submit" id="btn_submit" value="save">
</form>

Nothing new here, I’m still bad at indenting the code properly. Please bear with me.
The code above is the form that we are going to use. As you can see it has a checkbox which the user can check in order to save his input into a cookie. And uncheck it to delete any existing cookie. That’s just a scenario of what it does, we didn’t actually wrote the code that does what I just said.

Next, write the usual thing to do when using jquery: Initialize elements on page load:

<script>
$(function(){
  //code goes here
});
</script>

Then we assign values to the name and course fields to be equal to the cookies that were going to declare shortly. You can actually check if those cookies exist before assigning it to the textfields. But I didn’t get any error on Firebug so I think this is just fine.

$('#name').val($.cookie('name'));
$('#course').val($.cookie('course'));

Right after the user has clicked on the submit button we want to execute something:

$('#btn_submit').click(function(){
  //something
});

You’re asking what’s something? Here’s the algorithm:

  1. check the if the checkbox is checked
  2. if checked assign the cookies
  3. if not clear the cookies

Next time the page loads: values are automatically assigned to the text fields if the cookies exists.

Okay, so here’s what goes as inside the btn_submit() function. Assign the values which are currently in the text fields into the variables name and course:

var name = $('#name').val();
var course = $('#course').val();

Also assign the status of the checkbox to a variable. The variable cook will have a value of true if the checkbox is checked and false if its not:

var cook = $('#rem').attr('checked');

That’s it! All that is left to do now is to write the code that will assign the cookie if the checkbox is checked. And the code that will clear the cookie if the checkbox isn’t checked:

if(cook == true){
    $.cookie('name', name);
    $.cookie('course', course);
}else{
    //clear cookies
    $.cookie('name', '');
    $.cookie('course', '');
}

 

Conclusion

You have just learned how to use the jquery cookies plugin to create client-side cookies. You can actually use this to add a remember me functionality on your login form or any other kind of form which needs to be automatically filled up based on user preferences.

Generating form elements using jquery

Last time I showed you how you can generate form fields using javascript and a little bit of jquery:

How to generate form fields using javascript

This time, I’ll show you how you can do it in jquery with a little bit of javascript.

Requirements

  • Jquery core

 

Assumptions

Yep! It’s the first time that I’m going to do this section. A proper introduction is needed. Assumptions section is where I speak of  all the things which you need to know first before trying to read a tutorial. So in this tutorial, I assume that you already know the basics of jquery and javascript. That’s all there is to it, if you already know javascript and jquery, and you have all the requirements. Then you’re ready to start.

 

Procedure

First, do the housekeeping. I won’t tell you how to do it…
Just kidding! When I say housekeeping, it means including all the files which are needed on your page. And the bit of code which will let you perform actions using jquery.

$(function(){
       //form generation code goes here
});

Second, create the form which will be used by the user to generate another form element.

<form name="x" action="jquery_generatefields.php" method="post">
<input type="button" id="jq_gen_txt" value="generate text field"/><br/>
<input type="button" id="jq_gen_sel" value="generate select field"/>

<div id="gen_txt_fields"></div>
<div id="gen_sel_fields"></div>
<input type="submit"/>

If you have red my last tutorial on creating form elements using javascript. You might already know that the 2 buttons in the form will be the event launcher. And the 2 divs is where the generated field goes to.

You might also notice that I have action and method attributes for the form. That’s because I’m going to make a 2nd part for this tutorial in which we will actually save the inputted data in those dynamically generated fields into the database. Stay tuned for that.

Going back to javascript. Inside the document.ready() function. Create 2 new variables. This will serve as the index for the elements that the user is going to create later on. If you didn’t catch what I mean by that. I said that were going to use it for the id attribute for each dynamically generated form elements.

var num_txt = 0;
var num_sel = 0;

By the names of those variables, you might already predicted that what were going to generate are:

  • Text field
  • Select field

Next, create the function that will execute if the button for generating text fields has been clicked:

$('#jq_gen_txt').click(function(){
  //code for text field generation goes here
}

Inside the function. We create the element input. Then add attributes id, name, and placeholder to it. Id is optional, if you want to have a unique identifier for the form elements that are created then put the id attribute. Name attribute is mandatory for this tutorial. Since were going to use it later to access the value of that specific field for our database. Finally we append it to the div with the id attribute of gen_txt_fields.

var txt = $("<input>").attr({'id': 'tx' + num_txt,
 'name': 'tx[]',
 'placeholder':  num_txt}).appendTo('#gen_txt_fields');

Next we also create a button which can be used by the user to remove the text field that has been created.

var rem_btn = $("<input>").attr({'type' : 'button',
 'id' :  num_txt, 
'value' : 'remove'}).appendTo('#gen_txt_fields');

The code is the same, the only difference are the attributes which are being applied. Type attribute is used to determine what type of input field will be generated, this is a mandatory attribute. Since without it, you can’t possibly know what type of input field will be generated because there are lots of input fields. Some of those are:

  • radio buttons
  • checkboxes
  • text fields
  • password fields

And with the advent of html5. Another set of fields has been added to the list:

  • email fields
  • telephone number fields
  • number fields

I think there are still more, but I can’t recall them. And I can’t even Google them since my internet connection has already been turned off at this moment.

Oops, don’t forget to include the code which will increment the variable num_txt everytime the user clicks on the button:

num_txt++;

Next create the function for creating select fields:

$('#jq_gen_sel').click(function(){
   //code for select field generation goes here
}

First, you have to create the select field.

var sel = $("<select>").attr({'id' : 'gender' + num_sel, 
'name' : 'gender[]'}).appendTo('#gen_sel_fields');

Next, will be its options:

var male = $("<option>").attr({'id' : 'male' + num_sel ,
 'value' : 'Male'}).text('Male').appendTo(sel);

var female = $("<option>").attr({'id' : 'female' + num_sel,
 'value' : 'female'}).text('Female').appendTo(sel);

We both append those to the select field which is currently assigned to the variable sel. So its safe to make use of the variable name. But you can also make use of the id of the select field, that will also work.
Remember that the value is different from text:

  • value – actual value of the option
  • text – the value which is being shown in the option. (innerHTML as you might call it)

Then finally the incrementing code:

num_sel++;

Next, we write the code for the button which removes/deletes the generated text field (I’ll leave the removal of select field to you).

$('input[id^=rem_btn]').live('click', function(){
   //code for input field removal
}

The code is a bit different from usual. Since we didn’t use the click() event directly. We used the live() event instead. Its always been my practice to use this in cases wherein I need to access a dynamically generated form.

var clicked = $(this).attr('id');
var tx_id = 'tx' + clicked;
$("#" + tx_id).remove();
$(this).remove();

In the code above, we accessed the Id attribute of the button, and stored it in the tx_ad variable together with the prefix that we used in the text fields id which is the word ‘tx’. We then performed a simple remove() function to remove the text field with the same index as that of the button.

 

Conclusion

That’s it for this tutorial. You’ve learned how to generate form elements using jquery. Next time I’m going to show you how you can save the data inputted in those dynamically generated text fields into the database.

Hide or show multiple form elements using jquery and fieldsets

In this tutorial I’m going to show you how you can hide or show multiple form elements in one go. That is by grouping those form elements in an html fieldset.

 

Requirements

  • jquery core

 

Procedure

First, do the housekeeping.

<style>
#full{
    width:500px;
}
</style>
<script src="jq.js">
</script>

I’m really lazy today, so I didn’t include the style and the script type. This works, but its not really a good practice.

Next, create the form elements.

<input type="button" id="hide" value="hide/show"/>

<fieldset id="full">
<legend id="full_legend">Fieldset_hideshow</legend>
<p><input type="text" name="a" placeholder="a"/></p>
<p><input type="text" name="b" placeholder="b"/></p>
<p><input type="radio" name="c"/>
<input type="radio" name="c"/>
<input type="radio" name="c"/></p>
</fieldset>

We grouped the 2 text fields and the 2 radio buttons inside the fieldset. So that we won’t be accessing those elements one by one if we want to hide/show them.

Finally, we create the script which will hide/show the fieldset and all of the elements inside of it.

<script>
$(function(){

$('#hide').click(function(){
    $('#full').toggle('fast');
    });
});
</script>

In case you don’t know toggle is just a shortcut for .show() and .hide() functions. And here’s what it does: first it checks if the element is hidden or not. Might be something like this, if you hand code it:

if($(element).is(":visible")){
    //hide it
}else{
    //stay put
} 


Conclusion

I can’t really think of a good conclusion, because it seems like I’m only repeating what I’m saying every time I make a conclusion. And what’s worst is that what I’m saying doesn’t really fit the description of a conclusion. Don’t you agree? Anyway, again thanks for reading!

How to generate form fields using javascript

In this tutorial I’m going to show you how you can generate form fields using javascript and jquery.
This is useful when you need to conserve space on your form and you only want to show the optional fields if the user needs it.

Requirements

 


Procedure

Yeah, I  guess I’ll just call this portion ‘procedure’ from now on. You might have notice the inconsistency if you’re a regular reader of my blog.

First, I need you to setup your folder structure. You must know how to link your jquery core file. If its just inside the same folder as the file that we are building right now then it might look something like this:

<script type=”text/javascript” src=”jq.js”>
</script>

 

Means

Second, let’s build the form elements which will serve as a way to create the dynamically generated form fields. For this tutorial, we will be using a button.

<input type=”button” id=”glink” value=”generate link”/>
<input type=”button” id=”gtext” value=”generate textbox”/>
<input type=”button” id=”gradio” value=”generate radio”/>

In the sample code above. I have 3 buttons. One that generates a link, the other generates a text field, and the last one generates a radio button. As you can see from the values.

Parent

Third, let’s build another set of form elements. This will serve as the parent for the form elements which will be generated:

<div id=”link_div”></div>

<div id=”text_div”></div>

<div id=”radio_div”></div>

 

Analogy

In real world (yeah, I guess this is my first time doing an analogy), a child needs a parent in order to be born or exist. They can’t just pop out of nowhere. They need someone to bring them into this world. And so are form elements. In the sample above, there is a separate parent element for links, text fields , and radio buttons. So that they won’t just scatter everywhere in the page once they’re created.

 

Housekeeping

Fourth, let’s go back to jquery and javascript. I’m talking about the code which we are going to put inside the <script></script> tags. If you don’t already have that, then I think its time you type it on your text-editor. Then do the housekeeping:

$(function(){

var num = 0;
var num2 = 0;
var num3 = 0;

});

If you’re a psychic or someone who has mental powers. Then you might now what those 3 variables are for. If not, then here’s my answer since I’m no good at naming things: variables num, num2 , and num3 will be used as an index to keep track of how many links, textboxes, or radio buttons are generated. They will also serve as the id attribute for each element. If this is not clear to you, then you’ll see what I mean once you see the output.

 

Functions

Fifth, let’s now create the functions that will be performed when users click on each of the buttons that we created a while ago. Prepare yourself because here’s a big chunk of code:

$(‘#glink’).click(function(){

    var link = document.createElement(‘a’);
    link.setAttribute(‘href’, ‘mypage.htm’);
    link.setAttribute(‘id’, ‘link’ + num);

    document.getElementById(‘link_div’).appendChild(link);
    document.getElementById(“link + num).innerHTML = “spanner” + num + “<br/>”;
    num++;

});

On the first line, we declared a function which will be called if the user clicks on the button with an id attribute of glink (glink for generating link). Then we declared a variable called link, which will hold the value returned by the create element javascript function. Create element takes up 1 argument, and that is the actual html element that you want to create. In the code above, were trying to create an anchor element (link). If you want to create an image you do it this way:

document.createElement(‘img’);

As you can see, its not just for form elements. You can use the create element function to create any html element which can be seen.

Next, we set the attributes for the newly created form. Since it’s a link, it needs an href attribute which will contain the actual link (like this: http://google.com). And also an id attribute, which will differentiate it from the rest of the links that will be generated. And to make the id as unique as possible, I added the num variable. Which will be incremented every time we generate a new link to the page.

link.setAttribute(‘href’, ‘mypage.htm’);
    link.setAttribute(‘id’, ‘link’ + num);

Then we append it to its parent element. Which is the div element with the id attribute of link_div:

document.getElementById(‘link_div’).appendChild(link);

Lastly, we try to give it a form. So that we can see that its actually there:

document.getElementById(“bolok” + num).innerHTML = “spanner” + num + “<br/>”;

And don’t forget the code which makes the unique id thing possible:

num++;

 

Conclusion

I guess one example should do. Just check out the files that I used in this tutorial in the files section of this blog. If you want to see the code for the textbox and radio button generation.

How to display current time using javascript

Okay, so here’s another quick tip. Let me show you how you can build a digital clock which updates without refreshing the page.

 

Building the function

First let’s build the function which will output the date:

function tym(){

var date = new Date();
var hr = date.getHours();
var min = date.getMinutes();
var sec = date.getSeconds();
document.getElementById(“time”).innerHTML =  hr + ” : ” + min + ” : ” + sec;

}

I said I’ll make this quick but I’ll still explain this one to you. First we created a function called tym().
Then we declared an object for the Date javascript class. (I called it class because it really looks like a class to me, so correct me in the comments if you think I’m wrong). We then break down the date into hours, minutes and seconds and assigned them to their very own variables.

Basically, getHours(), getMinutes(), and getSeconds(). As their format suggests, are functions inside the Date class which returns what the hours, minutes and seconds. So all we have to do is to spit them out on the screen to see their contents.

On the last line, what we did was just to output the things that we have gathered so far.

 

html

Here’s the little piece of code which will serve as a container for the time:

<div id=”time”>

</div>

 

realtime

Lastly, let’s call the function that we created earlier:

document.onload = setInterval(“tym()”,100);

setInterval is a javascript function which takes two parameters:

  • function
  • time interval – 100 is like 1 second. Don’t take my word for it, I’m not really sure if its 1 second or less.

 

output

The output will be like a digital clock, which ticks every second without refreshing the page.