How To Read TextBox Values By Id Using jQuery

In this article we will learn how to read Text Box values using jQuery. Consider the following is the Razor View in MVC Named Employee having the following HTML controls.
<div class="form-horizontal">
        <div class="editor-label">
            Name
        </div>
        <div class="editor-label">
            <input type="text" id="txtName" />
        </div>

        <div class="editor-label">
            Address
        </div>
        <div class="editor-label">
            <input type="text" id="txtAddress" />
        </div>

        <div class="editor-label">
            City
        </div>
        <div class="editor-label">
            <input type="text" id="txtcity" />
        </div>
        <div class="editor-label">
            <br />
            <input class="btn-default" type="button" id="btnSave" value="Save" />
        </div>
    </div>
To read the Text Box values using jQuery ,use the following syntax.
//Reading text box values using Jquery 
$("#txtName").val(),
$("#txtAddress").val(),
$("#txtcity").val()
Create the following jQuery function to read the text box values by Id using the jQuery on button click.
$(document).ready(function () {
        $("#btnSave").click(function () {
            $.ajax(
            {
                type: "POST", //HTTP POST Method
                url: "Home/AddEmployee", // Controller/View 
                data: { //Passing data
                    Name: $("#txtName").val(), //Reading text box values using Jquery 
                    City: $("#txtAddress").val(),
                    Address: $("#txtcity").val()
                }

            });

        });
    });

Note

To work with jQuery, we need to reference the jQuery library at the head section of the HTML file. You can use either CDN jQuery library or offline reference.
CDN Reference Example
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script> 
To use the above jQuery library, you need an active internet connection. You can download and use it as an offline jQuery library as well. You need to add reference as below.

Offline Reference Example
<script src="~/Scripts/jquery-1.10.2.min.js"></script>

I hope from the above examples, you have learned how to read a TextBox values by Id using jquery.

Related Articles

Post a Comment

www.CodeNirvana.in

Protected by Copyscape Online Copyright Protection
Copyright © Compilemode