Home > OS >  How can JQuery know if the value inside the input is equal to the value inside the span with which i
How can JQuery know if the value inside the input is equal to the value inside the span with which i

Time:11-30

How can JQuery know if the value inside the input is equal to the value inside the span with which it was created and the duplicate value is deleted

for example

 <div id="tags-here" style="width: 100%;height: 150px;background-color: rgb(173, 199, 196);">
        <input id="make-tags" type="text" class="animated-progress" style="background-color: white;">

    </div>

I've only got as far as this and I'm stumped. I have looked on google but I haven't found anything.

$("#make-tags").on("keyup",function(e){

var key = e.keyCode || e.wich,
inpval = $("#make-tags").val(),
va =  $(".tag-span").val(),


tinpval = $("#make-tags").text(),
tva =  $(".tag-span").text();


if(key === 188 ){  //comma preased
    var value = $(this).val().slice(0, -1);
    $("#tags-here").append("<span class='tag-span'><i class='fas fa-times'></i>"   value  "</span>")
    $(this).val('');   
}

$(".tag-span").each(function(){
            if( inpval === tva){
                console.log("yes")
            }else{
                console.log("nono")
            }
    });

CodePudding user response:

The issue is that in your .tag-span loop, you're comparing the current inpval to tva (which is returning a concatenated string of all span text), but you want to compare it to each .tag-span's text instead. So in the loop, you can pass in the index and item, so then you can access values of each item in the loop:

$(".tag-span").each(function(index, item) {
    if (inpval === $(item).text()) {
        ...
    }
});

Then if it matches, you'll want to take an action and then stop iterating with return false;

$("#make-tags").on("keyup", function(e) {

  var key = e.keyCode || e.wich,
    inpval = $("#make-tags").val(),
    va = $(".tag-span").val(),


    tinpval = $("#make-tags").text(),
    tva = $(".tag-span").text();


  if (key === 188) { //comma preased
    var value = $(this).val().slice(0, -1);
    $("#tags-here").append("<span class='tag-span'><i class='fas fa-times'></i>"   value   "</span>")
    $(this).val('');
  }

  $(".tag-span").each(function(index, item) {
    if (inpval === $(item).text()) {
      console.log("yes")
      // do something
      return false;
    } else {
      console.log("nono")
    }
  });
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="tags-here" style="width: 100%;height: 150px;background-color: rgb(173, 199, 196);">
  <input id="make-tags" type="text" class="animated-progress" style="background-color: white;">
</div>
<iframe name="sif1" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>

  • Related