Validation of a Dynamic Select Option

Asked

Viewed 332 times

2

Guys I need a super help!

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

                            <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>

inserir a descrição da imagem aqui

The contents of SELECT OPTION are the same in all fields.

What I need: to perform a validation so that the user does not select the same item twice, displaying some message or an alert warning that the item "Email" (EXAMPLE) has already been selected in the previous SELECT OPTION.

Can anyone help me with any suggestions?

  • 1

    And when the warning shows what happens to duplicate options? changes the first, the last or the two?

  • Sergio, it should continue on the same page, until you fill all fields without any repeat, gave to understand?

  • @Vitor You managed to solve the problem?

1 answer

1

I’d do it this way:

Define the Count function within the scope of an object of the Array type

    // 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 selected options

var opts = [];

Place a change event in your selects

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

Browser other questions tagged

You are not signed in. Login or sign up in order to post.