简体   繁体   中英

accessing value of input field by id using jquery

suppose name of an id is store in a variable x (var x="big";), i was hoping to access the value of an input field whose id is big

eg

<script>
$(document).ready(function(){
    $('#btn').click(function(){

        var x="#"+$(this).attr("name"); ///works fine here
        alert($(x).value());   //hoping to get small but not working

    });


});


</script>
<input type="hidden" value="small" id="big" />
<input type="button" value="click" id="btn" name="big"/>

In your code:

$(x).value()

.value() is not a valid/standred jquery method. For getting the values of text-box, you should use .val() .

Try this:

$(document).ready(function(){
    $('#btn').click(function(){
        var x="#"+$(this).attr("name"); 
        alert($(x).val()); 
    });
});

Working Example

This method is val() :

alert($(x).val());

Live Demo:

http://jsfiddle.net/dreamweiver/4rjjf/

value is not function. change it to val(); here is demo

Demo

$(document).ready(function(){
    $('#btn').click(function(){

        var x=$(this).attr("name"); ///works fine here
        alert($("#"+x).val());   //hoping to get small but not working

    });


});

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