Archive

Posts Tagged ‘Java Script’

Access HTML Element using Javascript/JQuery

Java Script

There are two ways to access html element from javascript.

Let us suppose your HTML file has the following content.

<html>

<head>

</head>

<body>

<form >

<input type=”text” id=”txtusername” name=”txtusername” />

<input type=”password” id=”txtpassword” name=”txtpassword” />

<input type=”submit” value=”Submit” />

</form>

</body>

</html>

Then you can access any element using the code lines below

1.          var username=document.getElementById(“txtusername”).value;

2.          var username=  document.forms[0].txtusername.value;

I hope this was helpful to you.

 

JQuery

The code snippet below shows how to access html element from jquery.

Let us suppose your HTML file has following content.

<html>

<head>

/* add jquery library reference in your code.

If you haven’t yet downloaded it then you can download from http://docs.jquery.com/

*/

<script type=”text/javascript” src=”jquery1.4.2.js” />

</head>

<body>

<form >

<input type=”text” id=”txtusername” name=”txtusername” />

<input type=”password” id=”txtpassword” name=”txtpassword” />

<input type=”submit” value=”Submit” />

</form>

</body>

</html>

You can access any element using the below lines:

$(document).ready(function() // function called when page load is complete

{

$username=$(‘#txtusername’).val();

alert(“Hello ! Mr.  “+$username);

});

Hope this small bit of code was helpful to you.

Advertisements
Categories: JavaScript, JQuery Tags: ,
%d bloggers like this: