Dycey
Dycey

Reputation: 4685

How do I hide a div based on empty input fields within it?

I have a form made up of multiple, optional subparts - each of which is enclosed in a

<div class="details"></div>

When editing the form I would like to hide those subparts which aren't as yet completed, and obviously I would like to do it unobtrusively. To simplify things I'm just checking to see if those fields whose name ends in 'surname' are empty, and then show/hide appropriately. So far, I have this.

//hide the all of the element class details
$(".details").each(function (i) {
  if ($('input[name$=surname]:empty',this).length == 1) { 
    $(this).hide();
  } else {
    $(this).show();
  }
});

Of course, the :empty selector may be wrong, or indeed inappropriate. (Of course what I really want to do is show any parts where any fields are completed, but I thought I'd start with just checking the most important one.)

I would be greatful if anyone could anyone point me in the right direction...

Upvotes: 3

Views: 6862

Answers (4)

Dycey
Dycey

Reputation: 4685

Thanks guys - the [value=""] was the piece I was missing. In case anyone else wonders, the barebones jQuery that did the trick (thanks to cristian) was

    //hide the all of the element class details
    $(".details").each(function (i) {
      if ($('input[name$=surname][value=""]',this).length == 1) { 
        $(this).hide();
        console.log('hiding');
      } else {
        $(this).show();
        console.log('showing');
      }
    });

Upvotes: 3

Tomalak
Tomalak

Reputation: 338228

This would probably do the requested thing:

$("div.details input").each(function () {
  if (this.value == "")
    $(this).parents("div.details").eq(1).hide();
  else
    $(this).parents("div.details").eq(1).show();
});

To affect only fields with "surname" in the name attribute, do the obvious:

$("div.details input[name$=surname]").each(function () { /* etc... */

Upvotes: 1

Kevin Gorski
Kevin Gorski

Reputation: 3771

This may have just been a typo, but you also don't need / shouldn't have a CSS class name of ".details" in your markup, just "details". The dot prefix is part of the CSS/jQuery selector syntax.

According to the documentation, ":empty" finds empty elements (as in containing no child elements), not form elements without values (an empty textbox). Checking for the value attribute equating to an empty string will work for single line text inputs, but you'd need a more complex query for including text areas, radio buttons, etc.

Upvotes: 1

Cristian Libardo
Cristian Libardo

Reputation: 9258

No selector love? Not exactly sure it's what you're really looking for but this hides all details elements with an empty input inside. Perhaps it's a clue.

<div class="details">
    <input type="text" name="surname" />
</div>

<script type="text/javascript">
    $(".details input[@value='']").parents(".details").hide();
</script>

Upvotes: 7

Related Questions