16
<html>
<head>
<script type="text/javascript" src="jquery-1.7.1.min.js"></script>
<script type="text/javascript">
$(document).ready(function(){
  $("button").click(function(){
    alert('hi'+$("input:text").val());
    $("input:not(:empty)").val("sdfdf");
  });
});
</script>
</head>
<body>
<input type="text" value="aa" />
<input type="text" value="" />
<input type="text" value="aa" />
<button>Click me</button>
</body>
</html>

i am trying to access empty textboxex using jquery and assigning a value hello to it.. but it's not working .

thanks in advance

Prakash Chandra
  • 317
  • 1
  • 3
  • 14
  • 2
    read http://stackoverflow.com/questions/1299424/selecting-empty-text-input-using-jquery – Dau Feb 07 '12 at 09:11

4 Answers4

30

:empty checks for whether an element has child elements. input elements cannot have child elements.

If you want to test that the input element's value is blank:

$(document).ready(function(){
  $("button").click(function(){
    $("input").filter(function() {
        return this.value.length !== 0;
    }).val("sdfdf");
  });
});

There we get all of the input elements, and then filter it so only the ones whose value property isn't "" are included.

T.J. Crowder
  • 1,031,962
  • 187
  • 1,923
  • 1,875
  • 3
    This is the right way to do it. A selector like `input[type=text][value='']` probably isn't correct for this case because it only considers the initial value attribute and ignores characters entered by the user. – Dave Methvin Feb 07 '12 at 13:53
5

You could use another selector for your task:

$("input[value='']").val("sdfdf");
Candide
  • 30,469
  • 8
  • 53
  • 60
  • 3
    Note that this selects based on the HTML attribute initial value; not the DOM property. Therefore if the user changes the value, this selector will not pick it up. [More on the difference between attributes and properties](http://api.jquery.com/attr/) – David Cook Feb 08 '16 at 23:22
4

jQuery(':empty') Description: Select all elements that have no children (including text nodes).

From http://api.jquery.com/empty-selector/. Thus :empty does not do what you think it does.

Have a look at this answer https://stackoverflow.com/a/1299468/138023 for a solution.

Community
  • 1
  • 1
Markus Hedlund
  • 23,374
  • 22
  • 80
  • 109
0

You could use an .each with this inside:

if( $(this).val().length === 0 ) {
    $(this).parents('p').addClass('warning');
}
mynameisnotallowed
  • 564
  • 1
  • 11
  • 34