简体   繁体   中英

How to get selectable div value or id in jquery?

I was trying to get selected div value or id using jquery selectable .My problem is i have div inside for loops so when im trying to get value or id it is giving me only first div value or id.Below is my code.

<input type="text" id="mod">
    <div class="row">
      <?php for($i=0;$i<4;$i++){ ?> 
      <div class="col-lg-3 col-md-3 col-sm-6 col-xs-12 list"   >
        <div class="dashboard-stat blue cmp" value="<?php echo 'test'.$i; ?>" id="<?php echo 'test'.$i; ?>">
          <div class="visual">
           <i class="fa fa-comments"></i>
          </div>
          <div class="details ">
            <div class="desc" > akak</div>
          </div>
        </div>
      </div>
      <?php }?>
    </div>

When i am selecting div it should give value of cmp div.But when im selecting every time same value is coming.I am trying to get this value inside hidden text box.Below is my JS code.

$(".list").selectable({
    stop: function() {
     $(".cmp", this).each(function() {
      var index  =$(this).attr('data');
      console.log($('.cmp').attr('id'));
      items += ("," +(index));
     });
      $('#mod').val(items);
    }
}) 

Thanks in advance.

You are using

$('.cmp').attr('id')

which will give you all div with class value having cmp and calling attr('id') will give you id of first div only.

As you are iterating through list of divs, you must use $(this) which will give you the current div in the loop as shown below

$(this).attr('id')

Consider looking into documentation at this URL: http://jqueryui.com/selectable/#serialize

it will give you exactly what you need.

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