AnthonyGalli.com AnthonyGalli.com - 7 months ago 12
Javascript Question

How to append correct details based upon category?

If a user clicks on

#challenge_category_goal
then the details
for-goal
appear, if the user clicks on
#challenge_category_habit
then the details
for-habit
appear.

<%= f.radio_button :category, 'goal', class: 'date-format-switcher' %>
<label for="challenge_category_goal">Goal</label>

<%= f.radio_button :category, 'habit', class: 'date-format-switcher' %>
<label for="challenge_category_habit">Habit</label>

<div id='details'>
<div id='for-goal'>
goal attributes
</div>
<div id='for-habit'>
habit attributes
</div>
</div>

<script>
var removed = $('#for-b').detach();
$('#challenge_category_goal').click(function() {
$('#details').append(removed);
removed = $('#for-goal').detach();
})

$('#challenge_category_habit').click(function() {
$('#details').append(removed);
removed = $('#for-habit').detach();
})
</script>


When the form first loads the appropriate category is chosen (based upon code passed on the backend from the user choosing a featured challenge), but the
details
are not changed based upon page load. They only change based upon
.click
. How can I make javascript show correct
details
based upon page load &
.click
?

Answer

You can try to use the checked status to determine the show/hide status:

<script>
function updateInfo(){
    if($('#challenge_category_goal').prop('checked')){
        $('#for-goal').show();
        $('#for-detail').hide();
    }else{
        $('#for-goal').hide();
        $('#for-detail').show();
    }
}

$(function() {
  $('#challenge_category_goal').click(updateInfo);
  $('#challenge_category_habit').click(updateInfo);
  updateInfo();
});
</script>

I also suggest you to check whether this pure CSS method fits your case.