Christine Ong
Christine Ong

Reputation: 51

How can i change the value of checkbox upon change

I would like to change the value of the checkbox, but failed with the following code.


$("input:checkbox").on("change", function () {
    if (this.checked == true) {
        this.val("1");
    }
    else {
        this.val("0");
    }
});

I not sure why it is no responds without the code, which it should've the "checked" when I'm calling this element, but no. So i will need to add a value field manually.

<input class="c-switch-input" type="checkbox" name="pk_{{$d['id']}}" value="{{$d['status']}}">

Upvotes: 1

Views: 42

Answers (1)

mplungjan
mplungjan

Reputation: 177841

You are mixing jQuery and DOM incorrectly

EITHER

this.value = "1";

OR

$(this).val("1")

But use a ternary:

$("input:checkbox").on("change", function () {
   this.value = this.checked  ? "1" : "0";
   console.log(this.value)
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type="checkbox" />

Upvotes: 1

Related Questions