简体   繁体   English

根据另一个div内的值显示或隐藏div的内容?

[英]Show or hide content of a div based on value inside another div?

I'd like to show a message inside a div if the value inside another div is over a certain value. 如果另一个div内的值超过某个值,我想在div内显示一条消息。 I can work that out but the value inside the other div will change depending on what the user has selected and then the required message doesn't appear or disappear each time this happens. 我可以解决这个问题,但另一个div内的值将根据用户选择的内容而改变,然后每次出现这种情况时所需的消息就不会出现或消失。 I'm currently using: 我目前正在使用:

if ($('#id1').val() < '25') {$('#id2').css('display','none');}

So #id2 is set to display as normal, but when a dropdown selection changes the value displayed inside #id1 to something less than 25 it needs to disappear and vice versa. 因此,#id2设置为正常显示,但是当下拉选择将#id1中显示的值更改为小于25时,它需要消失,反之亦然。

Any ideas? 有任何想法吗? Thanks. 谢谢。

You need to: 你需要:

  1. Bind event on #id1 #id1上绑定事件
  2. Convert the selected value to integer 将所选value转换为整数
  3. Compare this against integer 25 与整数25进行比较
  4. Use toggle() to show/hide the div based on condition 使用toggle()根据条件显示/隐藏div
  5. Trigger change event on page load 在页面加载时触发change事件

Code: 码:

$('#id1').on('change', function() {
    $('#id2').toggle(parseInt($(this).val().match(/\d+/)[0], 10) >= 25);
}).trigger('change');

 $('#id1').on('change', function() { $('#id2').toggle(parseInt($(this).val().match(/\\d+/)[0], 10) >= 25); }).trigger('change'); 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.10.0/jquery.min.js"></script> <select id="id1"> <option value="$0">0</option> <option value="£10">10</option> <option value="£25">25</option> <option value=£50>50</option> <option value=£100>100</option> </select> <br/> <br/> <div id="id2">This should show when greater than or equal to 25</div> 

something like this? 这样的东西?

 $(document).ready(function() { $('#id1').on('change', function() { if (parseInt($(this).val()) >= 25) { $('#id2').show(); } else { $('#id2').hide(); } }); // initialize div state $('#id1').trigger('change'); }); 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <select id="id1"> <option value=0>0</option> <option value=10>10</option> <option value=25>25</option> <option value=50>50</option> <option value=100>100</option> </select> <br/> <br/> <div id="id2">This should show when greater than or equal to 25</div> 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM