I'm using the .on() method to show/hide content depending on which label has been clicked; and to indicate which radio is currently checked.
I want my code to programmatic, so that the data-type of the label and the value of the input are dynamic rather than hard coded.
What's the best approach?
$('.js-choice[data-type="skip"]').on('click', function () {
$('input[name="choice"][value="1"]').prop('checked', true);
$(jsSkip).removeClass('hide-content');
$(jsAddr).addClass('hide-content');
$(jsNew).addClass('hide-content');
});
Here is a link to my jsFiddle: http://jsfiddle.net/curlybraces/x8Qbz/2/
In your fiddle, you are using a lot of classes but no ids. Start by giving an id
similar to the data-type
attribute of your labels to the three <div>
s. Also add a class to the div
s that identifies them as a container for your form fields. They have that in common.
In your JavaScript, all you need to do now is select the <label>
s, which have the class js-choice
. To each of them you apply an onClick
handler. That handler just needs to hide all of the <div>
s that have form fields and show the one belonging to the <label>
that was clicked.
This leaves us with this simple function:
$('.js-choice').each(function () {
$(this).on('click', function () {
$('.form-fields').addClass('hide-content');
$('#fields-' + $(this).attr('data-type')).removeClass('hide-content');
});
});
I've updated your jsFiddle.