jeudi 16 août 2018

Checking input and checkbox with JS

In my code I have a checkbox, which is followed by an input field. Checkbox is checked automatically, but I want to get an alert if input field is left empty. I made a JS script but it doesn't work. What am I doing wrong?

Thank you for the answers.

<!doctype html>
<html lang="en">
  <body>

    <div id="vsebina">
    <!-- Bootstrap CSS -->
    <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.1/css/bootstrap.min.css" integrity="sha384-WskhaSGFgHYWDcbwN70/dfYBj47jz9qbsMId/iRN3ewGhXQFZCSftd1LZCfmhktB" crossorigin="anonymous">

        <div class="form-row">
            <div class="form-group col-md-4">
            <div class="input-group mb-3">
              <div class="input-group-prepend">
                <div class="input-group-text">
                  <input type="checkbox" id="price_checked" name="price_checked" checked />
                </div>
              </div>
              <input type="number" class="form-control" min="1" id="price" name="price">
              <div class="input-group-append">
                <span class="input-group-text">€</span>
              </div>
            </div>
            </div>
        <div>
            <button href="/oglasi/" class="btn btn-outline-secondary btn-lg" style="float: right;" onclick="check(this)" role="button" aria-pressed="true">Oddaj oglas</button>
        </div>
            <script language='javascript' type='text/javascript'>
                function check(input) {
                    const inputPriceElm = document.getElementById('price');
                    if (document.getElementById('price_checked').checked && document.getElementById('price').value == "None") {
                        inputPriceElm.setCustomValidity('Give a price.');
                    } else {
                        // input is valid -- reset the error message
                        inputPriceElm.setCustomValidity('');
                            }
                    }
            </script>
    </div> <!-- /container -->
  </body>
</html>




Aucun commentaire:

Enregistrer un commentaire