Jason Chen Jason Chen - 5 months ago 8
jQuery Question

jQuery change variables with child elements

I am trying to target child elements in jQuery, make changes based on whether there are any inputs. However, this code has a few problems. First, the CSS effect on click does not apply to the textarea even when I have specified it.

Second, filling in the input field still returns the variable

truth
as false, so it does not execute the code below
$('p').html('Solid')
.

My HTML:

<div id="section">
<button>Click It</button>
<label>
<input type="text" required="true" />
</label>
<label>
<input type="text" />
</label>
<textarea required="true"></textarea>
</div>
<p></p>


$('button').click(function(){
var truth = true;
$('#section label').each(function(){
var chooseinputs = $(this).find('input[required=true], textarea[required=true]');
if ( !$.trim(chooseinputs.val()) ){
$(chooseinputs).css('border', '1px solid red');
$('p').html("Empty");
truth = false;
}
if (truth)
$('p').html("Solid!");
});
});


JSFiddle

Kld Kld
Answer

You are just checking the first input, you need a foreach

$('button').click(function() {
  var truth = true;
  $('#section label> input[required=true], textarea[required=true]').each(function() {
    
    if (!$.trim($(this).val())) {
      $(this).css('border', '1px solid red');
      $('p').html("Empty");
      truth = false;
    }
    if (truth) {
      $('p').html("Solid!");
    }
  });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div id="section">
  <button>Click It</button>
  <label>
    <input type="text" required="true" />
  </label>
  <label>
    <input type="text" />
  </label>
  <textarea required="true"></textarea>
</div>
<p></p>