最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Get value of input in jQuery - Stack Overflow

programmeradmin0浏览0评论

I want to redirect to another page when a checkbox is clicked.

<script type="text/javascript"><!--
$(document).ready(function(){
    jQuery(".cbno").click(function(e){
        e.preventDefault();
        alert('test');
        alert(this.val());
//      window.location = this.val();
    });
});
//-->
</script>

<input type="checkbox" class="cbno" name="content" value="/map/?filter=all" />

Pretty simple - but I cannot figure out why the second alert does not produce any output? Internet Explorer says: "The object does not support the method val".

It works if I use this.getAttribute('value') - why does it not work with the jquery val()?

I want to redirect to another page when a checkbox is clicked.

<script type="text/javascript"><!--
$(document).ready(function(){
    jQuery(".cbno").click(function(e){
        e.preventDefault();
        alert('test');
        alert(this.val());
//      window.location = this.val();
    });
});
//-->
</script>

<input type="checkbox" class="cbno" name="content" value="/map/?filter=all" />

Pretty simple - but I cannot figure out why the second alert does not produce any output? Internet Explorer says: "The object does not support the method val".

It works if I use this.getAttribute('value') - why does it not work with the jquery val()?

Share Improve this question edited May 3, 2012 at 17:57 Brad Fox 6816 silver badges19 bronze badges asked Apr 7, 2012 at 10:37 reggiereggie 3,67414 gold badges64 silver badges102 bronze badges
Add a ment  | 

5 Answers 5

Reset to default 4

use

alert(jQuery(this).val());

Any of $(this).val() or $(this).attr("value") or this.getAttriute("value") or this.value will work

Please be consistent on $ () and jQuery()

<script type="text/javascript"><!--
$(document).ready(function(){
    $(".cbno").click(function(e){
        e.preventDefault();
        window.location = $(this).val();
    });
});
//-->
</script>

<input type="checkbox" class="cbno" name="content" value="/map/?filter=all" />

because this is not a jQuery object. you need to use $(this).val();

Change:

alert(this.val());

To:

alert($(this).val());

$(this) refers to checkbox you are after.


You can also simply use:

this.value

So you can modify your code like this:

$(document).ready(function(){
    jQuery(".cbno").click(function(e){
        e.preventDefault();
        alert(this.value);
        //window.location = this.value;
    });
});
$(document).ready(function(){
    jQuery(".cbno").click(function(e){
        e.preventDefault();
        alert('test');
        alert( $(this).val());
//      window.location = $(this).val();
    });
});

this in events function is a link to the DOM element, so you should create a jQuery object with it`s methods to take them

发布评论

评论列表(0)

  1. 暂无评论