AlwaysStudent
AlwaysStudent

Reputation: 1374

Possibility to find a clicked number in a value using jQuery

I want to learn, can we find the same number in two input values. For example:

<input type="hidden" id="multinumber" value="1,2,3,4,5">
<input type="hidden" id="justonenumber" value="3">

<div class="click">Click and test the same number</div>

JS

$(document).ready(function(){

  $("body").on("click",".click", function(){
    var multiple = $("#multinumber").val();
    var single = $("#justonenumber").val();
  });
});

When onClick event on the .click button then check the same number in the #multinumber and #justonenumber input values and get the result in an alert box.

Is there a way to do this ? Anyone can help me here please?

Upvotes: 0

Views: 105

Answers (3)

AdityaParab
AdityaParab

Reputation: 7100

Just use indexOf or includes on your multiple string. :)

$(document).ready(function(){

  $("body").on("click",".click", function(){
    var multiple = $("#multinumber").val();
    var single = $("#justonenumber").val();
    var doesMultipleIncludeSingle = multiple.includes(single);
    // OR
    var doesMultipleIncludeSingle = multiple.indexOf(single) > -1;

  });
});

As per the problem explained in the comment, it seems the requirement does involve splitting the array.

$(document).ready(function(){

  $("body").on("click",".click", function(){
    var multiple = $("#multinumber").val().split(',');
    var single = $("#justonenumber").val();
    var doesMultipleIncludeSingle = multiple.includes(single);
    // OR
    var doesMultipleIncludeSingle = multiple.indexOf(single) > -1;

  });
});

Upvotes: 1

mshouman
mshouman

Reputation: 384

is this what you want?

$(document).ready(function(){

  $("body").on("click",".click", function(){
    var multiple = $("#multinumber").val();
    var single = $("#justonenumber").val();
    if(multiple.indexOf(single) > -1) alert(single + " is found");
    else alert(single + " isn't found");
  });
});

Upvotes: 1

Muhammad Usman
Muhammad Usman

Reputation: 10148

You can get the value of first input box. Split it by , and check with .indexOf for the other input. If it's there, you can put the result in alert box like

$(".click").click(function(){

  var x = $("#multinumber").val().split(",");
  var y = $("#justonenumber").val();
  
  if(x.indexOf(y) > 0){
   alert(x.find(o=> o==y))
  }
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<input type="hidden" id="multinumber" value="1,2,3,4,5">
<input type="hidden" id="justonenumber" value="3">

<div class="click">Click and test the same number</div>

Upvotes: 1

Related Questions