How to make the first letter of a string uppercase using JavaScript

Syntax

string.charAt(index)

Definition and Usage

charAt() is a very useful function in Javascript and all the related Object Oriented Programming concepts. The function acts to extract and return individual characters at a designated index on a particular string. It however acts with taking the first character of a string to be as 0. This is very useful to calculate the positions of a string, especially to calculate the position and length of a phrase or a word. The chief criteria of using this function should be the length from 0 to length()-1.

s.chartAt(1)

This will return the 2nd character index of a string.

However, the function follows certain set of exceptions, of which the most commonly observed is the IndexOutOfBoundsException. This parameter appears in the comment line section if the array index is lesser than 0 or is greater than or equal to that of the length().

Example explaining charAt() to convert the first letter of a string to uppercase using javascript.

Example

<script>

    // Define function to capitalize the first letter of a string

    function capitalizeFirstLetter(string){

        return string.charAt(0).toUpperCase() + string.slice(1);

    }

    

    // Calling function and display the result

    var str1 = 'hi there!';

    str1 = capitalizeFirstLetter(str1);

    document.write(str1); // Print: Hi there!

    

    var str2 = 'the Gods must be crazy.';

    str2 = capitalizeFirstLetter(str2);

    document.write(str2); // Print: The Gods must be crazy.

    

    var str3 = '/app/index.html';

    str2 = capitalizeFirstLetter(str3);

    document.write(str3); // Print: /app/index.html

</script>

In this code, a non-void returnable function with a string parameter is passed. The string character is returned with the first index, which is 0 and called by the charAt(0). This is converted to uppercase using toUpperCase() function.

Moreover, the presence of slice() function, allows to extract parts of a string and returns a newer string.

Next part is the function calling, where the result of a function is displayed. Mostly, the function is used as a one-step measure to convert the input string.

For an instance, “hi there!” is stored in string called str1, which is called as a parameter inside the main function capitalizeFirstLetter. Thus, it prints “Hi there!” Similarly, the other strings, i.e. str2, str3 too gives away similar results with first character transformed to Upper Case.

charAt() function also works for looping parameters, where more than a small set of characters might be required to trigger and get extracted. However, the iterative process of looping should always have a maximum range to the length()-1 to that of the string value.

View Demo

Get the Value of TextArea using the jQuery Val () Method

Syntax

$(selector).val()

Definition and Usage

The Val( ) method is known to set or return the value attributes of the selected elements. This method is mainly used with the HTML form of elements.

Two Arguments for this method consists of:

  • When it is used to Return the Value: The Val( ) method returns the value of the ‘Value Attribute’ of the first matched elements.
  • When this method is used to Set the Value: It sets the value of the ‘Value Attribute’ of ‘ALL’ matched elements.

You can use this script in HTML to derive the value of ‘TextArea’ using the Val( ) Method of jQuery. It can be understood with the help of the following example.

Example

<!DOCTYPE html>

<html lang="en">

<head>

<meta charset="utf-8">

<title>Get Value from Textarea in jQuery</title>

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

<script>

    $(document).ready(function(){

        $("button").click(function(){

            var comment = $.trim($("#comment").val());

            if(comment != ""){

                // Show alert dialog if value is not blank

                alert(comment);

            }

        });

        

    });

</script>

</head>

<body>

    <textarea id="comment" rows="5" cols="50"></textarea>

    <p><button type="button">Get Value</button></p>

    <p><strong>Note:</strong> Type something in the textarea and click the button to see the result.</p>

</body>

</html>

The Val( ) method helps in getting the values from the elements like ‘input’, ‘select’ and the ‘textarea’. The value of each field here can be attained with the help of jQuery. In the above example, the script involves the usage of the jQuery and the comment button to receive the value in the TextArea. Here the text is an actual text and not an HTML element and values retrieved from the ‘form elements’.

In the Val( ) method, if you are not applying any parameters then you will get the desired property as the result. In addition, if you want to set the property instead of call, then you need to specify an extra parameter.

However, you must remove any kind of leading whitespace or the trailing while writing this script. So, you do not get an unexpected result as an outcome. This example helps in showing the value in the TextArea by showing it in the alert dialog box with the click of the button when this appears not equal to “ “.

View Demo

How to Check if the Variable Exists or Defined in JavaScript

Definition and Usage

You can use the typeof( ) function to check the existence of variables and if it is defined in the JavaScript. The typeof( ) in JavaScript allows to look after the data type of its concerned ‘operand’. Here it is checked if the variable is numeric, string or undefined. The typeof operator returns the string, which recognizes data type of an expression. Here the ‘expression argument’ is any of the expressions for which typeof information is sought out.

Here is an example that will show how to check the existence of a variable or if it is defined in JavaScript.

Example

<script>

    var x;

    var y = 10;

    

    if(typeof x !== 'undefined'){

        // this statement will not execute

        alert("Variable x is defined.");

    }

    

    if(typeof y !== 'undefined'){

        // this statement will execute

        alert("Variable y is defined.");

    }

    

    // Attempt to access an undeclared z variable

    if(typeof z !== 'undefined'){

        // this statement will not execute

        alert("Variable z is defined.");

    }

    

    /* Throws Uncaught ReferenceError: z is not defined,

    and halt the execution of the script */

    if(z !== 'undefined'){

        // this statement will not execute

        alert("Variable z is defined.");

    }

    

    /* If the following statement runs, it will also

    throw the Uncaught ReferenceError: z is not defined */

    if(z){

        // this statement will not execute

        alert("Variable z is defined.");

    }

</script>

In the above example, it can be seen that by using typeof operator, you will come to know if the variable is defined or undefined. It will never show the ‘ReferenceError’ unless it is used with an ‘undeclared variable’. You can use the ‘defined test’ to see if the variable really exists in JavaScript that will provide the same outcome as in the example above where ‘Variable z’ is defined.

The typeof( ) will help them to know whether a variable has been initialized, which means that it has been assigned some value or declared while writing in the JavaScript. However, if he makes a mistake then the variable may remain undefined.

The typeof( ) function of JavaScript helps in checking out variables and defining the script by carrying out few expressions as:

  • It checks out whether the variable has been declared or is still undefined.
  • The typeof operator checks out the missing parameters, uninitialized variables and non-existent properties.
  • While writing the variable in JavaScript the developer must see that the value is neither null nor undefined. The introduction of ‘default operator’ will also tell about the ‘default value’ or in case ‘myValue’ is not defined
  • Apart from checking the existence of variables, other typeof values that are returned include the ‘object’, ‘Boolean’, ‘function’, ‘number’, ‘string’ and ‘undefined’ values.

While writing the script, the parentheses can be optional in the ‘typeof’ syntax.

View Demo

Changing the Background Color of the Web Page Dynamically in JavaScript

Syntax

object.style.backgroundColor

The Style Property helps in changing the background color of the Web Page dynamically in the JavaScript. It returns the ‘CSS Style Declaration Object’ that highlights the style attributes of a particular element. Moreover, the Style Property is used to set or even get a specific style of an element using various CSS properties.

If you want to change the background color of a Web page or the <body> element or even any other element in the JavaScript then ‘Style Property’ dynamically carries out this change. The style property sets and gets the ‘inline style’ of the elements. Even any of the HTML elements, which support style attributes, also possess the style property. It can be cleared with the help of an example.

Example

<!DOCTYPE html>

<html lang="en">

<head>

<meta charset="utf-8">

<title>Change the Background Color with JavaScript</title>

<script>

    // Function to change webpage background color

    function changeBodyBg(color){

        document.body.style.background = color;

    }

    

    // Function to change heading background color

    function changeHeadingBg(color){

        document.getElementById("heading").style.background = color;

    }

</script>

</head>

<body>

The above example clearly shows that the style property helps in changing the web page color with the applicability of this function. However, in any case, if you are using a DIV container or any other element then one needs to modify the background of that element instead of the web page document body.

Here one thing worth noting is that it is not possible to set the styles in JavaScript by assigning a string in the ‘Style Property’. The style property is said to return only the CSS declarations but this property does not give any vital information about the style rules or their applicability. Moreover, you cannot get information about the style rules used in the <head> section of any of the document or the external style sheets.

The example provided above shows that the usage of ‘style property’ instead of any kind of element attributes will help in not overwriting the CSS properties that may be otherwise specified in any of the style attributes used while designing the Web Page.

Even another important point relative to the style property is that if it is applied to any element then it only provides back its value. Like, if you want to change the background color of a specific web page or just the text body then ‘style property’ applicability will help in carrying out the needful.

View Demo

How To Detect If Enter Key Is Pressed In A Text Input Field Using Jquery

Syntax

$(selector).keypress()

jQuery and programming have some of the most important functions associated with triggering or activating a certain set of events and functions. Likewise, if there is an instance, which might require the user to check whether an event function is activated or not, is performed using the keypress() function.

With this function, you can simply detect a function is called to run, when a keypress event gets going. Yet, keypress() cannot be used for detecting all the keys in the keyboard, with some exceptions being alt, ctrl, esc, shift, etc. Like any other inbuilt functions in jQuery, keypress() is a parameterized operation, and a parameter can be called within the scope of the function.

Following code demonstrate how to check if the enter key is pressed in a text input field in jQuery.

Example

<!DOCTYPE html>

<html lang="en">

<head>

<meta charset="utf-8">

<title>Detect the Enter Key in a Text Input Field with jQuery</title>

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

<script>

    $(document).on("keypress", "input", function(e){

        if(e.which == 13){

            var inputVal = $(this).val();

            alert("You've entered: " + inputVal);

        }

    });

</script>

</head>

<body>

    <p><strong>Note:</strong> Type something in the text input box and press enter key.</p>      

    <p><input type="text"></p>      

</body>

</html>

Now, taking the side of the code, the source script has the document, which takes the function help of keypress and input space with respect to function e. In the forthcoming statements, the value of e is taken and is checked whether is equal to key code number “13.” Now 13 is the code of the function combination keypress, and with the assistance of which function e is compared for any blank space.

Following the checked value, the inputVal variable is taken and the value of the function is merged with the previous check, this will ensure to give an alert, that will come up and state “you have entered: <blank space>.

Why is the function useful? The answer is the utility scope, which will allow the user to get more space and not to give unnecessary blank space in every application. The usage of ASCII codes comes to the savior and makes easy out amends for coding simplicity. Likewise, in the program code above, the usage of ASCII values have ensured the blank space, formed as for pressing enter key is easily rectified.

Almost all of the up-to-date OOP supported programming languages are today, equipped, contains packages of both functions, and accepts ASCII values, which is considered the global search code. The entire set of codes contains numerous utilities and data input values embedded with different values.

View Demo

How to detect enter key press on keyboard with jQuery

Syntax

$(selector).keypress()

Definition and Usage

jQuery is a complete application version of Java, which like any other programming language, is particular with the keys and applications of each of them. There are specific scenarios, where a developer might be skeptical on whether he/she have assured to develop the “Enter” key properties in the code. Enter Key in any computing applications is considered the most valuable form to send and transmit data.

For the same reason, there is a very useful and a specific way, which requires the application of an ASCII Code called as key code 13. This is equivalent to Enter and most of the modern-day browsers allow the usage and application of the same.

Here is the code, which works to accept the enter key on a keyboard.

Example

<!DOCTYPE html>

<html lang="en">

<head>

<meta charset="utf-8">

<title>Check if Enter Key is Pressed with jQuery</title>

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

<script>

    $(document).on("keypress", function(e){

        if(e.which == 13){

            $("body").append("<p>You've pressed the enter key!</p>");

        }

    });

</script>

</head>

<body>

    <p><strong>Note:</strong> Click on the viewport and press the Enter key on the keyboard. A message will be displayed.</p>

</body>

</html>

Here, we see the source code under the script menu, where the program is asking the user to input or press the enter key and the “append” function (e) is used to accept all the possible outcomes. Inside the function, e checks whether the code is equivalent to 13. If the answer of the “if” statement is affirmative, the function will once again append the enter key inside the main script body.

In the main case, the requirement of a statement or function event is required, which will then be appended to the enter key. Thus, the function box e is taken i to consideration, which works for a script called document and the function “on” is emphasized. Finally, in the end of a code, the main body of a program is appended to the print statement.

ASCII codes and its applications play a huge part in programming logic control. The usage of these codes simplifies functions and allows the programmers to manipulate just by using the appropriate codes. In Object Oriented Programming concepts, ASCII is used in every possible junctures for different keys and set of operations. Here in this case, the usage of “Enter” key plays a vital role in any application software, which will assure the user’s entry to proceed forward.

View Demo

How to Select Elements by Class Name in the JavaScript

Syntax

document.getElementsByClassName(classname)

Definition and Usage

Here, you can use the getElementsByClassName( ) for selecting the elements by class name in the JavaScript. This particular method returns a collection of all the elements in a specified document with a particular class name, provided as a NodeList object. The ‘NodeList’ object represents the collection of Nodes that can be accessed with the help of index numbers. Here, the ‘index number’ starts with “0”.

For using this object, one of the tips is that you can use ‘length property’ of the NodeList object to check out the number of elements provided in a specific Class Name. Then, you can loop through all provided elements in JavaScript and take out the information you require. This usage of the getElementsByClassName( ) can be seen with the help of the below-stated example.

Example

<!DOCTYPE html>

<html lang="en">

<head>

<meta charset="utf-8">

<title>Select Element by Class in JavaScript</title>

<style type="text/css">

    .box {

        height: 50px;

        background: #ddd;

        margin: 20px;

    }

    .box.bordered{

        border: 5px solid #333;

    }

</style>

</head>

<body>

    <div class="box"></div>

    <div class="box bordered"></div>

    <div class="box"></div>

    <div class="box bordered"></div>

    <div class="box"></div>

 

    <script>

        var boxes = document.getElementsByClassName("box");

    

        // Select first box and style it with red background

        boxes[0].style.background = "#CD5C5C";

    

        /* Select elements having both "box" and "bordered" class 

        and style them with yellow background */

        var borderedBoxes = document.getElementsByClassName("box bordered");

        for(var i = 0; i < borderedBoxes.length; i++){

            borderedBoxes[i].style.background = "#F08080";

        }

        // Select last element and style it with green background

        boxes[boxes.length - 1].style.background = "#FFA07A";

    </script>

</body>

</html>

In the above example, it is shown that getElementsByClassName( ) method returns an array of the matched elements as it can be seen here that more than one element in the JavaScript or a page can possess the same class. Moreover, the ‘classname’ is a parameter here in which the ‘String’ type is used. Therefore, the requirement that you will get involves Class Name of the elements that you want to receive in the JavaScript. One thing worth noting is here that if you want to search for ‘Multiple Class Names’ then it must be separated with the spaces like the “test demo”.

The method used in JavaScript to select the Class Name, which is getElementsByClassName also returns an ‘array-like object’ of all the provided child elements that possess all the given class names. Here when you will call on the ‘Document Object’, it will search a complete document that includes the ‘root node’ too.

As shown in the above example, state the getElementsByClassName( ) on any of the elements in JavaScript like the border, style, color, etc. This method will only return Elements that are the descendants of a specific ‘root element’ with its provided ‘Class Names’. This method is specifically supported in the latest browsers of the Internet Explorer or Firefox versions.

View Demo

How to determine if variable is undefined or null using JavaScript

JavaScript, is perhaps one of the most complex programming languages with some of the most abstract rules to name a few. However, the language, which is used predominantly to make JavaScript work is Java, has some of the most powerful tools and rules, which allows the programmer to think beyond the usual scope of programming all the way. One such rule is the usage of “==” or the equality operator.

Equality Operator is significantly used in situations, where a variable is checked with a numeric or even non-numeric value to be true or not. Unlike “=”, the values will not be stored for different variables, only the condition will be evaluated. Thus, with the equality operator, there is a simple way to check whether the variable is defined or is null.

The major difference between null and undefined is the value of any unassigned variable, which is simply used, results in the value to be undefined. Whereas, in case of null value, this is a popular special assignment value, with an ASCII value, and renders the variable it is assigned to have no value.

Example

script>

    var firstName;

    var lastName = null;

    // Try to get non existing DOM element

    var comment = document.getElementById('comment');

    

    console.log(firstName); // Print: undefined

    console.log(lastName);  // Print: null

    console.log(comment);   // Print: null

    

    console.log(typeof firstName); // Print: undefined

    console.log(typeof lastName);  // Print: object

    console.log(typeof comment);   // Print: object

    

    console.log(null == undefined)  // Print: true    

    console.log(null === undefined) // Print: false

    

    /* Since null == undefined is true, the following statements will catch both null and undefined */

    if(firstName == null){

        alert('Variable "firstName" is undefined.');

    }    

    if(lastName == null){

       alert('Variable "lastName" is null.');

    }

    

    /* Since null === undefined is false, the following statements will catch only null or undefined  */

    if(comment === undefined) {

        alert('Variable "comment" is undefined.');

    } else if(comment === null){

        alert('Variable "comment" is null.');

    }

</script>

In the program code, the first and the last name values are initiated in the first place. On observing, the value of lastName is assigned to be null. Unlike the firstName, whose value is undefined.

While in the next part, the comment is initiated in the print part, which will allow the function to print, whatever function is called. So, when console.log(firstName) is called, undefined will be the answer, followed by the lastName, which will be null.

In the next part, the value of null is equalized to that of undefined. This means, during the next “if” part, where the firstName is checked with “==” operator being null, the result will spring up multiple checks with firstName being both undefined as well as null. It will be the result for last name as well. Only the value of variable “comment” will be shown, whether the variable is null or undefined, depending on the decision statements.

View Demo

How to detect click inside iframe in JavaScript

Java packages and methods are filled with rules and methods. They allow the user to setup the defined codes and work on them. However, there are some exceptions. Most of these exceptions arise with respect to common clauses and boundaries. One of which is the iFrame interface.

In this iFrame interface, the method is used to embed another file within the existing HTML document. This is a very powerful utility and allows developers to facilitate addresses of different websites and sources to get a scrutinized access to that of the current web page. In many cases, the iFrame works out to work as a hyperlink generating code.

Inside this frame, however, there are certain commands, which may not work. The reasons for a function not working can be plenty. The click ( ) function does not work, because of an iFrame embedded web page within another web page. Thus, to detect or create a feasible event inside the iframe requires a set of different functions, viz. contents ( ) and load ( ).

Example

<!DOCTYPE html>

<html lang="en">

<head>

<meta charset="utf-8">

<title>Detect Click into iFrame</title>

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

<style type="text/css">

    iframe{

        width: 100%;

        height: 200px;

        border: 2px solid #ccc;

    }

</style>

<script type="text/javascript">

$(document).ready(function(){

    $("iframe").load(function(){

        $(this).contents().on("mousedown, mouseup, click", function(){

            alert("Click detected inside iframe.");

        });

    });

});

</script>

</head>

<body>

    <iframe src="http://google.co.in/"></iframe>

</body>

</html>

In the above code, you can observe that the iFrame is created in the previous statements and the data, which includes width, height, and the border of the frame, is seen. Inside the script part, the document is merged into the ready ( ) function for further execution and the iFrame is loaded by load ( ) function concurrently.

With this function, the entire frame is taken into the function part and the calling of functions will feature the load part. Next comes the content ( ) function, which is designated to initialize the function of the mouse from up, down and click functions respectively. Since the contents are loaded with this keyword, the function (), redirects to the load function, which in return gives out the alert message of click detected inside the iFrame.

In the final part, the source iFrame is designated, right outside the script of the main function part. This is the way, where an iFrame function is tested with the help of load and content functions without the source of click ( ) function.

View Demo

Replacing Multiple Spaces with Single Space using JavaScript Replace () Function

Syntax

string.replace(searchvalue, newvalue)

Definition and Usage

In the Replace() method, the string for a specified value is searched for a regular expression and a new string is returned where the specific values are replaced.

Multiple spaces can be a problem for JavaScript developers, ASP.NET, T-SQL and VB.NET developers. Here JavaScript Replace() cites two arguments:

  • The First argument is related to the string that is to be replaced using JavaScript Replace function.
  • The Second argument is for the new replaced string.

Here is an example of JavaScript Replace() where multiple spaces are shown to be removed with a single space:

Example

<script type="text/javascript">

    var myStr = 'PHP     CSS   HTML  jQuery';

    alert(myStr);  // Output 'PHP     CSS   HTML  jQuery'

    

    var newStr = myStr.replace(/  +/g, ' ');

    alert(newStr);  // Output 'PHP CSS HTML jQuery'

</script>

The developers need to keep one thing in mind that while printing the strings on the web page, the difference will not be visible. The browsers treat multiple spaces as a single space until the developers preserve the white space.

In the above example, the new string is returned that provides the Output of single space. Here, to perform the global search and replace() method, the ‘g’ switch can be included in a regular expression. However, in case, the first parameter here is a string as shown above then developers must include ‘g’ switch in the flags parameter.

Moreover, here in the example of replacing multiple spaces into single space, the string method is used. The Replace() searches for the match between a string and a regular expression that acts as a tool and the output is given as a new string. In the above Output, this function has helped to remove leading spaces that removed multiple spaces and merged into a single space.

The JavaScript Replace() function helps in unifying the spaces and reduces a number of white spaces that occurs while writing the script. For replacing all the occurrences of multiple spaces, the use of ‘g’ or a global modifier in the string method should be used.

View Demo