Showing posts with label JQUERY. Show all posts
Showing posts with label JQUERY. Show all posts

Monday, December 30, 2013

Javascript validation for dynamic element



Many time in web-application we come across the functionality to build - adding dynamic form elements and validating them. its pretty simple with .rules() and validate()


 var newElement = $('<input type="text" name="input' + count + '" value="" />');
            $('form').append(newElement);
            newElement.rules('add', {
                required: true,
                messages: {
                    required: 'This field is required'
                }
            });

and add this script and jQuery, using foreach() to retrieve the data being $_POST'ed:

<script type="text/javascript">
   $(document).ready(function() {
        var numberIncr = 1; // used to increment the name for the inputs

        function addInput() {
            $('#inputs').append($('<input class="comment" name="name'+numberIncr+'" />'));
            numberIncr++;
        }

        $('form.commentForm').on('submit', function(event) {

            // adding rules for inputs with class 'comment'
            $('input.comment').each(function() {
                $(this).rules("add", 
                    {
                        required: true
                    })
            });            

            // prevent default submit action         
            event.preventDefault();

            // test if form is valid 
            if($('form.commentForm').validate().form()) {
                console.log("validates");
            } else {
                console.log("does not validate");
            }
        })

        // set handler for addInput button click
        $("#addInput").on('click', addInput);

        // initialize the validator
        $('form.commentForm').validate();

   });


</script>



Know more about JAVASCRIPT, JQUERY, Form Validation, Validate
Hope you have enjoyed the post let us know your views.


Friday, April 19, 2013

5 ways to redirect URL with Javascript




5 ways to redirect URL with Javascript



some days before i was searching for a trick to force redirection of a page to java script event . how can we Redirect to an HTTP POST Request with Javascript? 

I summarized 5 ways to redirect URL(The purpose of below script is to perform a local redirect using Javascript).


way 1
 



way 2
 




way 3
 




way 4
 


way 5   
 




 







Hope you have enjoyed to read this post,
let me know if you have more suitable suggestions.




you might be more interested in JQUERY, JAVASCRIPT, TIPS AND TRICS.
want to know more about the author ?





Good Day [/ Night] ! Happy Google + ing !

Tuesday, April 9, 2013

Using jQuery String Functions

Using jQuery String Functions

 

 

Using jQuery String Functions






i was working on a project almost building on jQuery, and i came to know some interesting JQuery string functions that i never know before, here i am sharing some important JQuery functions, hope it will be worth sharing.



charAt(n): 

 Returns the character at the specified index in a string. The index starts from 0.



var str = "JQUERY By Example";
var n = str.charAt(2)

//Output will be "U"




charCodeAt(n): 
Returns the Unicode of the character at the specified index in a string. The index starts from 0.

var str = "HELLO WORLD";
var n = str.charCodeAt(0);

//Output will be "72"







concat(string1, string2, .., stringX):

 The concat() method is used to join two or more strings. This method does not change the existing strings, but returns a new string containing the text of the joined strings.



var str1 = "jQuery ";
var str2 = "By Example!";
var n = str1.concat(str2);

//Output will be "jQuery By Example!"





fromCharCode(n1, n2, ..., nX):

Converts Unicode values into characters. This is a static method of the String object, and the syntax is always String.fromCharCode().


var n = String.fromCharCode(65);

//Output will be "A"







indexOf(searchvalue, [start]): 
Returns the position of the first occurrence of a specified value in a string. This method returns -1 if the value to search for never occurs. This method is case sensitive!





var str="Hello world, welcome to the my blog.";
var n=str.indexOf("welcome");

//Output will be "13"







lastIndexOf(searchvalue, [start]): 
Returns the position of the last occurrence of a specified value in a string. The string is searched from the end to the beginning, but returns the index starting at the beginning, at postion 0. Returns -1 if the value to search for never occurs. This method is case sensitive!




var str="Hello planet earth, you are a great planet.";
var n=str.lastIndexOf("planet");

//Output will be "36"




substr(start, [length]):
The substr() method extracts parts of a string, beginning at the character at the specified posistion, and returns the specified number of characters.



var str="Hello world!";
var n=str.substr(2,3)

//Output will be "llo"









substring(from, [to]):
 The substring() method extracts the characters from a string, between two specified indices, and returns the new sub string. This method extracts the characters in a string between "from" and "to", not including "to" itself.






var str="Hello world!";
var n=str.substring(2,3)

//Output will be "l"




toLowerCase(): 
The toLowerCase() method converts a string to lowercase letters.



var str="HELLO WoRld!";
str = str.toLowerCase();
//Output will be "hello world!"









toUpperCase(): 
The toUpperCase() method converts a string to uppercase letters.



var str="hello WoRLd!";
str = str.toUpperCase();
//Output will be "HELLO WORLD!"








match(regexp): 
The match() method searches a string for a match against a regular expression, and returns the matches, as an Array object.




var str="The rain in SPAIN stays mainly in the plain"; 
var n=str.match(/ain/g);

//Output will be "ain,ain,ain"
//There are 3 matches with the "ain" regex in small letters. So it returns ain 3 times.




replace(searchvalue, newvalue):
The replace() method searches a string for a specified value, or a regular expression, and returns a new string where the specified values are replaced.



var str="Visit jQuery Blog!";
var n = str.replace("jQuery ","jQuery By Example ");

//Output will be "Visit jQuery By Example Blog!"







search(searchvalue): 
 The search() method searches a string for a specified value, or regular expression, and returns the position of the match. This method returns -1 if no match is found.



var str="Visit jQuery Blog!";
var n = str.search("jQuery");

//Output will be "6"












slice(start, [end]): 
The slice() method extract parts of a string and returns the extracted parts in a new string. Use the start and end parameters to specify the part of the string you want to extract. The first character has the position 0, the second has position 1, and so on.


var str="Visit jQuery Blog!";
var n = str.slice(6,12);

//Output will be "jQuery"







Hope you this post have summarized your view !
U might have more interest in JavaScript String Functions, jQuery, jQuery String Functions,String Functions.

Happy Google + ing !

Good Day !



Wednesday, April 3, 2013

How to Add Maxlength On TextArea Using JQuery

How to Add Maxlength On TextArea Using JQuery

How to Add Maxlength On TextArea Using JQuery


here is the pretty good and easy to understood code for making textarea working with maxlength property.


JQuery Code :
 

 
    $(document).ready( function () {
 
	maxLength = $("textarea#comment").attr("maxlength");
        $("textarea#comment").after("
" + maxLength + " remaining
"); $("textarea#comment").bind("keyup change", function(){checkMaxLength(this.id, maxLength); } ) }); function checkMaxLength(textareaID, maxLength){ currentLengthInTextarea = $("#"+textareaID).val().length; $(remainingLengthTempId).text(parseInt(maxLength) - parseInt(currentLengthInTextarea)); if (currentLengthInTextarea > (maxLength)) { // Trim the field current length over the maxlength. $("textarea#comment").val($("textarea#comment").val().slice(0, maxLength)); $(remainingLengthTempId).text(0); } }

HTML Code :
 
<body>

<h1>TextArea maxlength with jQuery</h1>

<textarea id="comment" maxlength="10" rows="10" cols="60" ></textarea>

</body>

Working Demo



Any more Questions ? let me know with comments.
for projects write me at bhavinrana07@gmail.com



Monday, October 15, 2012

JQuery set to tackle mobile Web development

The JavaScript-based tools for Web development are widely used for desktop and laptop browsers. JQuery Mobile will let coders reach mobile phones, too. read Main Article.
Countless developers use jQuery software tools today to build advanced Web sites  and to ease the difficulties of spanning multiple browsers. 


Cheers !
Hope you got the Ans !
still having probs ? let me know by comments !

Know More About :
PHP Freelancing India

Saturday, September 8, 2012

How can I check if one string contains another substring in JavaScript? JavaScript: string contains

Q. How can I check if one string contains another substring in JavaScript?








Usually I would expect a String.contains() method, but there doesn't seem to be one.

My code is:

var allLinks = content.document.getElementsByTagName("a");

for (var i=0, il=allLinks.length; i<il; i++) {
   
   elm = allLinks[i];
   var test = elm.getAttribute("class");
   if (test.indexof("title") !=-1) {
   alert(elm);
   foundLinks++;

}
}

if (foundLinks === 0) {
   alert("No title class found");
}
else {
   alert("Found " + foundLinks + " title class");
}



Solution :



var s = "foo";
alert(s.indexOf("oo") != -1);

indexOf returns the position of the string in the other string. If not found, it will return -1.





Cheers !
Hope you got the Ans !
still having probs ? let me know by comments !

Know More About :
PHP Freelancing India


Friday, September 7, 2012

Monday, September 3, 2012

How do I check a checkbox with jQuery or JavaScript?


How do I check a checkbox with jQuery or JavaScript?

 
jQuery 1.6+


: Solution : 

Use the new .prop() function:
$(".myCheckbox").prop("checked", true);
$(".myCheckbox").prop("checked", false);


jQuery 1.5 and below

The .prop() function is not available, so you need to use .attr().

To check the checkbox (by setting the value of the checked attribute) do $('.myCheckbox').attr('checked','checked')



and for un-checking (by removing the attribute entirely) do $('.myCheckbox').removeAttr('checked')


Any version of jQuery

If you're working with just one element, it will always be fastest to use DOMElement.checked = true. The benefit to using the .prop() and .attr() functions is that they will operate on all matched elements.


if (this.checked) 
// Assuming an event handler on a checkbox




:D
Steel facing probs ? let me know by comments !

Know More About :
PHP Freelancing India


Saturday, September 1, 2012

Check checkbox checked property using jQuery

Check checkbox checked property using jQuery,  check the checkbox checked with JQuery


Solution :

if ($('#isAgeSelected').is(':checked')) {
$("#txtAge").show();
} else {
$("#txtAge").hide();
}

You can shorten this using ternary, some might say it's a bit less readable, but that's how I would do it:$('#isAgeSelected').is(':checked') ? $("#txtAge").show() : $("#txtAge").hide();


here's a much prettier way to do this, using  
toggle:

$('#isAgeSelected').click(function () {
$("#txtAge").toggle(this.checked);
});
<input type="checkbox" id="isAgeSelected"/>
<div id="txtAge" style="display:none">Age is something</div>​


Cheers !
Hope you got the Ans !
still having probs ? let me know by comments !

Know More About :
PHP Freelancing India


Friday, August 31, 2012

Get query string values in JavaScript

Is there a plugin-less way of retrieving query string values via jQuery (or without)?

If so, how, and if not what plugin do you recommend?
You don't need jQuery for that purpose you can use the pure JavaScript


function getParameterByName(name)
{
name = name.replace(/[\[]/, "\\\[").replace(/[\]]/, "\\\]");
var regexS = "[\\?&]" + name + "=([^&#]*)";
var regex = new RegExp(regexS);
var results = regex.exec(window.location.search);
if(results == null)
return "";
else
return decodeURIComponent(results[1].replace(/\+/g, " "));
}


Cheers ! 
Hope you got the Ans ! 
still having probs ? let me know by comments ! 



Know More About :

Thursday, August 30, 2012

Testing if something is hidden with jQuery, Check Form Element is hidden



Testing if something is hidden with jQuery, Check Form Element is hidden



In jQuery, suppose you have an element of some kind that you're hiding and showing, using .hide(),.show() or .toggle(). How do you test to see if that element is currently hidden or visible on the screen?


$(element).is(":visible") 




Hope you got the Ans !
still having probs ? let me know by comments !




Know More About :
PHP Freelancing India 

Tuesday, August 28, 2012

How to get select radiobutton value using its name in jQuery? Getting the value of a selected radio button out of a radio group in jQuery.

How to get select radiobutton value using its name in jQuery? 

Getting the value of a selected radio button out of a radio group in jQuery.



Just want to point out that Jeff's answer might suit others because it can be used to get the value from anywhere, not just within a click handler for the radio button. here is preety simple solution. 

$('input:radio[name=theme]:checked').val();



:D 
Steel facing probs ? let me know by comments ! 




Know More About :
PHP Freelancing India 


Saturday, September 24, 2011

Submit Form Using Ajax (Post)


Hi Googler,
here is some code , will be helpfull in submit form using ajax post.
you need to create following files. 


Post.html





<script type="text/javascript" language="javascript">// <![CDATA[
var h_request = false;
function makePOSTRequest(url, parameters) {
h_request = false;

<!--more-->

if (window.XMLHttpRequest) //MOZILLA
{
h_request = new XMLHttpRequest();
if (h_request.overrideMimeType)
{
h_request.overrideMimeType('text/html');
}
}
else if (window.ActiveXObject) { // IE
try {
h_request = new ActiveXObject("Msxml2.XMLHTTP");
} catch (e) {
try {
h_request = new ActiveXObject("Microsoft.XMLHTTP");
} catch (e) {}
}
}
if (!h_request) {
alert('Cannot create XMLHTTP instance');
return false;
}

h_request.onreadystatechange = alertContents;
h_request.open('POST', url, true);
h_request.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
h_request.setRequestHeader("Content-length", parameters.length);
h_request.setRequestHeader("Connection", "close");
h_request.send(parameters);
}

function alertContents() {
if (h_request.readyState == 4) {
if (h_request.status == 200) {
result = h_request.responseText;
document.getElementById('myspan').innerHTML = result;
} else {
alert('There was a problem with the request.');
}
}
}

function get(obj) {
var poststr = "mytextarea1=" + encodeURI( document.getElementById("mytextarea1").value ) +
"&mytextarea2=" + encodeURI( document.getElementById("mytextarea2").value );
makePOSTRequest('post.php', poststr);
}

// ]]></script>

<form action="javascript:get(document.getElementById('form1'));" name="form1" id="form1">
<textarea id="mytextarea1">testing data
1
2
3
</textarea>
<textarea id="mytextarea2">testing data 2
4
5
6</textarea>
<br>
<input type="button" name="button" value="Submit"
onclick="javascript:get(this.parentNode);">

</form>

<br><br>
Server-Response:<br>
<hr>
<span name="myspan" id="myspan"></span>
<hr>
Post.php
<?
print_r($_POST);
?>


Hope post helped you.
for questions comment on this.


:D

Know More About :
PHP Freelancing India

Tuesday, September 20, 2011

Speed up Page Load by reducing HTTP requests with PHP


Hi Googler,


A nice technique to speed up your page loading times is to try to reduce the amount of calls your browsers has to make to the server. This will be every image, every css and every JavaScript file included in the webpage. Each time you want to load in one of these elements you will be sending a request to the server which will return the requested object known as a HTTP request.

Reduce Page Loading Time With PHP

Each one of these uses up time on your page loading, so to reduce page load all you have to do is reduce the amount of calls being made. But what if you want to organise you JavaScript files, jquery file, general file, application file and page file. There could be upto 4 requests for some javascript for the page.
It is possible in PHP to combine these JavaScript files together and trick the browser into thinking they are just one JavaScript file, therefore reducing the amount of calls being made to the server. This is done by reading the JavaScript with PHP then changing the header to JavaScript like the example below.
Create a PHP file and use the readfile function to bring in your Javascript files then change the header to Javascript and the server will treat this page as Javascript.


readfile(jquery.js');
readfile(general.js');
readfile(jquery-ui.js');
readfile(page.js');
header('Content-type: text/javascript');

The above technique can also be used with CSS files or a combination of them both.

hope this post helped,
any questions ? let me know by comments ..
:D 

Sunday, July 17, 2011

Find nth Parent Div using jQuery


Hello Friends,
Are you looking for finding the parent div in easiest way using jQuery ? You can easily find parent div element using jQuery. Look at below link for parent functionality of jQuery. You can find nth div element using this parent function. Look at below code for 2nd parent div. In the same way you can find the nth parent HTML element.
$(this).parent().parent().attr(“id”);
If you find any problem in this than let me know by comment.

Move (Copy) Div from one place to another using jQuery


Hello Friends,
jQuery is very useful while you develop any web application. Whatever you can do with jQuery is not enough, you should know much more and implement more and more with jQuery. Yesterday i need to move one of my “Pending” record to “Paid” records section once i click on selectbox and change the record to “Paid” status. I can do it by creating new HTMLand append it to paid records list. But i came to know about Clonefunctionality of jQuery. There are two possiblility in Clone function of jQuery. If you want to keep the Div at their place and create the same Div at some other place than you can go for Clone. If you want to Move the Div from one place to another than use appendTo. Look at below syntax.
$(“div#source_div_id”).appendTo(“div#destination_div_id”);
 If you find any problem in this than let me know by comment.

About

Professional & Experienced Freelance Developer From India, Technologist, Software Engineer, internet marketer and Open Sources Developer with experience in Finance, Telecoms and the Media. Contact Me for freelancing projects.

Enter your email address:

Delivered by FeedBurner