skip to Main Content

I have an HTML web page which allows a user to enter multiple rows of numbers. I need to add a validation check to check the number entered OR changed does not already exist in the table.

A row is added to the table on button click using the below JQuery

$('table tbody').append(
'<tr>' +
'<td>' +
'<input name="Associated Numbers" class="form-control telNumberInput"' +
' type="text" minlength="11" maxlength="11" placeholder="Enter telephone number" />' +
'<div name="tel-num-error-msg" class="text-danger" style="display: none"></div>' +
'</td>' +
'<td>' +
'<select name="Tel Number Action" class="form-control">' +
'<option value="" selected hidden>Select an option</option>' +
'<option value="One">Test 1</option>' +
'<option value="Two">Test 2</option>' +
'</select>' +
'</td>' +
'<td>' +
'<button name="del-tel-num-btn" class="btn btn-danger bin-icon" type="button">' +
'<i class="bi bi-trash3"></i>' +
'</button>' +
'</td>' +
'</tr>'

)

The above code works fine, but I need to do is on blur or focusout of the input with the focus, I need it to check that the telephone number is not already listed, but I can not get it to work.

This is all the code I have tried but it always displays my error message.

The validation scenario is:

  1. It has more than one row in the table
  2. The input that has been changed (whether updating an existing inputs value or adding the number in the new empty input)

Initial

enter image description here

Button clicked

enter image description here

This is the JQuery I have been trying to use but whenever I have 2 rows in the table it drops in my if and displays the error message even when the telephone number isn’t already listed.

I have tried using array and various if statements. It is probably easier than I’m thinking but im in a hole and "code blind" and can’t think of the code to do it correctly.

$(document).on('focusout', 'input[name="Associated Numbers"]', function() {
// $(document).on('blur', 'input[name="Associated Numbers"]', function() {
    const enteredNum = this.value
    let rowCount = 0
    let errorMsgTxt = ''
    let existingNumbers = []
    // let rowIndex = $(this).closest('#associated-num-tbl tbody tr').index()

    // $('#associated-num-tbl tbody tr').each(function() {
    //     rowCount++
    //
    //     // if (rowIndex !== $(this).index() && rowCount > 1) {
    //     if (rowCount > 1) {
    //         $(this).find('input').each(function () {        //
    //             if (enteredNum === this.value && rowIndex !== $(this).index()) {
    //                 errorMsgTxt = 'has already been added'
    //
    //                 return false
    //             }
    //         })
    //     }
    // })

    $('#associated-num-tbl tbody tr').each(function() {
        rowCount++

        $(this).find('input').each(function () {
            existingNumbers.push(this.value)
        })
    })

    if (rowCount > 1) {
        $.each(existingNumbers, function (i, number) {
            if (number === enteredNum && number !== '') {
            // if (number === enteredNum) {
                $(this).closest('tr').find($('div[name="assoc-num-error-msg"]')).text('Number has already been added').show(0, function () {
                    $(this).closest('td').find('input').trigger('focus')
                })

               return false
            }
        });
    }
});

enter image description here

As you can see the number does not exist in the table

2

Answers


  1. Chosen as BEST ANSWER

    So the fix was to use the index. So I got the table row index of the input changed then in the following each if the index matched the variable stored index number then ignore it

    if (rowCount > 1) {
       $.each(existingNumbers, function (i, number) {
          if (number === enteredNum && i !== rowIndex) {
             $(this).closest('tr').find($('div[name="assoc-num-error-msg"]')).text('Number ' + errorMsgTxt).show(0, function () {
                $(this).closest('td').find('input').trigger('focus')
            })
          }
       });
    }
    

    Full JQuery workout

    $(document).on('blur', 'input[name="Associated Numbers"]', function() {
       const enteredNum = this.value
       let rowIndex = $(this).closest('#associated-num-tbl tbody tr').index()
       let existingNumbers = []
       let rowCount = 0
    
       $('#associated-num-tbl tbody tr').each(function() {
          rowCount++
    
          $(this).find('input').each(function () {
             if (this.value !== '') {
                existingNumbers.push(this.value)
             }
          })
       })
    
       if (rowCount > 1) {
          $.each(existingNumbers, function (i, number) {
             if (number === enteredNum && i !== rowIndex) {
                $(this).closest('tr').find($('div[name="assoc-num-error-msg"]')).text('Number ' + errorMsgTxt).show(0, function () {
                   $(this).closest('td').find('input').trigger('focus')
                })
    
                return false
             }
          })
        }
    })
    

  2. I’ve tried the logic and the code was mentioned below.
    Here I’m using only one loop .each to find the duplicate and show the error message on appropriate tr. May be it’ll helpful to you.

    $(document).on('blur', 'input[name="Associated Numbers"]', function() {
       const enteredNum = this.value;
       const rowIndex = $(this).closest('#associated-num-tbl tbody tr').index();
       let isDuplicate = false;
    
       $('#associated-num-tbl tbody tr').each(function() {
           const inputValue = $(this).find('input[name="Associated Numbers"]').val();
    
           if (inputValue && inputValue === enteredNum && $(this).index() !== rowIndex) {
               isDuplicate = true;
               return false; // Exit the loop on finding a duplicate
           }
       });
    
       if (isDuplicate) {
           $(this).closest('tr').find('div[name="tel-num-error-msg"]')
               .text('Number has already been added')
               .show(0, function() {
                   $(this).closest('td').find('input').trigger('focus');
               });
       } else {
           $(this).closest('tr').find('div[name="tel-num-error-msg"]').hide();
       }
    });
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search