Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Change input value on change and on page load

The following code works on change of the select box but not on page load.

I tried wrapping the following jQuery with $( document ).ready(function() { //code// }); but that didn’t work.

jQuery:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

function hotelCheck(that) {
if (that.value == "1") {
        $('#decimal').val('0.00');
        $("#decimal").prop('disabled', true);
    } else {
        $("#decimal").prop('disabled', false);
    }
}

HTML:

<select onchange="hotelCheck(this);">
    <option value="2">Hotel 1</option>
    <option value="3">Hotel 2</option>
    <option value="4">Hotel 3</option>
    <option value="1" selected>No Hotel</option>
</select>

Can anyone help?

Thanks.

function hotelCheck(that) {
if (that.value == "1") {
        $('#decimal').val('0.00');
        $("#decimal").prop('disabled', true);
    } else {
        $("#decimal").prop('disabled', false);
    }
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
    <select onchange="hotelCheck(this);">
    <option value="2">Hotel 1</option>
    <option value="3">Hotel 2</option>
    <option value="4">Hotel 3</option>
    <option value="1" selected>No Hotel</option>
</select>

    <input type="text" id="decimal">

>Solution :

You need to trigger the select onchange first time when page load.

$(document).ready(function() {
  $('select').trigger('change');
});

Working snippet:

$(document).ready(function() {
  $('select').trigger('change');
});

function hotelCheck(that) {
  if (that.value == 1) {
    $('#decimal').val('0.00');
    $("#decimal").prop('disabled', true);
  } else {
    $("#decimal").prop('disabled', false);
  }
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<select onchange="hotelCheck(this);">
  <option value="2">Hotel 1</option>
  <option value="3">Hotel 2</option>
  <option value="4">Hotel 3</option>
  <option value="1" selected>No Hotel</option>
</select>

<input type="text" id="decimal">
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading