mercredi 10 octobre 2018

Jquery - wildcard ID, Conditional value check fails if the first occurrence fails

I have the following simple HTML:

        <dl>
            <dt>Percentage</dt>
            <dd><input type="text" id="percentage1" value="20"/></dd>
            <dt>Description</dt>
            <dd><input type="text" id="wastetype1" value="Inert - Mixed"/></dd>
        </dl>
        <dl>
            <dt>Percentage</dt>
            <dd><input type="text" id="percentage2" value="20"/></dd>
            <dt>Description</dt>
            <dd><input type="text" id="wastetype2" value="Brick"/></dd>
        </dl>
        <dl>
            <dt>Percentage</dt>
            <dd><input type="text" id="percentage3" value="60"/></dd>
            <dt>Description</dt>
            <dd><input type="text" id="wastetype3" value="Concrete"/></dd>
        </dl>

I want to conditionally add the the values of those fields into an object using the following code:

if (($('[id^=percentage]').val().length > 0) || ($('[id^=wastetype]').val().length > 0)){
    var breakdownArray = [];
    $('[id^="percentage"]').each(function() {
        var thisId = $(this).attr('id').substring(10);
        if (($('#percentage'+thisId).val().length > 0) && ($('#wastetype'+thisId).val().length > 0)){
            var breakdownObject = {};
            breakdownObject.percentage = $('#percentage'+thisId).val();
            breakdownObject.description = $('#wastetype'+thisId).val();
            breakdownArray.push(breakdownObject);
        }
    });
    postData.breakdown = breakdownArray;
}

I am particularly vexed by the if statement

if (($('[id^=percentage]').val().length > 0) || ($('[id^=wastetype]').val().length > 0))

I was expecting this to pass the test if ANY of the field matching those Id's had values.

However, If percentage1 and wastetype1 are empty the whole 'if' statement fails, regardless of any other values in any other fields.

If I leave percentage3 and wastetype3 blank it works just fine.

It would seem that if the first set of fields are empty the whole thing fails but not of any of the others are empty?!?

Any help on would be appreciated.

Aucun commentaire:

Enregistrer un commentaire