DB1500 DB1500 - 4 years ago 65
CSS Question

If and else code blocks running together

I am trying to cycle through a form on load (that may have fields pre-populated) and assign a check or a cross if the field is filled in or blank respectively.

The jQuery is:



$(document).ready(function(){

// test code for dynamic validation
var $feedback = '.form-feedback';
var $icon = 'i';
var $good = 'ion-checkmark-circled';
var $bad = 'ion-close-circled';

// form selectors
var arr = ["username", "first-name", "last-name"];

$.each(arr, function(i, val) {
if ($("#form-" + val ).val() !== '') {
console.log("#form-" + val + ": "+ $good);
$("#form-" + val ).siblings($feedback).find($icon).addClass($good);
} else {
console.log("#form-" + val+ ": "+ $bad);
$('.main-input-field input').siblings($feedback).find($icon).addClass($bad);
}
});

});

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<p>Username:</p>
<p class="main-input-field"><input id="form-username" class="username" type="text" name="UserName" ><span class="form-feedback"><i></i></span></p>
<p>First Name:</p>
<p class="main-input-field"><input type="text" id="form-first-name" name="FirstName" ><span class="form-feedback"><i></i></span></p>
<p>Surname:</p>
<p class="main-input-field"><input type="text" id="form-last-name" name="Surname" ><span class="form-feedback"><i></i></span></p>





As you can see I have a blank
<i>
element which I want to add a class which will display either a check or a cross. When the input field is blank it works great, but if the input field has a value, it runs the code then also adds the else code (i.e. adds the $good class then adds the $bad class as well). The result is a cross on all outcomes.

Any help?

Thanks.

Answer Source

It's not because else runs as well. It is because you are using siblings().

try to run this:

console.log($('.main-input-field input').siblings('.form-feedback'));

you will change them all. Read documentation on how siblings works

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download