This tutorial aims to equip you with the knowledge and skills to dynamically manipulate form elements using jQuery. It will cover how to get and set form input values and create dynamic form behaviors.
By the end of this tutorial, you will be able to:
This tutorial assumes that you have a basic understanding of HTML, CSS, JavaScript, and the basics of jQuery.
jQuery is a fast, small, and feature-rich JavaScript library. It makes things like HTML document traversal and manipulation, event handling, and animation much simpler with an easy-to-use API that works across a multitude of browsers.
To manipulate form elements, jQuery provides several methods such as .val()
, .text()
, .html()
etc.
$(this)
selector where possible to avoid repeating your jQuery selectors$(document).ready(function(){
// Getting value of input field
var name = $("#name").val();
// Setting value of input field
$("#name").val("New Name");
});
This example uses the .val()
method to get and set the value of an input field with the id of 'name'.
$(document).ready(function(){
// Hiding form element
$("#name").hide();
// Showing form element
$("#name").show();
});
This example uses the .hide()
and .show()
methods to hide and show a form element with the id of 'name'.
In this tutorial, we covered how to use jQuery to interact with form elements, getting and setting form field values, and creating dynamic forms that respond to user interaction.
For further learning, you can explore more about form validation using jQuery, submitting forms with AJAX, and other advanced topics.
Create a form with a single input field and a button. When the button is clicked, change the value of the input field to 'Button Clicked!'
Create a form with two input fields and a button. When the button is clicked, swap the values of the two input fields.
Create a form with an input field and a checkbox. When the checkbox is checked, hide the input field. When it is unchecked, show the input field.
$(document).ready(function(){
$("#button").click(function(){
$("#input").val("Button Clicked!");
});
});
$(document).ready(function(){
$("#button").click(function(){
var temp = $("#input1").val();
$("#input1").val($("#input2").val());
$("#input2").val(temp);
});
});
$(document).ready(function(){
$("#checkbox").change(function(){
if($(this).is(":checked")){
$("#input").hide();
}else{
$("#input").show();
}
});
});