Dumm My
Dumm My

Reputation: 21

show alert if data is found - JQUERY

How can I create a filter like search data from database if it already exist show a certain element or show alert script.

Sample I have this code.

NOTE: *The input is inside a form.

<div>
  <input type="text" id="key"><span id="alert" style="display:none;">Data already exist</span>
</div>

This is where the data is compared on the input tag that is typed above.

NOTE: *assume that the code and elements is properly coded.
           

<?php foreach(getData() as $row)
{?>
  <tr class="data">
    <td><?php echo $row['samp1'];?></td>

  </tr>
<?php }?>

Basically show a warning alert beside the input field if the data exist.

if found this code

$("#key").on("keyup",function(){
  var val = $(this).val();

  $(".tr").filter(function(){
    $(this).toggle($(this).text().indexOf(val) > -1)
  });
});

It should be something like this but the tr is for comparing.

what I want is that when data is found the span tag shows.

Upvotes: 0

Views: 262

Answers (1)

muka.gergely
muka.gergely

Reputation: 8329

I think there's another approach to this question, that makes doing it much simpler: only output a data constant with PHP, and wrap it in a table with jQuery. This way you can handle your data (and its presentation) in a much more flexible way.

Here's the snippet I thought of:

// only rowData should be echoed with PHP

const rowData = [
  10,
  12,
  15,
  67
];

// displaying the table of data
$.each(rowData, function(i, el) {
  var row = '';
  row += '<tr><td>';
  row += el;
  row += '</td></tr>';
  $("#data-table").append(row);
});


// handling input and validation
$("#key").on("keyup", function() {

  var val = $(this).val();

  // native ES6 array.find syntax 
  var found = rowData.find(item => item == val);

  // displaying / hiding the alert
  if (typeof found !== 'undefined') {
    $("#alert").css("display", "block");
  } else {
    $("#alert").css("display", "none");
  }

});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div>
  <input type="text" id="key"><span id="alert" style="display:none;">Data already exist</span>
</div>
<table id="data-table">
</table>

Upvotes: 1

Related Questions