views:

28

answers:

2
+2  Q: 

Jquery form :input

Is there a "simple" way to ensure that ALL the inputs in a form have "an entry". I need/want to disable the submit button unless all inputs have a value they are all input type=text. I assume it is something like for each but I am not very good at the for each in JQuery. Possible problem is that the inputs are "dynamically" generated by sortables? All I need to know is is there a value in every input field. The "real" validation is done elsewhere.

So is it something like:

$j('#button').click(function (){
each(function(:input){
//check the length in here?
});
});
+1  A: 
$("#button").click(function(event) {
    var valid = true;
    $(":input").each(function(index) {
        if ($(this).val().length == 0) {
            valid = false;
        }
    });
    if (!valid) {
        event.preventDefault();
    }
});

Should work.

First part grabs the element with id of button, then assigns a function to the onclick event. Second part grabs all input fields, and run a function on each of them. Then you get the length of the value for each.

The $(this) works since the function is being applied to a specific element on the page, and will always get you the current element.

Slokun
Hi Slokun, as you said "should work" may be it does with "proper" Jquery, but I can't get it to - totally work . I have tried a number of things/ variations but the moment I use if(!valid) then the whole page refreshes etc. I cant get a result from if(!valid) {alert('this')} else{ alert('that')} I always get the "false" statment. The first part i.e. the each function works I know that will keep playing... Thanks
Oh had to change to $j("#tstform :input[type='text']").each(function(index) {... as it way firing for "every" form on the page
@russp So, did it work with the different selector? And yeah, if you don't specify the form the inputs are in, it will grab everything on the page.
Slokun