Created
October 15, 2013 03:23
-
-
Save hackingbeauty/6986054 to your computer and use it in GitHub Desktop.
Interview question: dynamically create N input nodes with +- in between inputs. Evaluate expression. Numbers allowed only.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| <div id="container"></div> | |
| <div id="result"></div> | |
| <input type="submit" id="submit-button" /> | |
| <script> | |
| VIKI = { | |
| init: function(){ | |
| var inputs = this.createNodes(5); | |
| this.computeValue(inputs); | |
| }, | |
| createNodes: function(numOfInputs){ | |
| var container = document.getElementById('container'), | |
| inputElem, | |
| selectMenuElem, | |
| optionElem1, | |
| optionElem2, arr = []; | |
| for(var i = 0; i<numOfInputs; i++){ | |
| inputElem = document.createElement('input'), | |
| inputElem.id = 'input' + i; | |
| arr.push(inputElem); | |
| container.appendChild(inputElem); | |
| if(i < (numOfInputs - 1) ){ | |
| optionElem1 = document.createElement('option'); | |
| optionElem1.value = 'add'; | |
| optionElem1.innerHTML = 'add'; | |
| optionElem2 = document.createElement('option'); | |
| optionElem2.value = 'subtract'; | |
| optionElem2.innerHTML = 'subtract'; | |
| selectMenuElem = document.createElement('select'); | |
| selectMenuElem.appendChild(optionElem1); | |
| selectMenuElem.appendChild(optionElem2); | |
| arr.push(selectMenuElem); | |
| container.appendChild(selectMenuElem); | |
| } | |
| } | |
| return arr; | |
| }, | |
| validate: function(arr){ | |
| for(var i = 0; i < arr.length; i++){ | |
| if(arr[i].nodeName == 'INPUT' && isNaN(parseInt(arr[i].value))) { | |
| return true; | |
| } | |
| } | |
| }, | |
| computeValue: function(arr){ | |
| var submitBttn = document.getElementById('submit-button'), | |
| resultDiv = document.getElementById('result'), | |
| stringArr, | |
| operator | |
| self = this; | |
| submitBttn.onclick = function(){ | |
| stringArr = []; // reset | |
| if(self.validate(arr)) { | |
| resultDiv.innerHTML = 'Must input a number in all input fields.' | |
| return; | |
| } | |
| for(var i = 0; i < arr.length; i++){ | |
| if(arr[i].nodeName === 'INPUT'){ | |
| stringArr.push(arr[i].value); | |
| } else if(arr[i].nodeName === 'SELECT'){ | |
| operator = arr[i].options[arr[i].selectedIndex].value == 'add' ? '+' : '-'; | |
| stringArr.push(operator); | |
| } | |
| } | |
| resultDiv.innerHTML = eval(stringArr.join('')); | |
| } | |
| } | |
| } | |
| VIKI.init(); | |
| </script> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment