简体   繁体   中英

Deleting value in hiddenfield when checkbox is unchecked jquery

I am pretty new with jquery and javascript. But i have made this function. When a checkbox is checked, it's value get set in a hiddenfield. Here is the function.

<script>
    $('#checkDk').on('change', function () {
        $('#MainContent_hiddenTargetDk').val($(this).val());
        console.log($("#MainContent_hiddenTargetDk").val());
    });
</script>

I dont know if this is the best way of doing it, but it works. The problem is when the checkbox is unchecked the value does not get deleted from the hiddenfield. I have been searching a bit around and found this.

var value = this.checked ? this.value : "";

Can you somehow use this to check if it is checked or not? And if yes how do i incorporate it in my function?

Here is the checkbox html.

<input id="checkDk" type="checkbox" value="208" onselect="getvalue()" autocomplete="off">

This should work:

<script>
    $('#checkDk').on('change', function () {
       $('#MainContent_hiddenTargetDk').val( $(this).prop("checked") ? $(this).val(): "");
        console.log($("#MainContent_hiddenTargetDk").val());
    });
</script>
$('#checkDk').on('change', function () {
    if(this.checked){
      var hidden = $('<input />').attr('type', 'hidden')
                                 .addClass('chooseNameHere')
                                 .val($(this).val());
      $('#yourFormId').append(hidden);
    }else{
      $('#yourFormId').find('input[name=chooseNameHere]').remove();
    }
});

$("#your_checkbox").prop("checked") should return true or false indicating if the checkbox is checked or not.

Try that instead of val()

Try

<script>
$('#checkDk').on('change', function () {
    if (this.checked) { 
      $('#MainContent_hiddenTargetDk').val($(this).val());
      console.log($("#MainContent_hiddenTargetDk").val());
    } else { $('#MainContent_hiddenTargetDk').val(''); }
});
</script>    

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