Validation of a Dynamic Select Option

1

I need some super help!

I need to validate a SELECT OPTION that is dynamically generated:

                            <table class="small-grid" style="margin-top:18px;">
                                <?php $i=1; foreach ($ImportFields as $EachField): ?>
                                    <tr>
                                        <td style="text-align:right;"><?php echo $EachField; ?></td>
                                        <td>
                                            <select name="MatchedFields<?php echo $i; ?>" id="MatchedFields<?php echo $i; ?>">
                                                <option value="0"><?php InterfaceLanguage('Screen', '1183'); ?></option>
                                                <?php foreach ($CustomFields as $EachCustomField): ?>
                                                    <option value="CustomField<?php echo $EachCustomField['CustomFieldID']; ?>"><?php echo $EachCustomField['FieldName']; print_r($EachCustomField['CustomFieldID']); ?></option>
                                                <?php endforeach; ?>
                                            </select>
                                        </td>
                                    </tr>
                                <?php $i++; endforeach; ?>
                            </table>

ThecontentsofSELECTOPTIONarethesameinallfields.

WhatdoIneed:todoavalidationsothattheuserdoesnotselectthesameitemtwice,displayingsomemessageoranalertwarningthattheitem"Email" has already been selected in the previous SELECT OPTION. >

Can anyone help me with any suggestions?

    
asked by anonymous 19.05.2016 / 00:36

1 answer

0

I would do it as follows:

Set the count function within the scope of an Array object

    // Definição de função no escopo de Array para contar 
    // quantas vezes um elemento aparece no conjunto.
    // Uso: var x = ['a','a','b','c'];
    //      x.count('a'); // retorna 2
    Array.prototype.count = function (what) {
        var count = 0;
        for (var i = 0; i < this.length; i++) {
            if (this[i] === what) {
                count++;
            }
        }
        return count;
    }

Create an array to save the selected options

var opts = [];

Put a change event on your selections

$('select[id*="MatchedFields"]').on('change', function (){
    if (!(opts.count($(this).val()) > 0)) {
        opts.push($(this).val());
    }else{
      // exibe uma mensagem de campo inválido
    }
});
    
19.05.2016 / 22:03