Search code examples
javascripthtmldatabaseweb

How to show elements based on database value


In the page that I work on, there is two different elements that I want to show based on the database value. When the value was 'picked', it will showing the process and if the value was 'send' it going to be showing the receipt number.

I tried using some JavaScript, but it doesn't work and I still need to change the text first before the element showing. Is there any way for the element showing up immediately when the page is loaded? This is the JavaScript code:

$(function(){
  $('input:text').change(function(){
    if($(this).val() =="picked") {
      $("#picked").show();
      $("#send").hide();
    }
    else {
      $("#picked").hide();
      $("#send").show();
    }
  });
});

And this is the HTML code:

<tr>
  <th>Metode</th>
  <td>
    <input class="metode" type="text" id="metode" value="{{ $p->methode }}" style="border: none;">
  </td>
</tr>
<tr id="send" style="display: none;">
  <th>Receipt</th>
  <td>{{ $p->receipt }}</td>
</tr>
<tr id="picked" style="display: none;">
  <th>Process</th>
  <td>{{ $p->process }}</td>
</tr>

Solution

  • The problem is you are using tr tag . In tr tag display: none will not work. And before value change you need to show/hide as well.

    $(function() {
      change()
      $("#metode").change(function() {
        change()
      });
    
    
      function change() {
        if ($('#metode').val() == "picked") {
          $("#picked").show();
          $("#send").hide();
        } else {
          $("#picked").hide();
          $("#send").show();
        }
      }
    });
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
    <tr>
      <th>Metode</th>
      <td>
        <input class="metode" type="text" id="metode" value="{{ $p->methode }}" style="border: none;">
      </td>
    </tr>
    <div id="send" style="display: none;">
      <th>Receipt</th>
      <td>{{ $p->receipt }}</td>
    </div>
    <div id="picked" style="display: none;">
      <th>Process</th>
      <td>{{ $p->process }}</td>
    </div>