Ratan
Ratan

Reputation: 883

Select all inputs using value attribute

I want to select all inputs (textbox) in my form which have required class and have no value. So I am using:

$('input[value=""]', '.required')

My problem is even when the user enters a value in the textbox, the val() returns that value, but value is still empty and so my above jquery still selects all the inputs which were previously empty, which it should not. How do i select all inputs whose val is empty?

Upvotes: 0

Views: 103

Answers (5)

Tonmoy Nandy
Tonmoy Nandy

Reputation: 381

You can select like this,

HTML

<input class="required"  />
<input class="required"  />
<input class="required" value='x'>
<input value='y'>

JS

 $("input:not([value]).required, input[value=''].required")

Thanks

Upvotes: -1

Dan Philip Bejoy
Dan Philip Bejoy

Reputation: 4381

You can use filter() to get all the inputs with val() empty, by checking each one's value in return statement.

$("#getInputs").click(function() {
  var arr = $('input').filter(function() {
    return ($(this).val() == '');
  });
  console.log(arr)
});
input {
  display: block;
  margin-bottom: 10px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" value="">
<input type="text" value="">
<input type="text" value="">
<input type="text" value="">
<button id="getInputs">Get</button>

Upvotes: 0

charlietfl
charlietfl

Reputation: 171679

The value attribute and value property of an input are not the same after a user edits it.

Use filter() and check the value property ... something like:

var $empties = $('input[required]').filter(function(){
   return !this.value;
}).doSomething();

if(!$empties.length){
   // process submit
}else{
   // prevent submit
}

Upvotes: 2

kind user
kind user

Reputation: 41893

Firstly, catch every input with required attribute, then look for inputs without value.

$('input[required=""]').each(function(){
  if (!$(this).val()) {
    console.log(this);
    //logic
  }
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input required>
<input required>
<input required value='x'>
<input value='y'>

Upvotes: 2

l.varga
l.varga

Reputation: 871

You could still use jquery's val() function

var required_inputs = [];
$('input.required').each(function() {
    var $this = $(this);
    if ($this.val() == "") {
        required_inputs.push($this);
    }
})

That way you have an array of required input elements which are empty. You could execute that function eg. on blur of each such input and then do with those elements whatever you want.

Upvotes: 0

Related Questions