EnexoOnoma
EnexoOnoma

Reputation: 8836

Looking for a hand on my jQuery and JS script

What I have is in my fiddle here http://jsfiddle.net/mPuj9/4/

What I tried to do is to disable the button until all of textboxes are filled and the checkbox is checked. My current code is not good, it let you submit in some cases and I don't know how to work it with the checkbox.

CODE

$(document).ready(function() {
    $('.textfield').blur(function() {
        if ($.trim(this.value) == "") {
            $('#btnUpdate').attr("disabled", true);
        }
        else {
            $('#btnUpdate').removeAttr("disabled");
        }
    });
});

$(document).ready(function() {
    $('#termid').change(function() {
        var val = $(this).val();
        $('#reservationdetails').empty().addClass('loading').load('../kratisis/forms/' + val + '.php', function() {
            $('#reservationdetails').removeClass('loading')
        });
    });
});

Upvotes: 4

Views: 102

Answers (3)

ShankarSangoli
ShankarSangoli

Reputation: 69915

Here you go

http://jsfiddle.net/mPuj9/8/

$(document).ready(function () {
    $('form').delegate('input:text, input:checkbox', 'blur keyup change', function () {
        if(($('form input:text').filter(function(){ return $.trim(this.value) == ''; }).length > 0)
           || ($('form input:checked').length == 0)){
          $('#btnUpdate').attr("disabled", true);
        }
      else {
            $('#btnUpdate').removeAttr("disabled");
      }
    });
});

Upvotes: 2

bozdoz
bozdoz

Reputation: 12870

I think the problem is that you're not using .each() for the text fields. You're checking the one that was recently changed to see if it's value is "", but you're not checking each one.

Upvotes: 0

kirb
kirb

Reputation: 2049

Here's another way you could do this, which also works if someone presses enter in a text box, or if the browser autofilled an input:

$(function() {
    $("form button").attr("disabled", true); //disable buttons at first
    var inputs = 0; //keep count of the inputs
    $("form input, form select, form textarea").each(function() {
        inputs++; //increment counter
        $(this).keypress(function() {
            if ($.trim($(this).val()) != "") { //if the value isnt empty
                inputs--; //decrement counter
                if (inputs == 0) { //if theyre all filled in
                    $("form button").attr("disabled", false);
                }
            }
        }).trigger("keypress"); //in case it was autofilled by the browser
    });
    $("form").submit(function(e) { //prevent the form being submitted by pressing enter
        if (inputs != 0) { //if they arent all filled in
            alert("Some fields aren't filled in. Please fix them and try again."); //tell the user
            e.preventDefault(); //cancel sending the form
            return false;
        }
    });
});

Upvotes: 1

Related Questions