WEI ZHUANG GOH
WEI ZHUANG GOH

Reputation: 333

How to check html table cell value in every rows and columns

I want to make a validation in my script. User need to input unique string only in order to insert to the html table. When user input and click submit, the script should check on the existing html table's cells value and then compare with the user input. If the user input is unique it will then insert to the html table. But if the user input is not unique, an alert pop up message will be prompt saying existed. So how can I check every column and rows of the table cells value?

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>


<input type='text' id='field1' />
<input type='text' id='field2' />
<input type='text' id='field3' />
<button id='add' >Add </button>


<table id='table'>
<tr>
  <th>Field 1 </th>
  <th>Field 2 </th>
  <th>Field 3 </th>
</tr>

</table>

$(function(){
  
  $('#add').on('click',function(){
      
      var field1=$('#field1').val();
      var field2=$('#field2').val();
      var field3=$('#field3').val();
      
      var data=`<tr><td>`+field1+`</td>`+
                      `<td>`+field2+`</td>`+
                      `<td>`+field3+`</td></tr>`;
      $('#table').append(data);
      
    });


});

Upvotes: 0

Views: 339

Answers (1)

Here is an example of a way to do it.

var m = $('#table td').filter(function() {
  return $(this).text() == field1 || $(this).text() == field3 || $(this).text() == field3
})

now you can check if m.length is equal to 0 if so then the words are unique.

Demo

$(function() {

  $('#add').on('click', function() {

    var field1 = $('#field1').val();
    var field2 = $('#field2').val();
    var field3 = $('#field3').val();

    var okay = true;

    var data = `<tr><td>` + field1 + `</td>` +
      `<td>` + field2 + `</td>` +
      `<td>` + field3 + `</td></tr>`;


    var m = $('#table td').filter(function() {
      return $(this).text() == field1 || $(this).text() == field3 || $(this).text() == field3
    })

    if (m.length == 0) {
      $('#table').append(data);
    }
  });
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type='text' id='field1' />
<input type='text' id='field2' />
<input type='text' id='field3' />
<button id='add'>Add </button>


<table id='table'>
  <tr>
    <th>Field 1 </th>
    <th>Field 2 </th>
    <th>Field 3 </th>
  </tr>

</table>

Upvotes: 2

Related Questions