Bookmark and Share

javascript_logo.png
Updating a span when input text changes using DOM API, jQuery, and Backbone





Updating a span when input text changes using DOM API
<html>
  <head>
    <meta charset="utf-8">
    <title>One-way Data Binding</title>
  </head>
  <body>
    Name:<input id="textInput" type="text"/>
    <br />
    <br />
    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>

Span_DOM_API.png


Updating a span when input text changes using jQuery
<html>
  <head>
    <meta charset="utf-8">
    <title>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"/>
    <br />
    <br />
    Hello <span id="nameDiv"></span>!
    <script>
      $('#textInput').on('keyup', function(){
        $('#nameDiv').html($('#textInput').val());
      });
    </script>
  </body>
</html>

jQuery_text_input_update.png


Updating a span when input text changes using Backbone
<html>
  <head>
    <meta charset="utf-8">
    <title>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"/>
    <br />
    <br />
    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> 

Backbone.png