Search code examples
jqueryhtmljquery-knob

How to change knob value dynamically in jquery..?


I have applied a jquery knob with readonly feature as follows :

<style>
.test{
    background: #292929;
    margin:50px;
}
</style>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script src="https://raw.github.com/aterrien/jQuery-Knob/master/js/jquery.knob.js"></script>
<body>

<input type="text" value="45%" class="dial"><button id="change">Change</button>
</body>
<script>
$(".dial").knob({
    readOnly: true,
    fgColor: "#00ABC6",
    bgColor: "#666666",
    thickness: 0.2
                });

$(document.body).on('click', 'button#change', function(){
    $("input.dial").val('80%');
    })
</script>

Now when i click on change button it only changes the value of input tag but failed to change the percentage on knob filled area.


Solution

  • Just trigger an change event on the input after setting the value for it like :

    $("input.dial").trigger('change');
    

    Your code will look like :

    <style>
    .test{
        background: #292929;
        margin:50px;
    }
    </style>
    <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
    <script src="https://raw.github.com/aterrien/jQuery-Knob/master/js/jquery.knob.js"></script>
    <body>
    
    <input type="text" value="45%" class="dial"><button id="change">Change</button>
    </body>
    <script>
    $(".dial").knob({
        readOnly: true,
        fgColor: "#00ABC6",
        bgColor: "#666666",
        thickness: 0.2
                    });
    
    $(document.body).on('click', 'button#change', function(){
        $("input.dial").val('80%');
        $("input.dial").trigger('change');
        })
    </script>