javascriptknockout.jsknockout-mapping-plugin

knockout js change div width as per textbox value


I am new to knockout js and need help. I want, when I will add number in text box division should resize to that size of pixel.

Following is the code:

    <html> 
        <head> 
            <style type="text/css"> 
                #myDiv { 
                        border:solid 1px #f00; 
                } 
                #myOtherDiv { 
                        border:solid 1px #00f; 
                        width: 150px; 
                } 
            </style> 
            <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
            <script src="http://cdnjs.cloudflare.com/ajax/libs/knockout/2.1.0/knockout-min.js"></script>
            <script type="text/javascript">
                $(document).ready(function(){

                     var viewModel = { 
                            myWidth: ko.observable( '250px'), 
                            anotherDiv: ko.observable('KO is working') 
                        }; 
                        ko.applyBindings(viewModel); 
                });
            </script>
        </head> 
            <body>
                    <div id="myDiv" data-bind="style: { width: myWidth }">
                       Some Text 
                    </div> 
                    <div id="myOtherDiv"> 
                            Some More Text 
                    </div> 
                    <div data-bind="text: anotherDiv"></div> 
                    Enter size<input type = text />
            </body> 
    </html>

Solution

  • You should bind input field tomyWidth property:

    Enter size <input type = text data-bind="value: myWidth"/>
    

    Also link to knockout is broken try this one: http://ajax.aspnetcdn.com/ajax/knockout/knockout-2.2.0.js

    Here is a working fiddle: http://jsfiddle.net/wAYqY/