简体   繁体   中英

How do I retrieve textblock value with onclick handler and show it using alert function in jQuery?

code:

<a class='link' href='javascript:void(0)' id='".str_replace(" ",'-',$sub_head)."'>
    <i class='fa fa-angle-double-right'></i>&nbsp;".$sub_head."
</a>
<input type='text' name='tag' class='tag' value='' />

<script>
    $(document).ready(function(){
        $(".link").bind("click", function() { 
            link = $(this).attr( 'id' );
            tag = $(".tag").val(link);
            alert(tag);
        });
    });
</script>

In this code I have create a link where class has to be define as link and inside id having dynamic value. Now what I want when I click on link then id of tag go to input field ie tag. Now what happen When I click on link it show me [object Object] in alert box but I want value. So, How can I do this?Please help me.

Thank You

Because $(".tag").val(link) set value for $(".tag") and it return object you should use .val() to get value of $(".tag") or you can alert value directly with alert(link); it return same value as $(".tag").val()

 $(document).ready(function() { $(".link").bind("click", function() { var link = $(this).attr('id'); $(".tag").val(link); val = $(".tag").val(); alert(val); }); }); 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <a class='link' href='javascript:void(0)' id='5678'> <i class='fa fa-angle-double-right'></i> Click </a> <input type='text' name='tag' class='tag' value='' /> 

This line makes the input tag get a new value, but also returns just the input element:

tag = $(".tag").val(link); 

Then the next line is actually alerting the entire input element object:

alert(tag);

To only alert the value of the input element, write:

tag = $(".tag")
tag.val(link); 
alert(tag.val());

You can see the difference between val(arg) and val() in jquery's documentation at http://api.jquery.com/val/ .

You can use this code, it's working fine for your requirements.

  $(document).ready(function(){ $(".link").on("click", function() { var link = $(this).attr( 'id' ); var tag = $(".tag").val(link); alert($(".tag").val()); }); }); 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <a class='link' href='javascript:void(0)' id='id_1'> <i class='fa fa-angle-double-right'></i>&nbsp;Sub Heading </a> <input type='text' name='tag' class='tag' value='' /> 

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