如何从选项中选择后使用jQuery计算相同数量的图片?

时间:2017-05-30 14:31:04

标签: javascript jquery html

我从不同的选择菜单下拉,当选择任何选项时,它的图片被加载。例如见图:

enter image description here

现在我的问题是找到我选择了相同选项的次数或者div中有多少具有相同名称的图片。尝试两种方式但未能得到正确的方法。

我试过这个var count = $("#some_id").find('img').length;,但每次都没有给出适当的价值。此外,我试图放置全局计数器myFuncCalls,但这样做只计算总选择数不是特定的,例如已经选择了两个苹果,但它给出了3.而不是2.

这是我的代码HTML:

<select id="fruits" name="fruits[]" class="form-control" style="width:19%;float:left;">
  <option value="">Fruit</option>
  <option value="Apple" onclick="pic('apple.png','apple',0);">Apple</option>
  <option value="Apple Black Currant" onclick="pic('AppleBlackCurrant.png','AppleBlackCurrant',0);">Apple</option>      
</select>

<select name="menuItems[]" id="Strawberry" class="form-control" style="width:19%;float:left;" onchange="">
  <option value="">Recess </option>
  <option value="Milk Strwaberry" onclick="pic('MilkStrwaberry.png','MilkStrwaberry',0);">Milk Strwaberry</option>
</select>

JS

//same for other
//v is picture
//name is picturename
//flag for yes or no
function pic(v, names, flag) { //alert(flag);
  //alert($(".fruits option:selected[value='"+names+"']").length);
  if (flag == 1) {
    if (myFuncCalls > 0) {
      alert("You can only select one item from each category");
      return false;
    } else {
      myFuncCalls++;
      // alert('s'+v);
      //alert(myFuncCalls);
      $("#image1").prepend('<div id="c" class="thumbnail" style="width:20%;float:left;background: rgb(238, 238, 238) none repeat scroll 0px 0px;"><img class="remove-img glyphicon glyphicon-remove" src="<?php echo base_url(); ?>assets/img/cross.png" style="float:right; vertical-align:top; height:18px; width:18px; z-index:9999;" ><img id="imgpic" src="<?php echo '
        http: //localhost:8080/catering/uploads/'?>'+ v +' " style="width:100px"></div>');
        $('.remove-img').click(function (e) {
          $(this).parent().find('img').remove();
          myFuncCalls = 0;
        });
      }
    }
    if (flag == 0) { //0 means No
      myFuncCalls++;
      // alert('s'+v);
      //alert(myFuncCalls);
      $("#image1").prepend('<div id="c" class="thumbnail" style="width:20%;float:left;background: rgb(238, 238, 238) none repeat scroll 0px 0px;"><img class="remove-img glyphicon glyphicon-remove" src="<?php echo base_url(); ?>assets/img/cross.png" style="float:right; vertical-align:top; height:18px; width:18px; z-index:9999;" ><img id="imgpic" src="<?php echo '
        http: //localhost:8080/catering/uploads/'?>'+ v +' " style="width:100px"></div>');

        $('.remove-img').click(function (e) {
          $(this).parent().find('img').remove();
          myFuncCalls = 0;
        });
      }
    }
  }
}

0 个答案:

没有答案