Home » Jquery » javascript – Just trying out to check whether the value is present in array or not

javascript – Just trying out to check whether the value is present in array or not

Posted by: admin February 22, 2020 Leave a comment

Questions:

I am trying to write a function in jQuery.

var arr1 = ["Jcob", "Pete", "Fin", "John"];
var str = $("#fname").val();
if (jQuery.inArray(str, arr1))
  $("#lname").text("Bob");
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type="text" id="fname" name="fname">
<input type="text" id="lname" name="lname">

Please check my fiddle here

What it will do it the user will give the value in the first input box the jQuery function will check if the value is present in that array it will fill the second input box with the given text.

How to&Answer:

Three things:

  1. You need to add an event listener to the first input to constantly keep checking when someone inputs something.
  2. Before selecting elements in the DOM, make sure the DOM is ready.
  3. You don’t need jQuery at all here. Like most things, very easy to do without jQuery.
const names = [ "Jcob", "Pete", "Fin", "John" ];
document.addEventListener('DOMContentLoaded', function() {
  const fname = document.getElementById('fname');
  const lname = document.getElementById('lname');
  fname.addEventListener('input', function(event) {
    lname.value = names.includes(fname.value) ? 'Bob' : '';
  });
});
<input type="text" id="fname" name="fname">
<input type="text" id="lname" name="lname">

If you insist on jQuery (which I do strongly recommend you shouldn’t until you are proficient with the native DOM API):

const names = [ "Jcob", "Pete", "Fin", "John" ];
$(document).ready(function() {
  const $fname = $('#fname');
  const $lname = $('#lname');
  $fname.on('input', function(event) {
    if ($.inArray($fname.val(), names) > -1) {
      $lname.val('Bob');
    } else {
      $lname.val('');
    }
  });
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type="text" id="fname" name="fname">
<input type="text" id="lname" name="lname">

Answer:

Try this:

<body>

    <input type="text" id="fname" name="fname">
    <input type="text" id="lname" name="lname">
    <button onclick="checkValue()">Click</button>

    <script>
        var arr1 = ["Jcob", "Pete", "Fin", "John"];

        function checkValue() {
            var str = $("#fname").val();
            var val = jQuery.inArray(str, arr1);
            if (val === -1) {
                console.log("no value");
            }
            else {
                $("#lname").val("Bob");
            }

        }
    </script>
</body>