Rees
Rees

Reputation: 3

jQuery: Target multiple form inputs that have the same class?

I'm trying to make a program which requires at least one of many (unknown amount, depending on prior conditionals) different form inputs to contain data in order for the user to be able to submit the form. I've successfully managed to create the code for a situation where only one input field is present, but I'm stuck as to what to do with multiple inputs.

All of the form inputs share the same common class rs2, so my theory was to hope that the jQuery code I used (below) would be able to target all instances of that class and validate whether or not at least one of them was not empty, which would return true if successful. However, it seems that only the first instance of the rs2 class is detected by the jQuery code, as - even if all other inputs contain data - a false value will be emitted as long as the first input box does not contain any data.

$( "form" ).submit(function( event ) {
  if( !$('.rs2').val() ) {
    event.preventDefault();
  }
});

The code prevents the form from submitting if rs2 contains no data - which is what I want. However, my aim of this is to make it so that, as long as at least one of the rs2 classes contains data, the form will still execute. I've looked at different methods, but currently I'm quite stumped as to a good alternative around this.

If anyone has any ideas, it'd be greatly appreciated.

Upvotes: 0

Views: 976

Answers (2)

Michelangelo
Michelangelo

Reputation: 5958

Created a fiddle: http://jsfiddle.net/chzzcosy/4/

You have to implement it to your likings but this is how I would do it:

HTML

<input type='text' class='rs2' />
<input type='text' class='rs2' />
<button id="submit">Check</button>

Javascript

$('#submit').click(function (event) {
    var array = document.getElementsByClassName('rs2');
    var count = [];
    for (i = 0; i < array.length; i++) {

        count += array[i].value;
    }

    if (count.length === 0) {
        alert("prevented");
    } else alert("not prevented");

});

Upvotes: 0

charlietfl
charlietfl

Reputation: 171690

You could use filter() to create a collection of those elements that have value, then check length of the collection as your conditional

$( "form" ).submit(function( event ) {

    var rs2HasVal = $('.rs2').filter(function(){
       return this.value !== '';
    }).length;

    if( !rs2HasVal ){
       event.preventDefault();
    }
});

Upvotes: 1

Related Questions