stockBoi
stockBoi

Reputation: 287

how to get text from hidden input element nested in a div

I have the following html code:

<a class="tog" href="#">Click Me</a> 
<div class="result">
    <input type="hidden" name="hid" value="val01" />
    This is a container div
</div> <br />
<a class="tog" href="#">Click Me</a> 
<div class="result">
    <input type="hidden" name="hid" value="val02" />
    This is a another container div
</div>

How can I get value from hidden input on click of <a>? I am trying with this jquery code but it is failing to retrieve value from those hidden input element.

$(document).ready(function(){
 $(".tog").click(function(){
   var $this=$(this);
 if (!$this.next(".result").data('loaded')){ 
   alert($this.next("input[name=hid]").val());
  }
 });
});

Upvotes: 1

Views: 6535

Answers (4)

arjuncc
arjuncc

Reputation: 3297

The problem with your code is that, you are using the next() which is by documentation is used to Get the immediately following sibling of each element in the set of matched elements. If a selector is provided, it retrieves the next sibling only if it matches that selector.. here your '$this' points to the anchor, and when you try to execute $this.next("input[name=hid]").val() it dont have any immediate sibling named "hid", thats why you are getting am undefined.

Try this code:

$(document).ready(function(){
    $(".tog").click(function(){
       var $this=$(this);
    alert($this.next("div").find("input[name=hid]").val());   
     });
});

jsfiddle

Upvotes: 0

palaѕн
palaѕн

Reputation: 73966

Simple

$(".tog").click(function () {
    var $this = $(this);
    if (!$this.next(".result").data('loaded')) {
        alert($this.next(".result").children("input:hidden").val());
    }
});

Upvotes: 1

Peter Rasmussen
Peter Rasmussen

Reputation: 16942

You can do the following:

Get the next element which is the div with the result class. From there you find the hidden Input and get it's value.

Demo

Javascript:

$(document).ready(function(){
    $(".tog").click(function(){
        var atag = $(this);
        var hiddenInput = atag.next().find('input[type=hidden]');
        alert(hiddenInput.val());         
    });
});

Upvotes: 0

Anujith
Anujith

Reputation: 9370

It should be:

$(document).ready(function () {
  $(".tog").click(function () {
    var $this = $(this);
    if (!$this.next(".result").data('loaded')) {
        alert($this.next().find("input[name=hid]").val());
    }
  });
});

Demo

Upvotes: 0

Related Questions