Alvin Mok
Alvin Mok

Reputation: 323

Disabled fields are not disabled/reset when page reload from validation

I've set certain fields to be disabled when a checkbox is checked. But when a user submits the form data and it's invalid, page is reloaded, where the checkbox remains checked but the fields are no longer disabled. Not sure how I can fix this?

The javascript:

$('#CommentFrequencyOk').on('click', function () {
    $('#test').prop('disabled', this.checked);
});

The fields to be disabled:

<fieldset id="test">
    <?php echo $this->Form->input('frequency_remarks'); ?>
    <?php echo $this->Form->input('duration_remarks'); ?>
</fieldset>

And the checkbox:

<div class="checkbox">
    <label for="CommentFrequencyOk">
        <input type="hidden" name="data[Comment][frequency_ok]" id="CommentFrequencyOk_" value="0" />
        <input type="checkbox" name="data[Comment][frequency_ok]" class="checkbox" value="1" id="CommentFrequencyOk" /> Frequency
    </label>
</div>

Upvotes: 0

Views: 359

Answers (4)

Jakir Hossain
Jakir Hossain

Reputation: 2517

Page reload checkbox checked and div#test is disabled if checkbox selected. You can try by flowing code.

<script>
  $(document).ready(function(){
  $('#CommentFrequencyOk').on('click', function () {
  $('#test').prop('disabled', this.checked);
 });
 });
</script>

<fieldset id="test" <?php if(@$_GET['data']['Comment']['frequency_ok'] == 1): echo 'disabled'; endif; ?>>
    <?php echo $this->Form->input('frequency_remarks'); ?>
    <?php echo $this->Form->input('duration_remarks'); ?>
</fieldset>

<div class="checkbox">
    <form >
    <label for="CommentFrequencyOk">
        <input type="hidden" name="data[Comment][frequency_ok]" id="CommentFrequencyOk_" value="0" />
        <input type="checkbox" name="data[Comment][frequency_ok]" class="checkbox" value="1" id="CommentFrequencyOk" <?php if(@$_GET['data']['Comment']['frequency_ok'] == 1): echo 'checked'; endif; ?> /> Frequency
    </label>
    <input type="submit" value="Submit"/>
    </form>
</div>

Upvotes: 0

vinodh
vinodh

Reputation: 724

Try to load the script in page load

$(function(){
$('#test').prop('disabled', $('#CommentFrequencyOk').is(":checked"));
});

Upvotes: 0

Divij Bindlish
Divij Bindlish

Reputation: 325

Note that during the initial form filling, the fields were disabled by the even handler for the click event on the checkbox. However, since the checkbox is already enabled, the event handler was never called and the fields remained enabled.

While rendering the page using PHP, you can simply disable the field there itself during page reload.

Upvotes: 0

Harsh Aggarwal
Harsh Aggarwal

Reputation: 192

Write the following line on page load also i.e.

// On Page Load
  $('#test').prop('disabled', $('#CommentFrequencyOk').is(":checked"));

Upvotes: 3

Related Questions