I'm learning javascript script and trying to hide some fields on radio change. It doesn't work, but I can't see why and there are no console errors. This is what I am trying:
HTML
<form>
<input type="text" name="field_0" id="field_0" value=" " class='text_box'>
<input type="text" name="field_1" id="field_1" value=" " class='text_box'>
<input type='radio' name='field_2' id='field_2_0' value="I can come" class='form_radio'>
<input type='radio' name='field_2' id='field_2_1' value="I can't come" class='form_radio'>
<input type='hidden' name='field_2_length' value='2'>
<input class="extra" type="text" name="field_3" id="field_3" value=" " class='text_box'>
<input class="extra" type="text" name="field_4" id="field_4" value=" " class='text_box'>
<input type='submit' value='Send' class='form_button'>
</form>
JS
jQuery(document).ready(function($) {
$('input:radio[name=field_2]').change(function() {
if ($(this).val() == 'hide') {
$('.extra').hide();
} else {
$('.extra').show();
}
});
});
This is the code (not) running https://jsfiddle.net/spadez/s25stbde/2/
Any ideas where I have gone wrong?
Your code for testing the value of $('input:radio[name=field_2]')
is looking for a value of 'hide' when it should be looking for a value of "I can't come". Change your javascript code to
jQuery(document).ready(function($) {
$('input:radio[name=field_2]').change(function() {
if ($(this).val() == "I can't come") {
$('.extra').hide();
} else {
$('.extra').show();
}
});
});
See working fiddle here. https://jsfiddle.net/mcebb8py/1/
In your version the 2 radio values are "I can come" and "I can't come",
So the case you're checking in your change handler, $(this).val() == 'hide'
never happens.
Here's an example changing one of the values of radio inputs to "hide":
jQuery(document).ready(function($) { $('input:radio[name=field_2]').change(function() { console.log('this ', $(this).val()) if ($(this).val() == 'hide') { $('.extra').hide(); } else { $('.extra').show(); } }); });
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <form> <input type="text" name="field_0" id="field_0" value=" " class='text_box'> <input type="text" name="field_1" id="field_1" value=" " class='text_box'> <input type='radio' name='field_2' id='field_2_0' value="hide" class='form_radio'> <!-- changed value to hide --> <input type='radio' name='field_2' id='field_2_1' value="I can't come" class='form_radio'> <input type='hidden' name='field_2_length' value='2'> <input class="extra" type="text" name="field_3" id="field_3" value=" " class='text_box'> <input class="extra" type="text" name="field_4" id="field_4" value=" " class='text_box'> <input type='submit' value='Send' class='form_button'> </form>
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.