Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to disable submit button until all text fields are full and file is selected

I'm new to javascript / jquery so I may be missing something obvious, but I've found solutions that disable the submit button until all text fields are filled, and I've found solutions that disable it until a file is chosen. However, my form consists of a file input and 3 text fields and I cannot find a way of it being disabled until all text fields AND a file is chosen.

The distilled version of the code I'm working with is here:

HTML

    <div>
    <input type="file" /><br />
    <input type="text" /><br />
    <input type="text" /><br />
    <input type="text" /><br />
    <input type="submit" value="Upload" class="submit" id="submit" disabled="disabled" />
    </div>

JS

    $('.submit').click(function() {
var empty = $(this).parent().find("input").filter(function() {
        return this.value === "";
    });
    if(empty.length) {

        $('.submit').prop('disabled', false);
    }
    });
})()

Thanks for your help

https://jsfiddle.net/xG2KS/482/

like image 619
Codedstuff Avatar asked Oct 19 '25 21:10

Codedstuff


1 Answers

Try capture the event on those field and checking the empty values by using another function, see below code :

$(':input').on('change keyup', function () {
  // call the function after
  // both change and keyup event trigger
  var k = checking();
  // if value inc not 0
  if (k) $('.submit').prop('disabled', true);
  // if value inc is 0
  else $('.submit').prop('disabled', false);
});

// this function check for empty values
function checking() {
  var inc = 0;
  // capture all input except submit button
  $(':input:not(:submit)').each(function () {
    if ($(this).val() == "") inc++;
  });
  return inc;
}

This is just an example, but the logic somehow like that.

Update : Event Delegation. You might need read this

 // document -> can be replaced with nearest parent/container
 // which is already exist on the page,
 // something that hold dynamic data(in your case form input)
 $(document).on('change keyup',':input', function (){..});

DEMO

like image 176
Norlihazmey Ghazali Avatar answered Oct 21 '25 11:10

Norlihazmey Ghazali



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!