从选择下拉菜单中隐藏/显示标签和段落

时间:2014-10-24 20:23:16

标签: javascript jquery

我试图隐藏我的gvw标签和<p>之后我只希望它显示何时选择卡车。有人可以帮助我,并使用此代码向我解释如何做到这一点?问题是放置它们,否则jQuery可能会更容易:/

http://jsfiddle.net/1xqbpLp1/

 function GVW(){
   var dropdown1 = document.getElementById('vehiclebody');
   var textbox = document.getElementById('gvw');
   // Array for storing whether the textbox is required
   var is_required = [false, false, false, false, true, false];
     
   if(is_required[dropdown1.selectedIndex]) {
       textbox.required = true;
       textbox.style.display = "inline-block";
   } else {
       textbox.value = "";
       textbox.required = false;
       textbox.style.display = "none";  
   }

 }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js"></script>
<select name="vehiclebody" id="vehiclebody" required="yes" message="Please select body." size="1"  onChange="GVW();">
    <option value="">Choose a Vehicle</option>
    <option value="0">2Dr</option>
    <option value="1">Pickup</option>
    <option value="2">4dr</option>
    <option value="3">Truck</option>
    <option value="4">Convertible</option>
    <option value="5">Van</option>
</select>


<label for="ew">Empty Weight:</label>
         <input type="text" name="ew" id="ew" validateat="onSubmit" validate="noblanks" required="yes" message="Please enter empty weight." value="">
         
         <label for="gvw">&nbsp;&nbsp;&nbsp;Gross Vehicle Weight:*</label>
         <input type="text" name="gvw" id="gvw" onfocus="this.select()" required="yes" message="Please enter gross vehicle weight." value="" style="display:none;">
         
         </p>  
         </div>
         
         <p>*Gross Vehicle Weight is required for heavy trucks over 5000 lbs. Visit our website for more information.&nbsp;<a href="http://www.taxcollector.com/services_vehicle_heavy_truck.asp" target="_blank">Heavy Truck Information and Fee Schedule based on GVW</a> </p>

2 个答案:

答案 0 :(得分:1)

您需要使用CSS来初​​始隐藏元素:

<p id="gvwInfo" style="display:none">

然后根据选择使用JavaScript显示/隐藏它们。这是一个有效的jsfiddle:http://jsfiddle.net/kgajera/1xqbpLp1/1/

答案 1 :(得分:0)

我会把你的内联onchange =“”取出来,然后去......

$("select").on("change", function() {
    if ($(this).val() =="3") {
        $("label[for='gvw']").toggle();        
    }
});