Show / Hide Form Element On event using JQuery
Show / Hide Form Element On Event using JQuery
This article belongs to beginners in web development and some of the "Just Became" pro in the web development who do some silly mistakes while coding. This article is on showing / hiding a form element on some other form element's change event.
Now, What is an event?
(Obviously with respect to HTML and JavaScript)It says : JavaScript's interaction with HTML is handled through events that occur when the user or the browser manipulates a page. - Tutorialspoint
What is Jquery:
jQuery is a fast, small, and feature-rich JavaScript library. It makes things like HTML document traversal and manipulation, event handling, animation, and Ajax much simpler with an easy-to-use API that works across a multitude of browsers. - jQuery.com
Now what?
Problem: Given a drop down select element having three values i.e (First, Second, Third). And There are three other elements containing only labeled text on the page which should be shown on the respective selection of value from the drop down.
For example: If "First" is selected. than the Text "First Selected" should be shown. and rest of the text i.e "Second Selected" and "Third Selected" should be hidden. By default all the three text will be hidden.
Below is the JsFiddle:
Below is the JsFiddle:
Explanation of the above code.
HTML Code:
JavaScript:
- In this code we have one form control select tag and three label tag.
- The select tag has three values ( As stated in the problem above)
- It has an id attribute which has value selectOption.
- This id attribute will be used to get event occurring on the select tag.
- The event we have used in this time is onChange.
- The three labels also have their respective unique ids "first", "second" and "third" respectively.
JavaScript:
- Here in this code we have written a function which looks for Change event on the <select> tag having id "selectOption".
- If the event occurs then this function is called and the function checks for the value of that select tag.
- The code section of that function contains simple control structure statements of if else only.
- The function $("#selectOption").value() gets the selected value select tag.
- $('#first').hide() is used to hide the element having id "first".
- Same goes with the show() function and other's show / hide statements.
If you have any further doubt or else if you have another solution with lesser LOC than you can mention that in the comment section below.
Have a Happy Coding!
Comments
Post a Comment