Show field if certain option value is selected - must work on pageload

可紊 提交于 2019-12-11 13:57:30

问题


This genius code works fine for checkboxes:

$(document).ready(function() {
   $("#Languages-spoken-and-understood-8").change(function() {
      $("#li-2-21")[$(this).is(":checked") ? 'show' : 'hide']("fast")
  }).change();
});

What I love about is that it works onload.

I was trying to modify it for a select box. Code is autogenerated by cforms on wordpress.

<select name="Severity-of-your-symptoms" id="Severity-of-your-symptoms" class="cformselect" >
    <option value="full01_severity_notselected" selected="selected">Please select...</option>
    <option value="Mild">Mild</option>
    <option value="Moderate">Moderate</option>
    <option value="Severe">Severe</option>
    <option value="full01_severity_other">Other</option>
</select>

This is what I tried:

  $('#Severity-of-your-symptoms').change(function() {
    $("#li-10-14")[("#Severity-of-your-symptoms[value='full01_severity_other']").attr('selected', 'selected') ? 'show' : 'hide']("fast")
  });change();

Obviously it's not working. Only if "Other" is selected, the text box should appear. Is there a way to use that nifty code again somehow or do I need a bigger function?

Thanks!


回答1:


You're almost there, this would be a much shorter way of doing it:

$('#Severity-of-your-symptoms').change(function() {
  $("#li-10-14")[$(this).val() == "full01_severity_other" ? 'show' : 'hide']("fast");
}).change();

You can give it a try here.

When getting or setting the value of a <select> (or any other input type element) you can use .val(). In case anyone wants this without the animation, it'd look like this:

$('#Severity-of-your-symptoms').change(function() {
  $("#li-10-14").toggle($(this).val() == "full01_severity_other");
}).change();


来源:https://stackoverflow.com/questions/3580886/show-field-if-certain-option-value-is-selected-must-work-on-pageload

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!