简体   繁体   中英

How to compare ul li text and array value

I am working in jQuery Vector Map, user selected region names I have to added in UL li tag. I done it so for, whenever user click vector map region, corresponding region value getting updated in li tag.

Now I have to do the condition,

If user selected region value is already there in li list item. I have to show alert ('user selected region is already in the list');

if user selected region value is not there in li item, I have to added the region value to li item.

Here the sample code - ( user selected region state value i am getting in "region" )

   var regionList = new Array('Alaska','Alabama','Arkansas','Arizona', etc....) /* sample array*/


   if( li item text value  == arrayvalue) /*exact condition statement I want*/
   {
       alert("user selected region already in the list")

   }
    else
   {
          $('<li>' + region + '</li>').appendTo('ul#location-selected');
   } 


   <ul id="location-selected" style="font-weight:bold;width:350px;padding-top:15px;color:red;"></ul>

Please help me to complete this..

var ul = document.getElementById('location-selected');
var lis = ul.getElementsByTagName('li');

for(var i = 0; i < lis.length; i++){
    if(lis[i].innerHTML === region) {
        isInList = true;
        break;
    }
}

if(isInList)
    alert("user selected region already in the list")
else {
    var newli = document.createElement('li');
    newli.innerHTML = region;
    ul.appendChild(newli);
}

jQuery:

var ul = $('#location-selected');
var lis = ul.children('li');

var isInList = false;
for(var i = 0; i < lis.length; i++){
    if(lis[i].innerHTML === region) {
        isInList = true;
        break;
    }
}

if(isInList)
    alert("user selected region already in the list")
else
    var newli = $('<li></li>').html(region).appendTo(ul);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM