Jan C Jan C - 1 month ago 11
jQuery Question

Hiding a section of a table in a form dependent on another field choice

I would like to only show a particular row in a form when the option selected includes the word 'split'

I have used a class on the row to be hidden and have got this far but can not get it to work




$(document).ready(function() {
$(".split td").hide();

$('#os0').change(function() {
var val = $(this).val();

if (val == "*split*") {
$('.split td').show();
} else {
$('.split td').hide();
}
});
});

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.0/jquery.min.js"></script>
<tr>
<td>
<input type="hidden" name="product[]" value="Type" /> Type:
<select name="product[]" id="os0">
<option value="Anodised closed">Anodised closed </option>
<option value="Plain closed">Plain closed</option>
<option value="Black filled closed">Plain closed Black filled </option>
<option value="Anodised split">Anodised split</option>
<option value="Plain split">Plain split</option>
<option value="Black filled split">Plain split Black filled </option>
</select>
</td>
</tr>
<tr>
<td class="split">
<input type="hidden" name="product[]" value="yrno" />Please specify year if required:
<input type="text" name="product[]" id="os9" onkeypress="return numbersonly(this, event)" maxlength="4" class="formfill" style="width: 50px;" />
</td>
</tr>





can anyone tell me where I am going wrong please :)

Answer

You selection $(".split td") must be like $("td.split")

and to search for existence of substring use indexOf() which returns first index of substring in main string.

$(document).ready(function() {
  $('td.split').hide();
  $('#os0').change(function() {
    var val = $(this).val();
    if (val.indexOf("split") > -1) {
      $('td.split').show();
    } else {
      $('td.split').hide();
    }
  });
});
td.split {
  display: none;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.0/jquery.min.js"></script>
<table>
  <tr>
    <td>
      <input type="hidden" name="product[]" value="Type" />Type:
      <select name="product[]" id="os0">
        <option value="Anodised closed">Anodised closed</option>
        <option value="Plain closed">Plain closed</option>
        <option value="Black filled closed">Plain closed Black filled</option>
        <option value="Anodised split">Anodised split</option>
        <option value="Plain split">Plain split</option>
        <option value="Black filled split">Plain split Black filled</option>
      </select>
    </td>
  </tr>
  <tr>
    <td class="split">
      <input type="hidden" name="product[]" value="yrno" />Please specify year if required:
      <input type="text" name="product[]" id="os9" onkeypress="return numbersonly(this, event)" maxlength="4" class="formfill" style="width: 50px;" />
    </td>
  </tr>
</table>