Daniel Robinson
Daniel Robinson

Reputation: 653

Jquery toggle dropdown show hide div on page load

I have a function that when selecting a dropdown it hides of shows a div and works perfectly.

$('#allday').on('change', function () {
    $("#mytimes").toggle(this.value == 'No');
});

When the user has selected this they go through to an edit page with the same field on it. Now if the value that was selected was a yes I want it to start with the div already hidden. If its a no I want it start with the div visable and still run the toggle in the correct manor. Here is my code on the edit page but its not working.

$('#allday').on('change', function () {
    $("#mytimes").toggle(this.value == 'No');
});

if ($('#allday').val() == 'No') {
    $('#mytimes').show();
} else if($('#allday').val() == 'Yes') {
    $('#mytimes').hide();
}

Here is my select field in php

Form::Select ("Available All Day", "allday", $allDayOpt,  array('name'=>'allday', "autocomplete"=>"off"));
echo '<div id="mytimes">';
Form::Textbox("Start Time", "hourstime", array('name'=>'hourstime', 'data-format'=>"HH:mm" ,'data-template'=>"HH : mm"));
Form::Textbox("End Time", "houretime", array('name'=>'houretime', 'data-format'=>"HH:mm" ,'data-template'=>"HH : mm"));
echo '</div>';

Upvotes: 0

Views: 1223

Answers (2)

Kiho
Kiho

Reputation: 38

If I understand right, you can maybe try something like

$("#mytimes").toggle(this.attr('value', 'no'));

and get the value with

if($('#allday').attr('value') == 'Yes'){ //do something }

Upvotes: 1

kscherrer
kscherrer

Reputation: 5766

I think you should put the show/hide part of the code in a function that runs after the page loaded.

$('#allday').on('change', function () {
   $("#mytimes").toggle(this.value == 'No');
});

$(function() {
    if ($('#allday').val() == 'No')
    {
      $('#mytimes').show();
    }
    else if($('#allday').val() == 'Yes')
    {
      $('#mytimes').hide();
    }
});

Upvotes: 1

Related Questions