S.M_Emamian
S.M_Emamian

Reputation: 17393

How to get next element's value - jquery

I have a div like this :

<div id="div_more_info">
    <input placeholder="title" name="title_info" class="title_info" style="margin: 1px" type="text">
    <input placeholder="des" name="des_info" class="des_info" style="margin: 1px;margin-left: 24px" type="text">

    <input placeholder="title" name="title_info" class="title_info" style="margin: 1px" type="text">
    <input placeholder="des" name="des_info" class="des_info" style="margin: 1px;margin-left: 24px" type="text">
</div>

now I would like to get title - value of each row of my div:

$("#div_more_info .title_info").each(function () {
    var title_info = $(this).val();
    var des_info = $(this).next().find('.des_info').val();

    alert(title_info);
    alert(des_info);
});

my code shows title_info value but des_info shows as a undefined .

Upvotes: 2

Views: 80

Answers (4)

John
John

Reputation: 770

You can keep this short:

  $(".title_info,.des_info").each(function() {
      alert($(this).val());
  });

Upvotes: 0

Murad Hasan
Murad Hasan

Reputation: 9583

Just use the next() function of jquery.

Updated Script:

$("#div_more_info .title_info").each(function () {
  var title_info = $(this).val();
  var des_info = $(this).next().val();

  alert(title_info);
  alert(des_info);
});

Fiddle Link

Upvotes: 0

Adam
Adam

Reputation: 1304

Either Kartikeya Khosla solution or could use:

var des_info = $(this).next().val();

Upvotes: 0

Kartikeya Khosla
Kartikeya Khosla

Reputation: 18883

There is no need of .find(), only with .next() you will reach .des_info node.

Instead of

var des_info = $(this).next().find('.des_info').val();

Use

var des_info = $(this).next('.des_info').val();

Upvotes: 6

Related Questions