Dynamically creating input fields on tab via CoffeeScript and JQuery

Below is my very own, very first, super-clean, super-sexy CoffeeScript snippet that dynamically appends input fields as the user tabs through the current input field. The source-code is on the left. On the right you can actually play with it and see it in action!

inputId = 1;
 
jQuery -> 
  $("#fields :input").live 'keydown', (e) ->
    if isModifierKeyPressed e
      return 
 
    if e.keyCode in [9, 13]
      e.preventDefault
 
      if isLastActivity($(this).attr 'id')
	addAnotherTextInput();
 
      $(this).next().focus();
      return false
 
isModifierKeyPressed = (e) ->
  e.ctrlKey or e.altKey or e.shiftKey
 
isLastActivity = (inputFieldId) ->
  inputNumber = 
    (Number) inputFieldId.split('activity')[1]
  inputNumber == inputId
 
addAnotherTextInput = ->
  inputId++
  $("#fields").append getInputField inputId
 
getInputField = (inputId) ->
  return "<input type='text' id='activity#{inputId}' 
                 class='input-super-large' 
                 placeholder='Type something and then press tab' />"

3 thoughts on “Dynamically creating input fields on tab via CoffeeScript and JQuery

  1. Pingback: Interesting .NET Links - April 10 , 2012 | Tech Blog

Leave a Reply

Your email address will not be published.


*

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>