Showing posts with label javascript help. Show all posts
Showing posts with label javascript help. Show all posts

Saturday, March 5, 2016

Display Other Texts rather then English using PHP MySQL


When we want to display and store the data other than ENGLISH using PHP.

Below is the code used to save and retrieve the data in PHP.

mysql_set_charset('utf8',$db_connect);

where $db_connect is the "MySQL Host" connection handler. You can see the example below for the connection handler.


<?php
$db_connect = mysql_connect(HOST_NAME,USERNAME,PASSWORD);
mysql_set_charset('utf8',$db_connect);
?>


By using the above, we can store and retrieve the data in different languages like Telugu, French, Hindi, German and many.

Note: And also a major note we need to be keep in mind, when we try to retrieve the same UTF-8 converted data using AJAX. We should not use "mysql_set_charset" as AJAX by default sets the content as "UTF-8" 

Monday, February 29, 2016

Disable Back Button using Javascript




User tries to use back button for most of the applications and it is valid, but few of the cases is required to disable the back button and also restrict the user.

It would be very useful when the user is on payment page. Below is the code to disable the back button in Browser.

var currentURL = window.location.pathname + window.location.search;
 history.pushState(null, null, currentURL);
 window.addEventListener('popstate', function(event) {
  history.pushState(null, null, currentURL);
 });

It works in all major browsers

Tuesday, July 7, 2015

Trigger onchange event manually using Javascript


Below is the code to trigger onchange event for an element using javascript.

Usage of the method can be, when we want to call the onchange event on page loads or on by changing the text box value for other textbox.


if(document.fireEvent) {
    document.getElementById("myElement").fireEvent('onchange');
} else {
    var event = document.createEvent("HTMLEvents");
    event.initEvent("change",true,false);

    document.getElementById("myElement").dispatchEvent(event);
}

Whereas in jQuery, we can simply call the below method.

jQuery('myElement').change();

Thursday, July 24, 2014

Javascript: trim function support in all browsers



In Javascript, when we want to remove spaces in a string, we would be using trim function which is supported in all major browsers. See below code to use trim function in Javascript.

var str = "     message to trim    ";
document.write(str.trim());  // this code will prints as message to trim in the body.

But the above trim() function doesnot support in IE. To support the same functionality in IE too, add the below code to work as expected.

if (typeof String.prototype.trim !== "function") {
    String.prototype.trim = function () {
        return this.replace(/^\s+|\s+$/g, "")
    }
}


Sunday, December 1, 2013

Value of CKeditor using Javascript


To get the value of the CKeditor content using Javascript or jQuery. We need to use the below syntax.

CKEDITOR.instances['article_long_desc'].getData().length => It provides the length of the content in the editor

CKEDITOR.instances['article_long_desc'].getData() => It retrieves the value of the Textarea


Where "article_long_desc" is the textarea name


Sunday, October 20, 2013

ajax with cross domain


We may worked with jQuery ajax in many cases but when we try to use jQuery AJAX to get the data from other domain, we need to use "crossDomain" & set it to true.

Let us consider the basic jQuery AJAX within the domain.

$.ajax({
            url: "show_users.php",
            data: {data1:"val1", data2="val2"},
            type:'POST',
            success: function(res)
            {
                $('#element_name').html(res);
            },
            error: function (){alert('something went wrong');}
});

Above is the AJAX request within the domain & just we are passing the data to the page "show_users.php" with two values. As it is simple AJAX request, it works fine.

But when we work with cross domains (i.e. AJAX request to other domain from our domain) we need to rewrite the jQuery AJAX as below.

$.ajax({
            url: "http://domain.com/show_users.php",
            data: {data1:"val1", data2="val2"},
            type:'POST',
            crossDomain: true,
            success: function(res)
            {
                $('#element_name').html(res);
            },
            error: function (){alert('something went wrong');}
});

We need to use "crossDomain" & set it to TRUE & in the domain.com show_users.php page we need to set an header as below.

header('Access-Control-Allow-Origin: *');

We can set the "Access-Control-Allow-Origin" with only one IP address or '*' if it is not limited to single IP address

Sunday, October 6, 2013

Verify whether HTML object has the event using javascript or jQuery

We would be using multiple events or plugins to get our requirement done using jQuery.

While adding them we may not know whether the plugin is activated or not that gives error to the browser if it does not initiate and stops the next line of scripts in jQuery which we should not be doing. 

To get rid of this, we can use jQuery hasOwnProperty which tells whether the HTML object has the event which we are checking for.

Below is the sample code:

Consider we have included the CKEDITOR in the script and it applies for the textareas.


<html>
<head>
<script type="text/javascript" src="ckeditor.js">
<title>Test Object Event Existence</title>
</head>
<body>
<ul>
     <li>First name: <input type="text" name="fname" /> </li>
     <li>Last name: <input type="text" name="lname" /> </li>
     <li>Address: <textarea name="address" id="address" ></textarea></li>
</ul>
</body>
</html>
For the above script, to check whether the textareas has CKEDITOR or not we can check as below

$('#address').hasOwnProperty('CKEDITOR') 

If it exists it returns true else returns false.


Monday, July 29, 2013

Decode html entities using javascript

Below is the code to decode the html entities using javascript rather than the Server side scripting

function decodeEntities(input) {
    var y = document.createElement('textarea');
    y.innerHTML = input;
    return y.value;
}

Above function just receives the html values like below

var str = "<p>Hello World<br />This is the test message";

When we pass the above HTML string to the function it returns as below,

calling the JAVASCRIPT function 

decodeEntities(str)

Output is: "&lt;p&gt;Hello World&lt;br/&gt;This is the test message";

Thursday, July 18, 2013

Disable right click in a page using javascript


When we want to restrict the right click of the mouse in some of the pages, need to add the below code in the <head> </head> tag within the JAVASCRIPT.

<script type="text/javascript">
var message="Sorry, Right Click has been disabled";
        function clickIE() {if (document.all) {window.console.log(message);return false;}}
       
       function clickNS(e) {
if (document.layers||(document.getElementById&&!document.all)) {
       if (e.which==2||e.which==3) {window.console.log(message);return false;}
}
}
        if (document.layers)
        {document.captureEvents(Event.MOUSEDOWN);document.onmousedown=clickNS;}
        else{document.onmouseup=clickNS;document.oncontextmenu=clickIE;}
        document.oncontextmenu=new Function("return false")

</script>


Thursday, January 3, 2013

javascript validation for file upload

Below is the article for adding javascript validation (or) jquery validation for a file upload that makes our life easier whether the file upload is a valid type or not.


if($('#upload_file').val() != '')
{
        var _validFileExtensions = [".jpg", ".jpeg", ".bmp", ".gif", ".png"]; // Can change the extensions if we need for doc type or something else
        if($('#upload_file').val() != '')
        {
            var sFileName = $('#upload_file').val();
            var blnValid = false;
            for (var j = 0; j < _validFileExtensions.length; j++)
            {
                var sCurExtension = _validFileExtensions[j];
                if (sFileName.substr(sFileName.length - sCurExtension.length, sCurExtension.length).toLowerCase() == sCurExtension.toLowerCase()) {
                    blnValid = true;
                    break;
                }
            }
            if(!blnValid)
            {
               alert("Sorry, " + sFileName + " is invalid, allowed extensions are: " + _validFileExtensions.join(", "));
                $('#upload_file').focus();
                return false;
            }
        }
 }

Tuesday, January 24, 2012

jQuery Form Validation

Tired of validating the form using javascript. Here is the code to validate the form using jQuery.


  function submit_form()
{
var formElements = $('#form_name .required'); // Reading all elements in the form which are having class as required

var error = 0;

formElements.each(function() { // Looping all the elements which are having the class name as required...
if($(this).val() == "") {  // Checking the value of the field
                                                // Showing the border color as red if the field is empty
$(this).css('border','1px solid red');
error++;
} else {
                                                // removing the border if the field has the value....
$(this).css('border','none');
}
});
}

Use the submit_form function in onsubmit of the form.

The fields in the form which need to be validated should be given as below.

<input type="text" name="field_name" class="required" />

If we add the class required for the textbox, it validates otherwise it doesnot validate the textbox.


Sunday, September 25, 2011

jQuery Basics

Below are the basics of jQuery. How to create a simple variable, array, objects and a function.

This is explained by Mike Kamminga (Managing director of W3industries). We had a nice session on some other things but I've considered below is the basic jQuery reference for creating objects, arrays.


// simple variable
var myVar = 'value1';
console.log(myVar); //By having console.log we can check the output of javascript in Console of Chrome


// simple array
var myArray = ['value1','value2'];
console.log(myArray);
console.log(myArray[1]);


// simple object
var myObject = {
key1:'value1',
key2:'value2'
};
console.log(myObject);
console.log(myObject.key2);


// multidimensional array
var myArray2 = ['value1','value2', ['value3','value4']];
console.log(myArray2);
console.log(myArray2[2][0]);
console.log(myArray2.length);


// multidimensional object
var myObject2 = {
key1:'value1',
key2:'value2',
key3:{key4:'value4'}
};
console.log(myObject2);
console.log(myObject2.key3.key4);


// example of object references
var settings = {
width : '100',
height : '200',
img : ['img/img1.jpg']
};
// creating reference (not copy)
var someSettings = settings;
// this overwrites the original
settings.img = ['img/img1.jpg','img/img1.jpg','img/img1.jpg','img/img1.jpg'];
someSettings.img = ['boe'];

console.log('settings');
console.log(settings);
console.log('someSettings');
console.log(someSettings);


// creating an object as a function
var settingsObj = function(){

this.width = '100';
this.height = '200';
this.img = ['img/img1.jpg'];
return this;
}


// instantiating the settingsObj twice (copies)
var mySettings1 = new settingsObj;
var mySettings2 = new settingsObj;

var testSettings = settingsObj();

// give first instance a new value
mySettings1.img = ['img/img1.jpg','img/img1.jpg','img/img1.jpg','img/img1.jpg'];

console.log('mySettings1.img:');
console.log(mySettings1.img);
console.log('mySettings2.img:');
console.log(mySettings2.img);
console.log('testSettings.img:');
console.log(testSettings.img);


// make a function that does a simple calculation
function test(i) {
this.value = 5;
return this.value*i;
}

// store result in a variable
var myTest = test(5);
console.log('myTest: '+myTest);
var myTest2 = test(10);
console.log('myTest2: '+myTest2);





/*
* Binding events to elements
*/

$('#my_button').bind({
click : function(){
console.log('clicked');
},
mouseenter : function(){
console.log('mouseenter');

var my_div = $('<div>This is my div</div>');
$('#container').append(my_div);
my_div.slideUp().fadeIn();

console.log(this);

// binding mouseleave inside mouseenter
// this way I have access to the variable my_div
$(this).bind({
mouseleave : function(){
my_div.fadeOut();
}
});
},
mouseleave : function(){
// binding mouseleave again
console.log('mouseleave');
}
});




// difference between each() and for() and while()
var arraylength = myArray.length;

// for loop
for(i = 0; i < arraylength; i++){
console.log(myArray[i]);
}

// while loop
var k = -1;
while(++k < arraylength){
console.log('testing while:');
console.log(myArray[k]);
}

// each() notiation 1
$(myArray).each(function(key, value){
console.log(key, value);
});

// each() notation 2
$.each(myArray, function(key, some){
console.log(key, some);
});

// jquery notation for array length (length is native JS)
console.log($(myArray).length);




Monday, September 5, 2011

Google map using Javascript

To show the google map in our website using javascript, first we need to register Google map API and need to provide the API key in the below code.


<div id="map" style="width: 400px; height: 300px"></div>

<script type="text/javascript">
<script src="http://maps.google.com/maps?file=api&v=1&key=REGISTERED_API_KEY_HERE" type="text/javascript"></script>
var map = new GMap(document.getElementById("map")); var point = GPoint(17.0477624,80.0981869); var address = 'L.B.Nagar | Hyderabad'; var mark = createInfoMarker(point, address); map.addOverlay(mark); function createInfoMarker(point, address) { var marker = new GMarker(point); map.centerAndZoom(point, 3); GEvent.addListener(marker, "click", function() { marker.openInfoWindowHtml(address); } ); return marker; } </script>






Monday, August 8, 2011

count of checkboxes selected using javascript

Below is the code to know the number of checkboxes selected in a form. The function returns the total count of the Checkbox checked.

<script type="text/javascript">
function anyCheck(form) {
var total = 0;
var Count = document.playlist.count.value;
for (var idx = 1; idx < Count; idx++) {
if (eval("document.playlist.ckbox" + idx + ".checked") == true) {
total += 1;
}
}
alert("You selected " + total + " boxes.");
}
</script>
<form method="post" name=playlist>
1<input type=checkbox name=ckbox>
<br>2<input type="checkbox" name="ckbox1" onchange="anyCheck(this.value)">
<br>3<input type="checkbox" name="ckbox2" onchange="anyCheck(this.value)">
<br>4<input type="checkbox" name="ckbox3" onchange="anyCheck(this.value)">
<br>5<input type="checkbox" name="ckbox4" onchange="anyCheck(this.value)">
<br>6<input type="checkbox" name="ckbox5" onchange="anyCheck(this.value)">
<br>7<input type="checkbox" name="ckbox6" onchange="anyCheck(this.value)">
<br>8<input type="checkbox" name="ckbox7" onchange="anyCheck(this.value)">
<br>9<input type="checkbox" name="ckbox8" onchange="anyCheck(this.value)" >
<input type="hidden" value="8" name="count">
</form>


Wednesday, June 1, 2011

include a javascript file in js file

Code to include a js file in another js file.

var js1 = document.createElement('script');
js1.type = 'text/javascript';
js1.src = 'js1.js';

var headEl = document.getElementsByTagName('head')[0];
headEl.appendChild(js1);





Saturday, April 23, 2011

Limit the text area using Javascript


 To limit the textarea using javascript, we can use the below simple code which limits the textarea characters.

function textLimit(field, maxlen) {
        if (field.value.length > maxlen + 1)
            alert('Total Length is only '+ maxlen +' Characters');
        if (field.value.length > maxlen)
            field.value = field.value.substring(0, maxlen);
    }

and the code to be used in the textarea is shown below.

<textarea name='address'  cols='28' rows='4'  onkeyup="textLimit(this,350)"></textarea>






Saturday, March 5, 2011

Photoshop Shortcuts

Photoshop shortcuts. Please check the below image for the photograph shortcuts. This may help you.

If I miss any of them, please make a comment so that I can also know it.





 

Wednesday, February 23, 2011

Change Page title using Javascript

Code to change the Page title using Javascript is shown below.

document.title = 'Page Title has been Changed using Javascript';


Monday, September 27, 2010

Date Validation using Javascript

Here is the validation for date using javascript.

var dtCh= "/";
var minYear=1900;
var maxYear=2100;

function isInteger(s){
    var i;
    for (i = 0; i < s.length; i++){  
        // Check that current character is number.
        var c = s.charAt(i);
        if (((c < "0") || (c > "9"))) return false;
    }
    // All characters are numbers.
    return true;
}

function stripCharsInBag(s, bag){
    var i;
    var returnString = "";
    // Search through string's characters one by one.
    // If character is not in bag, append to returnString.
    for (i = 0; i < s.length; i++){  
        var c = s.charAt(i);
        if (bag.indexOf(c) == -1) returnString += c;
    }
    return returnString;
}

function daysInFebruary (year){
    // February has 29 days in any year evenly divisible by four,
    // EXCEPT for centurial years which are not also divisible by 400.
    return (((year % 4 == 0) && ( (!(year % 100 == 0)) || (year % 400 == 0))) ? 29 : 28 );
}
function DaysArray(n) {
    for (var i = 1; i <= n; i++) {
        this[i] = 31;
        if (i==4 || i==6 || i==9 || i==11) {this[i] = 30;}
        if (i==2){this[i] = 29;}
   }
   return this;
}

function isDate(dtStr){
    var daysInMonth = DaysArray(12);
    var pos1=dtStr.indexOf(dtCh);
    var pos2=dtStr.indexOf(dtCh,pos1+1);
    var strMonth=dtStr.substring(0,pos1);
    var strDay=dtStr.substring(pos1+1,pos2);
    var strYear=dtStr.substring(pos2+1);
    strYr=strYear;
    if (strDay.charAt(0)=="0" && strDay.length>1) strDay=strDay.substring(1);
    if (strMonth.charAt(0)=="0" && strMonth.length>1) strMonth=strMonth.substring(1);
    for (var i = 1; i <= 3; i++) {
        if (strYr.charAt(0)=="0" && strYr.length>1) strYr=strYr.substring(1);
    }
    month=parseInt(strMonth);
    day=parseInt(strDay);
    year=parseInt(strYr);
    if (pos1==-1 || pos2==-1){
        alert("The date format should be : mm/dd/yyyy");
        return false;
    }
    if (strMonth.length<1 || month<1 || month>12){
        alert("Please enter a valid month");
        document.form1.month.focus();
        return false;
    }
    if (strDay.length<1 || day<1 || day>31 || (month==2 && day>daysInFebruary(year)) || day > daysInMonth[month]){
        alert("Please enter a valid day");
        document.form1.day.focus();
        return false;
    }
    if (strYear.length != 4 || year==0 || year<minYear || year>maxYear){
        alert("Please enter a valid 4 digit year between "+minYear+" and "+maxYear);
        return false;
    }
    if (dtStr.indexOf(dtCh,pos2+1)!=-1 || isInteger(stripCharsInBag(dtStr, dtCh))==false){
        alert("Please enter a valid date");
        return false;
    }
    return true;
}

To check the given string is a Date or not, the date format should be checked as shown below.

var dt = document.form1.month.value +'/' +document.form1.day.value +'/'+ document.form1.year.value;
    if (isDate(dt)==false){
        return false;
    }

The date format to be passed is MM/DD/YYYY.

     

Friday, September 3, 2010

Get the Meta Content using Javascript

Here is the code for retrieving the Meta Keywords, Description using Javascript.

var destination = window.location.href;
var meta_title = '',meta_description = '';
       var meta = document.getElementsByTagName("meta");
       for( var x in meta )
       {
               if(/^title$/i.test(meta[x]["name"]))
                       meta_title = meta[x]["content"];
               if(/^description$/i.test(meta[x]["name"]))
                       meta_description = meta[x]["content"];
       }