Monday, September 8, 2014

Updating a span when input text changes using javascript or JS SPA framework

JScript

<html>
  <head>
    <meta charset="utf-8">
    <title>DIY One-way Data Binding</title>
  </head>
  <body>
    Name:<input id="textInput" type="text"/>
    Hello <span id="nameDiv"></span>!

    <script>
      var textInputElement = document.getElementById('textInput'),
          nameDivElement = document.getElementById('nameDiv');

      textInputElement.addEventListener('keyup', function(){
        var text = textInputElement.value;
        nameDivElement.innerHTML = text;
      });
    </script>
  </body>
</html>

JQuery

<html>
  <head>
    <meta charset="utf-8">
    <title>DIY One-way Data Binding with jQuery</title>
    <script src="//code.jquery.com/jquery-2.0.3.min.js"></script>
  </head>
  <body>
    Name:<input id="textInput" type="text"/>
    Hello <span id="nameDiv"></span>!

    <script>
      $('#textInput').on('keyup', function(){
        $('#nameDiv').html($('#textInput').val());
      });
    </script>
  </body>
</html>

Backbone

<html>
  <head>
    <meta charset="utf-8">
    <title>DIY One-way Data Binding with Backbone</title>
    <script src="//code.jquery.com/jquery-2.0.3.min.js"></script>
    <script src="//jashkenas.github.io/underscore/underscore-min.js"></script>
    <script src="//jashkenas.github.io/backbone/backbone-min.js"></script>
  </head>
  <body>
    Name:<input id="textInput" type="text"/>
    Hello <span id="nameSpan"></span>!

    <script>

      // Model
      var model = new Backbone.Model({
        name: ''
      });

      // View
      model.on('change:name', function(){
        $('#nameSpan').html(model.get('name'));
      });

      // Controller
      $('#textInput').on('keyup', function(){
        model.set('name', $('#textInput').val());
      });

    </script>
  </body>
</html>

Angular

<html ng-app>
  <head>
    <meta charset="utf-8">
    <title>Angular.js Example</title>
    <script src="//cdnjs.cloudflare.com/ajax/libs/angular.js/1.2.1/angular.min.js"></script>
  </head>
  <body>
    Name:<input ng-model="name" type="text"/>
    Hello {{name}}
  </body>
</html>

No comments: