9

In my form, I want to enable form only when all fields (and radio button list) has been selected.

So far, I have successfully made the submit button enable when the title field has content with:

onkeyup="if(this.textLength != 0) {subnewtopic.disabled = false} else {subnewtopic.disabled = true}"

My aim is to enable submit button only once everything has been filled. How do I do this?

Here is my full code with working jsfiddle:

            <form action="" method="post" id="subnewtopicform" />

                Title:
                <input type="text" name="title" onkeyup="if(this.textLength != 0) {subnewtopic.disabled = false} else {subnewtopic.disabled = true}">

<br/>

                Description:
                <textarea name="description"></textarea> 

<br/>
                Category:
<ul class="list:category categorychecklist form-no-clear" id="categorychecklist">

<li id="category-19"><label class="selectit"><input type="radio" id="in-category-19" name="category" value="19"> Animation</label></li>

<li id="category-20"><label class="selectit"><input type="radio" id="in-category-20" name="category" value="20"> Anime</label></li>

    </ul>

                <input type="submit" value="Submit Topic" class="button-primary" name="subnewtopic" id="subnewtopic" disabled="disabled" /> 

            </form>
Henrik Petterson
  • 6,862
  • 20
  • 71
  • 155
  • Seems like you are really asking for someone to write validation code for you. There are lots of plugins and tutorials for this. Your overly simplistic code is a long way from being a form validator. There are also html5 validity properties that you can access. To be honest you should do more research – charlietfl Jan 07 '15 at 21:41

5 Answers5

10

Here is a fiddle for you. http://jsfiddle.net/soyn0xag/6/

$("input[type='text'], textarea").on("keyup", function(){
    if($(this).val() != "" && $("textarea").val() != "" && $("input[name='category']").is(":checked") == true){
        $("input[type='submit']").removeAttr("disabled");
    } else {
        $("input[type='submit']").attr("disabled", "disabled");
    }
});

$("input[name='category']").on("change", function(){
    if($(this).val() != "" && $("textarea").val() != "" && $("input[name='category']").is(":checked") == true){
        $("input[type='submit']").removeAttr("disabled");
    } else {
        $("input[type='submit']").attr("disabled", "disabled");
    }
});
eg_dac
  • 701
  • 4
  • 14
8

use the "required" command inside the tag.

edit: Even with the radio buttons. you'd only have to select one. Here is the JSFiddle: http://jsfiddle.net/soyn0xag/3/

edit 2: Added a new working JSfiddle with your request to keep the submit button disabled until all fields have content. I used jquery, and the submit button is available after all typable fields have content, and the radio buttons are still required with that nice pop up: http://jsfiddle.net/soyn0xag/9/

this option DISABLES the button again once you take away the content from one of the fields. I believe this is what you want.

edit 3 - Final Fix Fixed a bug that let the submit button show up early: http://jsfiddle.net/soyn0xag/36/

As long as the and the submit button are wrapped in the same tag, you will not be able to submit without content in the now required input fields.

Example:

<input type="radio" id="in-category-19" name="category" value="19" required> Animation</label>

Note that required does not use quotes or any other delimiter.

Sanova
  • 551
  • 3
  • 10
  • But with this approach... all radio buttons are required to be pressed which is impossible because only one of them can be clicked...= – Henrik Petterson Jan 07 '15 at 21:43
  • Not true @HenrikPetterson since it is a radio button you only have to select one: see this updated fiddle: http://jsfiddle.net/soyn0xag/3/ – Sanova Jan 07 '15 at 21:45
  • 1
    Interesting, although is there any way to make the submit button stay disabled until all fields have some content? – Henrik Petterson Jan 07 '15 at 21:46
  • @HenrikPetterson yes, check out this updated jsfiddle: http://jsfiddle.net/soyn0xag/9/ I've updated my answer as well with this link. – Sanova Jan 07 '15 at 21:55
  • @HenrikPetterson this option DISABLES the button again once you take away the content from one of the fields. I believe this is what you want. – Sanova Jan 07 '15 at 21:59
  • 1
    Wow great, it has one problem though. If you fill in the description box first, then the submit button becomes enabled, even though the title box is emptied. – Henrik Petterson Jan 07 '15 at 22:00
  • @HenrikPetterson Here you go buddy. working flawlessly. Updated my answer to reflect this, please mark as answer if it suits your needs. http://jsfiddle.net/soyn0xag/36/ – Sanova Jan 07 '15 at 22:15
  • Let us [continue this discussion in chat](http://chat.stackoverflow.com/rooms/68371/discussion-between-sanova-and-henrik-petterson). – Sanova Jan 07 '15 at 22:37
3

yet another solution

required = function(fields) {
  var valid = true;
  fields.each(function () { // iterate all
    var $this = $(this);
    if (($this.is(':checkbox') && !$this.is(":checked")) || // checkbox
       (($this.is(':text') || $this.is('textarea')) && !$this.val()) || // text 
       ($this.is(':radio') && !$('input[name='+ $this.attr("name") +']:checked').length)) {
            valid = false;
        }
    });
    return valid;
}

validateRealTime = function () {
    var fields = $("form :input:not(:hidden)"); // select required
    fields.on('keyup change keypress blur', function () {
        if (required(fields)) {
            {subnewtopic.disabled = false} // action if all valid
        } else {
            {subnewtopic.disabled = true} // action if not valid
        }
    });
}

http://jsfiddle.net/jsq7m8hL/2/

Master Slave
  • 27,771
  • 4
  • 57
  • 55
2

There are a few different ways to go about this (as you've likely seen above).

This probably isn't the most efficient way, but you could check every time they click or press a key to see if any of the text fields are empty and if any of the radio buttons are filled. If one radio button is filled and none of the text fields are empty, you can go ahead and enable the button. Otherwise, you can disable it (or leave it disabled).

Let's go line by line:

function check() { // Define a function that we can call our event listeners with
    // Get our inputs and textareas
    var inputs = document.getElementsByTagName("input");
    var textareas = document.getElementsByTagName("textarea");
    var filled = true; // We'll assume that all of the fields are full unless proven otherwise
    var oneChecked = false; // We can use this to keep track of the radio buttons (by assuming at first that none are checked)

    for (var i = 0; i < inputs.length; i++) { // Loop through all of the inputs first
        if (inputs[i].type === "text" && !inputs[i].value) { // If the input is a text field, check whether it is empty; if so, set filled to false
            filled = false;
        }

        if (inputs[i].type === "radio" && inputs[i].checked) { // If the input is a radio button, see if it is filled in; because we only need one radio button to be filled in, that's all we need to know
            oneChecked = true;
        }

    }

    if (!oneChecked) { // Check outside of the loop if any of our radio buttons were selected and, if not, set filled to false
        filled = false;
    }

    for (var j = 0; j < textareas.length; j++) { // Now loop through all of the text areas; if any aren't filled in, set filled to false
        if (!textareas[j].value) {
            filled = false;
        }
    }

    if (filled) { // Check whether any of the fields are empty (or, in the radio button's case, if one is selected, and enable/disable the button accordingly
        document.getElementById("subnewtopic").disabled = false;
    } else {
        document.getElementById("subnewtopic").disabled = true;
    }
}

// Add event listeners to check for keypresses and clicks
window.addEventListener("keyup", check);
window.addEventListener("click", check);

Demo

AstroCB
  • 12,337
  • 20
  • 57
  • 73
  • 1
    Hi AstroCB, I really like your solution for this topic! I took your example and added multiple checkboxes and select option. I could get multiple checkboxes work with submit button, however, I got stuck on select option, that doesn't work with submit button. Please take a look at this sample in https://jsfiddle.net/0oprsc4j/6/ Please give me a hand. Thanks. – abcid d Jan 24 '20 at 18:28
2

I thing still have to give a answer for this Question: Live Demo Link

$(document).on('change keyup', '.required', function(e){
   let Disabled = true;
    $(".required").each(function() {
      let value = this.value
      if ((value)&&(value.trim() !=''))
          {
            Disabled = false
          }else{
            Disabled = true
            return false
          }
    });

   if(Disabled){
        $('.toggle-disabled').prop("disabled", true);
      }else{
        $('.toggle-disabled').prop("disabled", false);
      }
 })

 $(document).on('change keyup', '.required', function(e){
   let Disabled = true;
    $(".required").each(function() {
      let value = this.value
      if ((value)&&(value.trim() !=''))
          {
            Disabled = false
          }else{
            Disabled = true
            return false
          }
    });
   
   if(Disabled){
        $('.toggle-disabled').prop("disabled", true);
      }else{
        $('.toggle-disabled').prop("disabled", false);
      }
 })
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select class="required">
    <option value="" selected disabled>selected a value</option>
    <option>Car</option>
    <option>Buss</option>
    <option>Train</option>
</select>
 
<select class="required">
    <option value="" selected  disabled>selected a option</option>
    <option>A</option>
    <option>B</option>
    <option>C</option>
    <option>D</option>
</select>
<br /> <br /> 
<input type="text" class="required" placeholder="Full Name">

<input type="number" class="required" placeholder="Age">
<br /> <br /> 
<button type="button" class="toggle-disabled" disabled>Submit</button>
MD Ashik
  • 9,117
  • 10
  • 52
  • 59