0

I have some rogue input and submit buttons that add new items in a list, I want to prevent them from being submittable when they have nothing in them. They look like this:

<input name="name" placeholder="Application Name">
<button type="submit">Add App</button>

I have a bunch of them, I was wondering if there was some way I could get all of them not to submit when they have nothing in them. Thanks!

3 Answers 3

2

Yes, just add the required attribute.

<input name="name" placeholder="Application Name" required>
Sign up to request clarification or add additional context in comments.

2 Comments

Excellent, thank you! Does this work on all browsers and all that?
yes, all moderns browsers. (use caniuse to see the support, excellent site caniuse.com/form-validation). You can also set a pattern, to check per example if the value is a valid mail, a number, etc...
0

There are 2 solutions...

  1. Solution is set HTML5 attribute required

  2. Solution is set function on form, so on submit, function will be processed and return false; will prevent submiting:

<form action="" method="post" onSubmit="checkInputs();return false;" id="form">

Then you can go through every input:

$('#form input').each(function() {

And finally, you will check, if is that input text type and if is empty:

if( type == 'text' && value.length == 0 )

Here is FIDDLE DEMO

Comments

0
  1. 'required' attribute is not supported in Internet Explorer 9 and earlier versions, or in Safari.
  2. Include the input and button inside a form and validate the form on submit.

HTML Code :

<script src="http://code.jquery.com/jquery-1.11.0.min.js"></script>
<form name="app_form" id="app">
    <input name="name" id="name" placeholder="Application Name">
    <button type="submit">Add App</button>
</form>

JS Code :

$("#app").submit(function(event) {
    if (!$("#app #name").val()) {
        alert("Please enter Application Name.");
        event.preventDefault();  // this will prevent form submission
});

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.