Get value of input in jQuery

2019-01-29 01:14发布

问题:

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

回答1:

use

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


回答2:

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:

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



回答4:

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;
    });
});


回答5:

$(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