Sachin Zade
Sachin Zade

Reputation: 90

getting blank value using this variable

I get a blank value on click of anchor tag using this operator. I have multiple divs with same class thats why I used .each() function, I dont know where am I doing wrong. Output should be, on click one the first value should appear in input and so on here is my code

$(document).ready(function(){
  $('.main').each(function(){
    $('a',this).click(function(){
      $val = $('p',this).text();
      $("#aarti").val($val);
      alert($val);
    });
  });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="main">
  <p>value one</p>
  <div id="sub" style="display: block;">
    <p><a href="#" data-toggle="modal" data-target="#myContactModal">CLICK ONE</a></p>
  </div>
</div>
<div class="main">
  <p>value two</p>
  <div id="sub" style="display: block;">
    <p><a href="#" data-toggle="modal" data-target="#myContactModal">CLICK TWO</a></p>
  </div>
</div>
<div class="main">
  <p>value three</p>
  <div id="sub" style="display: block;">
    <p><a href="#" data-toggle="modal" data-target="#myContactModal">CLICK THREE</a></p>
  </div>
</div>
<div class="main">
  <p>value four</p>
  <div id="sub" style="display: block;">
    <p><a href="#" data-toggle="modal" data-target="#myContactModal">CLICK FOUR</a></p>
  </div>
</div>
<input type="text" id="aarti" />

Upvotes: 0

Views: 40

Answers (3)

LittleHoopoe
LittleHoopoe

Reputation: 91

$('.main').on('click', 'a', function(e) {
      var $val = $(this).find('p').text();           
      alert($val);
});

Should help

Upvotes: 0

Satpal
Satpal

Reputation: 133403

You need traverse up to parent main element, then target its child p element

 jQuery(document).ready(function() {
   $('.main a ').click(function(e) {
     e.preventDefault();
     var $val = $(this).closest('.main').children('p').text();
     $("#aarti").val($val);
   });
 });
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="main">
  <p>value three</p>
  <div id="sub" style="display: block;">
    <p><a href="#" data-toggle="modal" data-target="#myContactModal">CLICK THREE</a>
    </p>
  </div>
</div>
<div class="main">
  <p>value four</p>
  <div id="sub" style="display: block;">
    <p><a href="#" data-toggle="modal" data-target="#myContactModal">CLICK FOUR</a>
    </p>
  </div>
</div>


<input type="text" id="aarti" />

Upvotes: 1

Kinshuk Lahiri
Kinshuk Lahiri

Reputation: 1500

There is no need to loop through the main class. Just click on the main you want and this will get it and can do the rest for you

Try this:

 $(document).on('click','.main',function(){
   $("#aarti").val($(this).find('p').html());
 });

Upvotes: 0

Related Questions