ihue ihue - 4 months ago 7
HTML Question

Check on checkbox, reset an input

I have



an input and a checkbox.

enter image description here




My goal



is when the user change something on the input box, I want to start showing the
set to default
checkbox.

Then, when the
set to default
checkbox is
check
, I want to set back the original value into that input.




Here is what I have tried

HTML



<div class="col-xs-4">
<input id="onboard_url" value="{{ $g_portal_url or ''}}" class="form-control" name="onboard_url" required placeholder="Ex. https://www.onboading.com" >
</div>

<div class="col-xs-2" style="display: none;" id="onboard_url_default">
<input type="checkbox" id="onboard_url_default_cb" value="0" >
Set to default
</div>





jQuery



$('#onboard_url').on('keyup', function() {
$('#onboard_url_default').show();

if($('#onboard_url_default_cb').prop('checked')){
$('#onboard_url_default_cb').val(1);
console.log('checked');
$("#onboard_url").val('');
$("#onboard_url").val('{{ $g_portal_url or ''}}');
}
});





$('#onboard_url').on('keyup', function() {
$('#onboard_url_default').show();

if($('#onboard_url_default_cb').is(':checked')){
$('#onboard_url_default_cb').val(1);
console.log('checked');
$("#onboard_url").val('');
$("#onboard_url").val('{{ $g_portal_url or ''}}');
}
});





Result



I couldn't get my
console.log
to print.

I'm not sure what I missed here. :(

Answer

I think, using checkbox for this situation is wrong for UX. The best way is using a button for it. Here is my code is for button;

$(function(){
    $('#your_button').click(function(){
        $("#onboard_url").val('');
        $("#onboard_url").val('{{ $g_portal_url or ''}}');
    });
});

For checkbox, this is the solution;

$(function(){
    $('#onboard_url').on('keyup', function() {
        $('#onboard_url_default').show();
    });

    $('#onboard_url_default_cb').on('change', function(){
        if($(this).prop('checked')){
            $(this).val(1);
            $("#onboard_url").val('');
            $("#onboard_url").val("{{ $g_portal_url or ''}}");
        }
    });
});
Comments