Recent News

Interactive character limit for textarea using Jquery

Posted by admin on November 9th, 2007

For a textbox, character of a field can easily be limited with maxlength attribute. But maxlength doesn’t work for  a textarea. So, It needs an alternate way. For one of my project, I wrote a function for this purpose where I used jQuery. Here I am explaining how I did it.

Let’s look an example of this interactive solution here

OK. Now we will make this in 2 easy steps.

1. Import your jQuery file and write the function "limitChars(textid, limit, infodiv)" in the head section of your page.

This function takes 3 parameters. They are:

  • textid : (string) The ID of your textarea.
  • limit : (num) The number of character you allow to write.
  • infodiv : (string) The ID of a div, in which limit information will be shown .

  Here is the function:

 1: <script language="javascript" src="Jquery.js"></script>
 2: <script language="javascript">
 3: function limitChars(textid, limit, infodiv)
 4: {
 5: var text = $(‘#’+textid).val(); 
 6: var textlength = text.length;
 7: if(textlength > limit)
 8: {
 9: $(‘#’ + infodiv).html(‘You cannot write more then ‘+limit+‘ characters!’);
 10: $(‘#’+textid).val(text.substr(0,limit));
 11: return false;
 12: }
 13: else
 14: {
 15: $(‘#’ + infodiv).html(‘You have ‘+ (limit - textlength) +‘ characters left.’);
 16: return true;
 17: }
 18: }
 19: </script>

Remember, the script is using jQuery. So be careful about the path of jquery at first line of this script.
 
2. Bind the function to the keyup event of your textarea. Do this in jQuery’s ready event of document. Just like this:
 1: $(function(){
 2: $(‘#comment’).keyup(function(){
 3: limitChars(‘comment’, 20, ‘charlimitinfo’);
 4: })
 5: });

Here my textarea’s id is ‘comment’ , limit of characters is 20 and limit information will shown in a div whose id is ‘charlimitinfo’. That’s all, we have made an "Interactive character limiter" for our textarea using Jquery.
 
If you are not using jQuery for your site, it will not be wise to include it only for this script. You can get the same functionality from javascript without jquery. Look at this example. It looks like and works 100% as the previous though not using jquery.
Here you need just 2 changes. First, change the function "limitChars" as follows :
 1: function limitChars(textarea, limit, infodiv)
 2: {
 3: var text = textarea.value; 
 4: var textlength = text.length;
 5: var info = document.getElementById(infodiv);
 6:  
 7: if(textlength > limit)
 8: {
 9: info.innerHTML = ‘You cannot write more then ‘+limit+‘ characters!’;
 10: textarea.value = text.substr(0,limit);
 11: return false;
 12: }
 13: else
 14: {
 15: info.innerHTML = ‘You have ‘+ (limit - textlength) +‘ characters left.’;
 16: return true;
 17: }
 18: }

 
And finally, call the function manually on keyup event of your textarea. Use "this" keyword for textarea instead of id when calling the function. example:
 1: <textarea name="comment" id="comment" onkeyup="limitChars(this, 20, ‘charlimitinfo’)">
 2: </textarea>

Finished. We made the solution again without dependency of any javascript framework.

Please let me know if you have an idea to make it better. 

jQuery controlled Dependent (or Cascading) Select List 2

Posted by admin on November 8th, 2007

Thank you all. Thanx for using, commenting and visiting my script jQuery controlled Dependent (or Cascading) Select List from my old bolg http://php4bd.wordpress.com and here.

I am getting a lots of request and questions from visitors about adding some features and some other problems. Sometimes I faced some problem when using this script myself. So, I have made some changes here. I hope, this change will help you to overcome some problems of previous version of this script. The main features added in this version are:

  1. It will keep in child list box only sub items of selected parent value when initializing.
  2. Added a 4th parameter to input a selected value for child list box.
  3. When "isSubselectOptional" is true, add a default value ‘none’ for ‘– Select –’ option of child list box.
  4. Automatically focus the child list box when a value is selected from parent list box.
  5. More effective for multilevel association.

Click here to see a demo of multilevel association using this function.

Here is the modified function:

 1: function makeSublist(parent,child,isSubselectOptional,childVal)
 2: {
 3: $("body").append("<select style=’display:none’ id=’"+parent+child+"’></select>");
 4: $(‘#’+parent+child).html($("#"+child+" option"));
 5: 
 6: var parentValue = $(‘#’+parent).attr(‘value’);
 7: $(‘#’+child).html($("#"+parent+child+" .sub_"+parentValue).clone());
 8: 
 9: childVal = (typeof childVal == "undefined")? "" : childVal ;
 10: $("#"+child+‘ option[@value="’+ childVal +‘"]’).attr(’selected’,’selected’);
 11: 
 12: $(‘#’+parent).change( 
 13: function()
 14: {
 15: var parentValue = $(‘#’+parent).attr(‘value’);
 16: $(‘#’+child).html($("#"+parent+child+" .sub_"+parentValue).clone());
 17: if(isSubselectOptional) 
 18: $(‘#’+child).prepend("<option value=’none’> — Select — </option>");
 19: $(‘#’+child).trigger("change"); 
 20: $(‘#’+child).focus();
 21: }
 22: );
 23: }

And initialize the association on ‘$(document).ready’, as following example:

 1: $(document).ready(function()
 2: {
 3: makeSublist(’parentID’,‘childID’, true, ‘selected_val_of_child’);
 4: });

If you want to create multilevel association, start the initialization from child most order. such as:

 1: $(document).ready(function()
 2: {
 3: makeSublist(‘child’,‘grandson’, true, ); 
 4: makeSublist(‘parent’,‘child’, false, ‘3′); 
 5: });

For details instruction and example of using this script, please visit the previous version. Feel free to ask me if any problem with using this script or any bug you found.

Ajax-like Unobtrusive File Upload

Posted by admin on July 28th, 2007

We use AJAX whenever we need to communicate with the server, without reloading the page. But this doesn’t function in the case of File Upload. In usual view, uploading files with AJAX is impossible! (FireFox/Mozilla can do this after change a setting in “about:config” – which we cannot guarantee for a lot of users).

When I was searching for any technique to upload file without reloading page, I found a script in www.webtoolkit.info . But it seemed very complex to me. Then I try to simplify their technique and its working great. So I thought why not share the technique with everybody?

First, look at the demo here to see how it works.

OK. Let’s get into the deep. What happens when we submit a form? The form is submitted to the action page and that page loaded in current frame of window. If the “target” attribute of form indicate “_blank” or any frame name of the window, the page loads in a blank window or in the named frame or inner frame. Here we’ll be using the second method.

First, take an inner frame in anywhere of the page. And set the display property of this frame as “none”:

    <iframe name="hiddenFrame" id="hiddenFrame" 
    src="about:blank" style="display:none" >
    </iframe> 

Now, just set this frame as the target of your uploading form.

<form name="testForm" id="testForm" enctype="multipart/form-data" 
    action="upload.php" method="post" target="hiddenFrame">
        <input type="file" name="name" /> 
        <input type="submit" value="Upload!" />
    </form>

If we submit this form now, it will submit the file to the target script on the server (can be in php, asp etc.). The script will upload the file and will load the response in the frame “hiddenFrame”. As the frame is not visible, nothing about this loading will be seen by the visitors. Now, as the uploading page displays nothing after uploading your file, the response can be immediate. Although it’s not AJAX, this technique will upload your file without (visually) reloading page.

What more?

For many purpose, we might need a callback function when using AJAX. For this file uploading technique also, we will try to create something like that. First, we’ll write the callback function as a simple JavaScript function in the header of the uploading page:

<script language="javascript">
function trackThis()
{
var resultDiv = 
    window.frames.hiddenFrame.document.getElementById(‘result’);
var uploadedImage = document.getElementById(‘UploadedImage’);

uploadedImage.src = resultDiv.innerHTML; 
uploadedImage.style.display="block";

alert("File Uploaded :" + resultDiv.innerHTML);
}
</script>

When the uploading of the server page is complete, it should print the JavaScript code in the hidden iframe, to call the callback function with the reference “window.top”. Any other required information also can be printed in specific DIVs. It will enable us to retrieve any response information using the innerHTML of any specific DIV (as shown in example callback function).

Example:

<?php
print_r($_FILES["name"]);
if(move_uploaded_file($_FILES["name"]["tmp_name"], 
            dirname(__FILE__)."/".$_FILES[‘name’][‘name’]))
{
echo "Your uploaded file is: <div id=’result’>".$_FILES[‘name’][‘name’]." </div>";
}           
else
{
    echo "<div id=’result’>Sorry! Error occured!</div>";  
}
echo <<<test
<script type="text/javascript">
window.top.trackThis()
</script>
test;
?>

Well, that’s it. This technique has already saved my ass once, see if it can save yours also when you need.

jQuery controlled Dependent (or Cascading) Select List

Posted by admin on July 15th, 2007

When I was searching the web for a client side dependent list boxes, I got some scripts. But some of them were very much static (static select name, option name etc.), some were vary complex. Then I thought to make it myself.
I have been using jQuery as the standard JavaScript library for most of my web project for some days. Writing javascript coding in jQuery is fun. So here goes my contribution using it.

Here is a simple demo.

Let me guide you through it.

1. Include jqury.js.

<script language=”javascript” src=”jquery.js”></script>

You can get Jquery from here.

2. Write this simple function in a javascript block in head.

function makeSublist(parent,child,isSubselectOptional)
{
$(”body”).append(”<select style=’display:none’ id=’”+parent+child+”‘></select>”);
$(’#'+parent+child).html($(”#”+child+” option”));
$(’#'+child).html(”<option> — </option>”);
$(’#'+parent).change(
function()
{
var parentValue = $(’#'+parent).attr(’value’);
$(’#'+child).html($(”#”+parent+child+” .sub_”+parentValue).clone());
if(isSubselectOptional) $(’#'+child).prepend(”<option> — Select — </option>”);
}
);
}

This function takes 3 arguments: the parent select input’s id, the child select input’s id, and a boolean value to indicate whether to select an item from child list by default.

Example: makeSublist(’listA’,'listB’,false);

This function will make the options of ‘listB’ list depending on the selection of ‘listA’. And user have to select an item from ‘listB’.
Here ‘listA’ and ‘listB’ are the IDs of parent and child select input respectively.

3. Add a class to the ‘<option>’s of the child list box. The class name will be the value of it’s parent ‘<option>’ in parent listbox with a ’sub_’ prefix.
Suppose, in parent listbox there is an item “Flower”. Its value is ‘fl’:

<option value=’fl’>Flower</option>

When the item “Flower” will be selected, only 3 items should be visible in child listbox. These 3 items should hold the class name ’sub_fl’:

<option class=”sub_fl” value=”1″>Rose</option>
<option class=”sub_fl” value=”2″>Sunflower</option>
<option class=”sub_fl” value=”3″>Orchid</option>

4. Now you are ready. On ‘$(document).ready’ event of Jquery, run the function to associate your list boxes.

$(document).ready(function()
{
makeSublist(’parentID’,'childID’, false);
});

5. Enjoy :)

Recent Comments | Recent Posts


designed by: Website Builder | Coded by: Blog Directory | Provided by: Wedding photojournalism chicago
bottom