Get value of input in jQuery

2019-01-29 01:45发布

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()?

5条回答
疯言疯语
2楼-- · 2019-01-29 01:49

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" />
查看更多
叼着烟拽天下
3楼-- · 2019-01-29 01:53

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;
    });
});
查看更多
啃猪蹄的小仙女
4楼-- · 2019-01-29 01:56

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

查看更多
迷人小祖宗
5楼-- · 2019-01-29 02:09

use

alert(jQuery(this).val());
查看更多
太酷不给撩
6楼-- · 2019-01-29 02:10
$(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

查看更多
登录 后发表回答