Today we will be learning about jquery functions, their difference, and how they work so you can use them when they are required.
val():-
Val() function returns the value of controls or also you can set the value of the selected element.
Example # 1:-
<input type="text" id="firstName" name="firstTxt" value="" />
<input type="button" id="firstButton" name="submitButton" value="Submit"/>
<script type="text/javascript">
$(document).ready(function(){
$("#firstButton").click(function(){
var name =$("#firstName").val();
alert(name);
});
});
</script>
So you see in the above example when you enter some value in the text box and click the “Submit” button you will get the value of that text box.
Example # 2:-
<select id="country">
<option >England</option>
<option >Pakistan</option>
<option >India</option>
</select>
<input type="button" id="firstButton" name="submitButton" value="Submit"/>
<script type="text/javascript">
$(document).ready(function(){
$("#firstButton").click(function(){
var countryName=$("#country").val();
alert(countryName);
});
});
</script>
And in this example also, with the help of the jquery val() function, you will get the selected value from the dropdown list.
html():-
It will give you the entire content inside a specific HTML element. It is only used in HTML documents.
Example # 1:-
<div id="testDiv">
<p>Cricket</p>
<p>Hockey</p>
<p>Football</p>
</div>
<input type="button" id="firstButton" name="submitButton" value="Submit"/>
<script type="text/javascript">
$(document).ready(function(){
$("#firstButton").click(function(){
var content=$("#testDiv").html();
alert(content);
});
});
</script>
In the above example, html() returns the inner content of the DIV element having an id=”testDiv”.
text():-
It will give you the text inside an HTML element. It can be used in XML as well as in HTML documents. Let’s have an example to explain this.
Example # 1:-
<div id="testDiv">
<p>Cricket</p>
<p>Hockey</p>
<p>Football</p>
</div>
<input type="button" id="firstButton" name="submitButton" value="Submit"/>
<script type="text/javascript">
$(document).ready(function(){
$("#firstButton").click(function(){
var content=$("#testDiv").text();
alert(content);
});
});
</script>
In this example text() will give the text content that is written inside the html elements.
Hope you guys understand the difference between val(), html(), and text() functions. Best of Luck.
Good one
ReplyDeletevery clear.
ReplyDeletereally clear concept
ReplyDeleteGood stuff...
ReplyDelete