在加载和隐藏字段上运行函数

时间:2017-11-10 12:30:26

标签: javascript jquery

我希望javascript在加载后立即运行以下功能,并且当用户选择任何其他选项时。下面的函数将隐藏一些字段并根据用户选择显示一些字段。

如果用户应选择“现金”,则应隐藏其他字段,但如果用户应选择“礼品”,则应显示其他字段。

    function TakeOff() {

     if(document.getElementById('id_six_to').options[
         document.getElementById('id_six_to').selectedIndex].value == "cash") {
         document.getElementById('id_name').style.display = 'none';
         document.getElementById('id_address').style.display = 'none';
         document.getElementById('id_details').style.display = 'none'; 
    } else {
         document.getElementById('id_name').style.display = '';
         document.getElementById('id_address').style.display = '';
         document.getElementById('id_details').style.display = '';
    }
}

window.onload = function() {
    document.getElementById('id_six_to').onchange = TakeOff;
};
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="form-group">
    <label class="sr-only" for="id_six_to">Mytake</label><select name="six_to" id="id_six_to" class="form-control" title="">
   <option value="cash" selected>Cash</option>

  <option value="gift">Gift</option>

  </select></div>

  <div class="form-group"><label class="sr-only" for="id_name">Name</label><select name="name" title="" required class="form-control" id="id_name">
  <option value="" selected>---------</option>

  <option value="a">a</option>

  <option value="b">b</option>

  <option value="c">c</option>

  </select></div>
<div class="form-group"><label class="sr-only" for="id_address">Address</label><input type="text" name="address" title="" id="id_address" readonly maxlength="10" placeholder="Address" class="form-control" /></div>
<div class="form-group"><label class="sr-only" for="id_details">Details</label><input type="text" name="details" title="" id="id_details" maxlength="200" placeholder="" class="form-control" /></div> 

        <input type="submit"  class="btn btn-danger repo" value="Submit" />
   </form>
</div>

问题:

默认情况下,从该选项中选择“cash”,当我加载表单的url时,而不是javascript来隐藏所有其他字段,因为默认情况下选择了“cash”,它将显示不是与“现金”价值相关。

我想默认隐藏3个字段,因为已选择“现金”。

1 个答案:

答案 0 :(得分:1)

当选择值改变时,只需触发设置事物状态的函数......

window.onload = function() {
    document.getElementById('id_six_to').onchange = TakeOff;
    TakeOff(); // add this so it runs at startup
};