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

Thursday, 6 August 2015

Avoid spaces being submitted in the script using jQuery

Leave a Comment

When we create any application using textfields it is possible that user may click on the submit button without entering any values in the textfield. We can restrict this easily simply by using if condition and double quotes like.

var name = $("#textfield").val();
if(name == ""){
alert("Please enter text in the text box");
}

But what if user presses spacebar a couple of times in the textfield and submits. This time the above code does not work. It will not alert the message instead it considers it as a value and executes the rest of the script. In this case we will get a null value submitted.


To stop user from entering null values ie spaces and submitting the form. We can trim the value first. That is we will remove the empty spaces. It can be done using jQuery trim statement.

var name = $("#textfield").val();
if($.trim(name) == ""){
alert("Please enter text in the text box");
}

Now the value gets trimmed and null values are avoided.

Read More...

Show remaining characters to be entered in textarea using jQuery

Leave a Comment

Some websites like Twitter limit number of characters that are typed in textarea. We can also see the remaining number of characters left for typing. This kind of feature can be easily implemented using jQuery.

Create a textarea  with id, cols, rows and maxlength attributes. In this example we will limit number of character to 25. Create a span with id. This span tag shows the number of characters remaining in textarea.

<textarea id="textarea" cols="20" rows="5" maxlength="25"></textarea>
Remaining Characters <span id="remain">25</span>

Now the jQuery part, here we should use .keyup event trigger in jQuery to capture every key release by the user in textarea. Create a new variable max, this is the maximum number of characters we can enter in the textarea. Now use if condition to check the characters entered in the textarea is less than or equal to 25 ie max variable. If condition is true, then subtract the number of characters in the textarea from max. Finally display that value in span tag. Thats it.

$("#textarea").keyup(function(){
var max = 25;
if($(this).val().length <= max)
var let = max - $(this).val().length;
$("#remain").text(let);
});

Lets see the full code

<textarea id="textarea" cols="20" rows="5" maxlength="25"></textarea>
Remaining Characters <span id="remain">25</span>

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
<script>
$("#textarea").keyup(function(){
var max = 25;
if($(this).val().length <= max)
var let = max - $(this).val().length;
$("#remain").text(let);
});
</script>
Read More...

Add more text fields dynamically using jQuery

1 comment

Add more than one text fields with the click of a button in jQuery.

First create a div with id=”more”, inside it create an input field and close the div. Then create a button. When we click this button new text fields must be created on web page.

<div id="more">
<input type="text">
</div>
<button>More input fields</button>

Now jQuery part, write button click event and anonymous function. Now create a new variable $i and add html input tag to it. We want to get more input fields when button is clicked in the div with id=”more”. So append the $i to div. Thats it.

$("button").click(function(){
var $i = "<br><input type='text'>";
$("#more").append($i);
});

Let’s look at the full code

<div id="more">
<input type="text">
</div>
<button>More input fields</button>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
<script>
$("button").click(function(){
var $i = "<br><input type='text'>";
$("#more").append($i);
});
</script>
Read More...

Wednesday, 29 July 2015

Toggle two CSS classes using jQuery

Leave a Comment

First create two paragraphs and a button in HTML.

<h3>This is heading</h3>
<p>jQuery is a fast, small and feature-rich <b>JavaScript</b> library.</p>
<p>'Write less: Do more'</p>
<button id="button">Click here to toggle classes</button>

Now create two different classes in CSS.

<style>
.clr1{
background-color:#CCF;
color:#60F;
}
.clr2{
background-color:#FC3;
color:#360;
}
</style>

Now the jQuery part. Here we want to toggle the classes when button is pressed. Lets see how its done.

$(document).ready(function() {
$("p").addClass("clr1");
$("#button").click(function(){
$("p").toggleClass("clr1 clr2");
});
});

Lets look at the full code.

<style>
.clr1{
background-color:#CCF;
color:#60F;
}
.clr2{
background-color:#FC3;
color:#360;
}
</style>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
<script>
$(document).ready(function() {
$("p").addClass("clr1");
$("#button").click(function(){
$("p").toggleClass("clr1 clr2");
});
});
</script>

<h3>This is heading</h3>
<p>jQuery is a fast, small and feature-rich <b>JavaScript</b> library.</p>
<p>'Write less: Do more'</p>
<button id="button">Click here to toggle classes</button>

That’s it. Now when you press the button paragraph color is changed or toggled between two classes.

Read More...

Monday, 27 July 2015

Change the color to red if text exceeds the limit in textarea using jQuery

Leave a Comment

First we should know that by using maxlength attribute in textarea we can limit the characters without using any additional coding.

Here is the code for maxlength attribute in textarea. Click here for demo.

<textarea rows="4" cols="50" maxlength="15">
Enter text here...</textarea>

For our example lets create a simple textarea with cols=”20” and rows=”5”, give it an id="mytextarea".

<textarea id="mytextarea" cols="20" rows="5"></textarea>

Now the jQuery part, add the jquery library and we will start coding.

$("#mytextarea").keyup(function(){

var maxlength = 15; // specify the maximum length

if($("#mytextarea").val().length > maxlength){
$("#mytextarea").css('color','red');
}
else{
$("#mytextarea").css('color','black');
}
});

In the above code keyup event occurs whenever key is released. So we are calling anonymous function whenever key is released. We are limiting text in textarea to 15 characters ie maxlength. If text in textarea is greater than 15 ie maxlength, then change text color to red else black. Everything is self explanatory. That’s it.


Let’s look at full code.

<textarea id="mytextarea" cols="20" rows="5"></textarea>

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
<script language="JavaScript"><!--
$("#mytextarea").keyup(function(){
var maxlength = 15; // specify the maximum length
if($("#mytextarea").val().length > maxlength){
$("#mytextarea").css('color','red');
}
else{
$("#mytextarea").css('color','black');
}
});
</script>
Read More...

Count number of paragraphs inside a div using jQuery

Leave a Comment

We need to count how many elements present in the page. How do we do this in jQuery?

var count = $("*").length;
alert(count);

In the above code * indicates all elements present on the page and .length is the count of all elements.


Now suppose we have div element with two paragraphs tags and a span tag inside it.

<div id="area">
<p>Paragraph one</p>
<p>Paragraph two</p>
<span></span>
</div>

Now I want to count paragraphs present in the div element. Here we are not bothered about the elements outside the div element but only inside. We can do it like this.

var count = $("#area").find("p").length;
alert(count);

Now the output will be 2.

Read More...

Sunday, 26 July 2015

Insert data into MYSQL database using jQuery, Ajax, PHP, MYSQL

Leave a Comment

Create a HTML form with id=”myform”, action=”userinfo.php”, and method=”post”. Add name and age text fields and add name attribute. Create a button, give it id=”sub”. Finally create a span with id=”result” and close it.

<form id="myform" action="userinfo.php" method="post">
Name:<input type="text" name="name"><br>
Age:<input type="text" name="age"><br>
<button id="sub">Save</button>
<span id="result"></span>

Create a new PHP file name it as userinfo.php. Write database connections and select the database. Now get the posted values in variables. Finally execute the MYSQL statement and echo the output.

<?php
//userinfo.php file
//Database connection
$conn = mysql_connect('localhost','root','');
$db = mysql_select_db('test');

//Posted values
$name = $_POST['name'];
$age = $_POST['age'];

if(mysql_query("Insert into user values('$name', '$age')"))
echo "Successfully inserted";
else
echo "Insertion failed";
?>

Now write the jQuery script, first we need to serialize the data taken from input boxes. Then post them using jQuery post method and append the result in span tags.

$("#sub").click(function(){
var data = $("#myform :input").serializeArray();
$.post( $("#myform").attr("action"), data, function(info){
$("#result").html(info);
clearinput();
});
});

In the above code clearinput() is the function we will talk about it later. Now when the form is submitted it should not redirect to PHP page. So we write the following code.

$("#myform").submit(function(){
return false;
});

Now every thing is fine. But the text fields are to be cleared when form is submitted. So we will write a code to clear the text fields. We will write clearinput() function to clear the fields.

function clearinput(){
$("#myform :input").each(function(){
$(this).val('');
});
}

Now let’s see the full code in one place.

<form id="myform" action="userinfo.php" method="post">
Name:<input type="text" name="name"><br>
Age:<input type="text" name="age"><br>
<button id="sub">Save</button>
<span id="result"></span>

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>

<script>
$("#sub").click(function(){
var data = $("#myform :input").serializeArray();
$.post( $("#myform").attr("action"), data, function(info){
$("#result").html(info);
clearinput();
});
});

$("#myform").submit(function(){
return false;
});

function clearinput(){
$("#myform :input").each(function(){
$(this).val('');
});
}
</script>
Read More...

Create a textarea with word count using jQuery and PHP

Leave a Comment

First create a textarea and give it id and name. Add text “Word Count:” and a span tag with id “count” like shown below.

<textarea cols="20" rows="5" name="textarea" id="textarea"></textarea>
<br>Word count: <span id="count"></span>

Now we will write jQuery code so you need to add jQuery library.  We will use the keyup event in the jQuery to call function. So whenever key is released we will call anonymous function to execute the code.

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
<script>
$("#textarea").keyup(function(){

});
</script>

Here we are calling a function whenever we type a character in textarea ie., to count number of words typed in the textarea. Now whenever we type character in textarea we need to count number of words present in the textarea.


We have a built-in function in PHP to count the number of words. So now we should send the typed words to the PHP script and get the output. We can do this using jQuery ajax method.

$.ajax({
url: 'count.php',
type: "POST",
data: {textarea:$("#textarea").val()},
dataType :'html',
success: function(result){
$("#count").empty();
$("#count").append(result);

},
error: function(){
alert("Ahh! something went wrong. Please try again after sometime.");
}
});

In the above code we are sending the data typed in the textarea to count.php file. If success append it to span tag else alert a message. Let’s see the count.php file.

<?php
$str = $_POST['textarea'];
$count = str_word_count($str);
echo $count;
?>

Since we are sending values using post method we are using $_POST in php to store the value in variable. str_word_count will count the number of words in variable $str. Finally output is echoed.


Let’s see the final code.

<textarea cols="20" rows="5" name="textarea" id="textarea"></textarea>
<br>Word count: <span id="count"></span>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
<script>
$("#textarea").keyup(function(){

$.ajax({
url: 'count.php',
type: "POST",
data: {textarea:$("#textarea").val()},
dataType :'html',
success: function(result){
$("#count").empty();
$("#count").append(result);
},
error: function(){
alert("Ahh! something went wrong. Please try again after sometime.");
}
});
</script>
Read More...
.