简体   繁体   中英

How to Disable button until required fields are filled without using javascript, just HTML5 and CSS

I have the following form

<form action="" method="post">
    <fieldset>
        <legend>Booking Details</legend>
        <div>
            <label for="name">Name:</label>
            <input id="name" name="name" value="" required  pattern="[A-Za-z-0-9]+\s[A-Za-z-'0-9]+" title="firstname lastname" aria-required="true" aria-describedby="name-format">
            <span id="name-format" class="help">Format: firstname lastname</span>
        </div>
        <div>
            <label for="email">Email:</label>
            <input type="email" id="email" name="email" value="" required aria-required="true">
        </div>
        <div>
            <label for="website">Website:</label>
            <input type="url" id="website" name="website" value="">
        </div>
        <div>
            <label for="numTickets"><abbr title="Number">No.</abbr> of Tickets:</label>
            <input type="number" id="numTickets" name="numTickets" value="" required aria-required="true" min="1" max="4">
        </div>
        <div class="submit">
            <input type="submit" value="Submit" onclick="alert('martharfarkar')">
        </div>
    </fieldset>
</form>

JS Fiddle FROM EXAMPLE

I want to send an email using a webservice on the onclick event of a button, but noticed that the event is triggered regardless the form validation, so the question is, is there a way to trigger the onclick event only if the form is valid without using javascript? perhaps HTML5 has something new to offer

I think the problem is that you are attaching an action to the button click not the form submit. So, two things are happening here:

  • You are atually using javascript in onclick="alert('whatever')"
  • You are binding this script to the button click not the form submit

Your validation is working fine for the submit action. Consider use the action parameter in form not the onclick param in the input button.

EDIT : To be more precise the <input type="submit" value="Submit"> default click action is submitting the form.

Hope it helps!

When I need some extra validation I change submit input to an element 'a' with an 'id' that I can check on a jquery click function. So I validate and I fire a submit manually. Example: $('#formId').submit ().

The best possible way is to bind the action to onsubmit event of the form rather than onclick event of button as user onepopcorn mentioned. It can be done by using

<form action="" method="post" onsubmit=alert('whatever')>

instead of using onclick for the submit button.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM