Mukesh
Mukesh

Reputation: 7798

On clicking an element get child hidden input field's value

In the following code when I click on anchor tag with class des_searchDate I want to get the value of immediate following input field value.

I tried following

<html>
    <div class="searched_date">
        <a href="#" class="des_searchDate">
            04-15-2014
            <input type="hidden" value="2014-04-15" name="searched-date">
        </a><br>
        <a href="#" class="des_searchDate">
            04-09-2014
            <input type="hidden" value="2014-04-09" name="searched-date">
        </a><br>
        <a href="#" class="des_searchDate">
            04-23-2014
            <input type="hidden" value="2014-04-23" name="searched-date">
        </a><br>
     </div>
 </html>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>

<script type="text/javascript">

    jQuery(document).on('click', ".des_searchDate", function(){

    var decDate = jQuery(this).next().find('input').val();

alert(decDate);
});

</script>

But I am getting undefined in alert. What is wrong with my code?

Upvotes: 4

Views: 4398

Answers (5)

Albzi
Albzi

Reputation: 15619

You can do this in pure javascript, no need for jQuery:

Pure JS Fiddle

var sd = document.getElementsByClassName("des_searchDate");

for (i = 0;i<sd.length;i++){
  var s = sd[i];
  s.onclick = function(){
    var input = this.getElementsByTagName("input")[0];
    alert(input.value);
  }
}

Upvotes: 0

Tuhin
Tuhin

Reputation: 3373

$('.des_searchDate').click( function(){
    var decDate = $(this).find('input').val();
    alert(decDate);
});

Upvotes: 1

K K
K K

Reputation: 18109

If you want the value of input inside the clicked anchor:

jQuery(document).on('click', ".des_searchDate", function(){
var decDate = jQuery(this).find('input').val();
alert(decDate);
});

Or if you need the value of next input following the clicked anchor:

jQuery(document).on('click', ".des_searchDate", function(){
var decDate = jQuery(this).nextAll('input:first').val();
alert(decDate);
});

Upvotes: 2

Dan Johnson
Dan Johnson

Reputation: 1482

jQuery(document).on('click', ".des_searchDate", function(){
    var decDate = jQuery(this).find('input').val();
    alert(decDate);
});

Here's a jsFiddle

http://jsfiddle.net/yT777/

Upvotes: 4

Govind Singh
Govind Singh

Reputation: 15490

jQuery(document).on('click', ".des_searchDate", function(){
var decDate = jQuery(this).find('input').val();
alert(decDate);
});

demo fiddle

Upvotes: 3

Related Questions