Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery: hide and show an input element

I'm trying to do is hiding/showing a certain input object if a select value is checked.

Code in JSFiddle

The HTML part of the code is here:

<label for="add_fields_placeholder">Placeholder: </label>
<select name="add_fields_placeholder" id="add_fields_placeholder">
    <option value="50">50</option>
    <option value="100">100</option>
    <option value="Other">Other</option>
</select>
<div id="add_fields_placeholderValue">
    Price:
    <input type="text" name="add_fields_placeholderValue" id="add_fields_placeholderValue">
 </div>​

And the jQuery part is here:

$(document).ready(function()
{
    $("#add_fields_placeholder").change(function() {
        if($(this).val() == "Other") {
            $("#add_fields_placeholderValue").show();
        }
        else {
            $("#add_fields_placeholderValue").hide();
        }
    });
});

​ So if user selects "Other", it shows another input object.

The problem now is this. First when you open the page the first option is selected by default and the optional input object is shown. It hides once you select another option.

Is there any trick to make it hide when you first load the page too? Not just when you select a value manually.

Thank you guys.

like image 784
inrob Avatar asked Aug 11 '12 23:08

inrob


People also ask

How do I show and hide input fields?

Style display property is used to hide and show the content of HTML DOM by accessing the DOM element using JavaScript/jQuery. To hide an element, set the style display property to “none”.

Can be used in jQuery to hide and display an element of HTML?

jQuery toggle() You can also toggle between hiding and showing an element with the toggle() method.

How do I toggle show and hide in jQuery?

jQuery toggle() MethodThe toggle() method toggles between hide() and show() for the selected elements. This method checks the selected elements for visibility. show() is run if an element is hidden. hide() is run if an element is visible - This creates a toggle effect.

What does jQuery hide () do?

The hide() method hides the selected elements. Tip: This is similar to the CSS property display:none. Note: Hidden elements will not be displayed at all (no longer affects the layout of the page). Tip: To show hidden elements, look at the show() method.


1 Answers

Just add:

$("#add_fields_placeholderValue").hide();

After your change event declaration on page load.

i.e.

$(document).ready(function()
{
 $("#add_fields_placeholder").change(function()
 {
  if($(this).val() == "Other")
  {
   $("#add_fields_placeholderValue").show();
  }
  else
  {
   $("#add_fields_placeholderValue").hide();
  }
 });
 $("#add_fields_placeholderValue").hide();
});

Working example: http://jsfiddle.net/bZXYR/

like image 164
Travis J Avatar answered Oct 03 '22 18:10

Travis J