Johnatan De Leon
Johnatan De Leon

Reputation: 166

Jquery selector to get all inputs that has a value

I hope you're having a nice day

I have a dynamic table like this:

enter image description here

I would like to know if is possible make a Jquery selector to get all the inputs that has a value something like this:

$('.some-input-class:valueNotEmpty')

And get a array that only has the inputs with values

Is this possible? or I have to make something like this:

$('.some-input-class').each(function(){
   if($(this).val()){
      //Do something
   }
})

Upvotes: 1

Views: 824

Answers (2)

Engin
Engin

Reputation: 815

You can simply use placeholder-shown pseudo-class which is also supported almost by all modern browsers.

To get it working, you need to apply placeholder to all inputs in your HTML. But if you wish, you don't want it to be visible, you can do it like following:

<input type="text" placeholder=" " />

Now you can use the placeholder-shown pseudo-class to select all input fields with text.

$("input:not(:placeholder-shown)")

Upvotes: 1

Rory McCrossan
Rory McCrossan

Reputation: 337560

There's no selector in jQuery to target form controls which have a value. However you can use filter() to achieve it instead:

let $inputs = $('.some-input-class').filter((i, el) => !!el.value.trim())

Working example:

let $inputs = $('.some-input-class').filter((i, el) => !!el.value.trim())
$inputs.addClass('valid');
.some-input-class {
  display: block;
  margin: 0 0 10px;
}
.valid {
   border: 2px solid #0C0;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type="text" value="foo" class="some-input-class" />
<input type="text" value="bar" class="some-input-class" />
<input type="text" value="" class="some-input-class" />
<input type="text" class="some-input-class" />

<select class="some-input-class">
  <option value="">Please select...</option>
  <option value="lorem">Lorem ipsum</option>
</select>

<select class="some-input-class">
  <option value="">Please select...</option>
  <option value="lorem" selected>Lorem ipsum</option>
</select>

Upvotes: 1

Related Questions