Create input on button clicked with angularJS - javascript
I am building a website and I need to create inputs dynamically. I currently have a button and it is pressed by the user, a text input is created with an appropriate span that I set (using the class, ids, style and all that) and add it to a div (lets say a list of input(s) in same div).
Now I want to do it with AngularJS.
Can someone show me example of code that creates the input dynamically?
Here is the start:
<script></script>
<div id="AddBtn" style="border-radius: 5px; border: 0px; background-color: #982222; color: #fff; font-size: 18px;" onclick="AddRowExample()">Add +</div>
<div id="listExample">
</div>
I want learn the how to do it the angular way. I already tried to create the input dynamically but it doesn't work. I seem to be getting $compile is not defined. I tried to figure out how to inject the $compile service but it didn't work.
After Edit:
Here is the code in my system:
js:
function getDefaultAmount(lines_number){
var defaultAmount = document.createElement("div");
defaultAmount.id = "AmountValue_" + lines_number;
defaultAmount.setAttribute("class", "inlineBlock amountValueStyle");
defaultAmount.setAttribute("ng-app", "myApp");
defaultAmount.setAttribute("ng-controller", "myCtrl");
var amountInput = document.createElement("input");
amountInput.setAttribute("type", "text");
amountInput.setAttribute("class", "inlineBlock");
amountInput.setAttribute("placeholder", "???? ????");
amountInput.setAttribute("ng-model", "firstName");
defaultAmount.appendChild(amountInput);
var amountVal = document.createElement("div");
amountVal.id = "AmountVal_" + lines_number;
amountVal.setAttribute("class", "inlineBlock");
amountVal.setAttribute("ng-bind", "{firstName}");
defaultAmount.appendChild(amountVal);
return defaultAmount.outerHTML;
}
and here is the function that called to ^:
function createNewRow(line_number){
var lines_number = line_number;
var lines_place = document.getElementById("EditLinesPlace");
if (lines_number < 19) {
//-----Start build line elements
//Create the line
var line = document.createElement("div");
line.id = "Line_" + lines_number;
line.style.cssText = "border-top: 1px solid #dddddd;";
var addClass = document.createAttribute("class");
addClass.value = "lineNum width100 padding2_0 inlineBlock";
line.setAttributeNode(addClass);
lines_place.appendChild(line);
/*//Create break line*/
//Create the category place in the line
var category = document.createElement("div");
category.id = "Category_" + lines_number;
var addClass = document.createAttribute("class");
addClass.value = "categoryStyle";
category.setAttributeNode(addClass);
category.innerHTML = '<div class="categoryBtn" onclick="openPopup(window.current_category,window.actions_list[0],'+ lines_number +');">' + "??? ???????" + '</div>' + getDefaultCategory(lines_number);
line.appendChild(category);
/*//Create break line*/
//Create the date place in the line
var date = document.createElement("div");
date.id = "Date_" + lines_number;
var addClass = document.createAttribute("class");
addClass.value = "dateStyle";
date.setAttributeNode(addClass);
date.innerHTML = "?????: " + getDate(lines_number);
line.appendChild(date);
/*//Create break line*/
//Create the amount place in the line
var amount = document.createElement("div");
amount.id = "Amount_" + lines_number;
var addClass = document.createAttribute("class");
addClass.value = "amountStyle";
amount.setAttributeNode(addClass);
amount.innerHTML = '<span class="inlineBlock">' +"???? :"+ '</span>' + getDefaultAmount(lines_number);
$compile(amount)($scope);
line.appendChild(amount);
/*//Create break line*/
//Create the repeated place in the line
var repeated = document.createElement("div");
repeated.id = "Repeated_" + lines_number;
var addClass = document.createAttribute("class");
addClass.value = "repeatedStyle";
repeated.setAttributeNode(addClass);
repeated.innerHTML = '<div class="repeatedBtn" onclick="updateRepeated(' + lines_number + ')">' + '<span class="floatA">???????? : ' + getDefaultRepeated(lines_number) + '</span></div>';
line.appendChild(repeated);
/*//Create break line*/
//Create the note place in the line
var note = document.createElement("div");
note.id = "Note_" + lines_number;
var addClass = document.createAttribute("class");
addClass.value = "noteStyle";
note.setAttributeNode(addClass);
note.innerHTML = "????? : " + getDefaultNote(lines_number);
line.appendChild(note);
/*//Create break line*/
//-----End build line elements
window.line_number++;
}
else {
var error = document.getElementById("ErrorPlace");
error.innerHTML = '<div class="" style="">???? ?????? ???????? ??? 20</div>';
return window.line_number;
}
}
This gives me $compile is undefined.
you could ng-repeat your inputs, and then just add another item to that model you're repeating
http://plnkr.co/edit/TXZNcq?p=preview
var app = angular.module('plunker', []);
app.controller('MainCtrl', function($scope) {
$scope.inputs = [0];
$scope.moreInputs = function(){
console.log('added an input');
$scope.inputs.push(0);
};
});
html
<!DOCTYPE html>
<html ng-app="plunker">
<head>
<meta charset="utf-8" />
<script data-require="angular.js#1.4.x" src="https://code.angularjs.org/1.4.3/angular.js" data-semver="1.4.3"></script>
<script src="app.js"></script>
</head>
<body ng-controller="MainCtrl">
<div ng-repeat="input in inputs track by $index">
<input type="text">
</div>
<button ng-click="moreInputs();">+ input</button>
</body>
</html>
Related
Javascript InnerHtml not working with razor devexpress
i want to show a combobox from devexpress using innerHtml. but is not working. please help me. thanks... and this is my javascript : var divContent = document.createElement("div"); var devexCombo = '##Html.DevExpress().ComboBox(settings => { settings.Name = "DepartmentId"; settings.Width = 300; settings.SelectedIndex = 0;' + ' settings.Properties.DropDownStyle = DevExpress.Web.ASPxEditors.DropDownStyle.DropDownList;' + ' settings.Properties.IncrementalFilteringMode = DevExpress.Web.ASPxEditors.IncrementalFilteringMode.StartsWith;' + ' settings.Properties.TextField = "Text"; settings.Properties.ValueField = "Id"; settings.Properties.ValueType = typeof(int);' + ' settings.Properties.DropDownRows = 10; }).BindList(ViewBag.DepartmentList).Bind(Model.DepartmentId).GetHtml()'; divContent.innerHTML = devexCombo;
Dynamically add accordion elements to the DOM
I am trying to dynamically add accordion elements to my DOM and I cannot seem to add it correctly so that the new element will have it's ID in place, class in place etc... Here is my code: function addAccordion(esr){ var elementID = document.getElementById("ThreatMainDiv_" + esr.marking); var emittersDiv = document.getElementById("Emitters"); if(elementID != null){ return; } var marking = esr.marking; var tmp; tmp = "\"" + "ThreatMainDiv_" + marking + "\""; var topDiv = '<div id='+ tmp + ' class="accordionTitle"><h1 style="font-size: 16px"></h1></div>'; var tDiv = document.createElement('div'); tDiv.innerHTML = topDiv; $('#Emitters').append(tDiv); }; How can I add it correctly?
Change $('.accordionTitle').click(function(){}); with $(document).on('click','.accordionTitle',function(){});
JavaScript not able to replace text with new text
I am trying to convert selected text's font with help of AngularJs and jQuery. This is my code. Everything is working fine but i am not able to change the text with a new text. This is my code: var app = angular.module('myApp', []); app.controller('editor', function($scope) { $scope.color = "black"; $scope.selectedText = ""; $scope.changeFont = function() { if ($scope.selectedText != "") { var changedText = "<span style='font-size:" + $scope.kys_selected_font + "px' >" + $scope.selectedText + "</span>"; alert($scope.selectedText + $scope.kys_selected_font + " " + changedText); document.getElementById("#content").innerHTML.replace($scope.selectedText, changedText); } else { $("#content").append("<span id='one' style='font-size:" + $scope.kys_selected_font + "px' > this is some text </span>"); $("#one").focus(); } }; $("#content").mouseup(function() { $scope.selectedText = window.getSelection(); }); });
innerHTML.replace(...) returns a new string, rather than modifying the existing one, so your replacement won't modify the element. You need to actually update the property: var el = document.getElementById("content"); el.innerHTML = el.innerHTML.replace($scope.selectedText, changedText); (also note # removed from element ID as per #IvanSivak's comment)
how to check if a string contains substring and color it in javascript?
I have to create: 1 <input type="text"> 1 <textarea> 1 <div> 1 <button> I have to fill the div with the textarea's content but if the content contains the input's string, I have to color it with <span>. For example: If the input contains "is" and the textarea contains "this is a beautiful day", I should put the following text in the div "this is a beautiful day" and color every time that the "is" string appears. I should use indexOf() and a loop. I have this: var a = $("#inp1").val(); var b = $("#txt").val(); var x = b.indexOf(a); if (x > -1)
If you absolutely have to use indexOf while(b.indexOf(a) != -1) { b = b.replace(a, '[X]'); } while(b.indexOf('[X]') != -1) { b = b.replace('[X]', '<span style="color:yellow;">' + a + '</span>'); } $("#targetDiv").html(b); You can also do this with RegExp var a = $("#inp1").val(); var b = $("#txt").val(); var re = new RegExp(a, 'g'); var divContent = b.replace(re, '<span style="color:yellow;">' + a + '</span>'); $("#targetDiv").html(divContent); Here is a fiddle with the indexOf http://jsfiddle.net/eva3ttuL/1/
Here is the code to find and change color of all searched word $(document).ready(function () { $("#here").on("keydown keyup", function () { var mytext = $(this).val(); var find = $("#find").val(); mytext=mytext.replace(new RegExp(find,"g"), "<span class='me'>"+find+"</span>"); $("#output").html(mytext); }); }) .me{color: #00f; background-color: #EFFF00; } <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script> <input id="find" type="text" /><br/> <textarea id="here"></textarea><br/> <div id="output"></div>
Use JavaScript substring to split the string inside textarea and form a paragraph with the highlighted text. HTML code: <input id="inp1" type="text"/><br> <textarea id="txt" col="10" row="5"></textarea><br> <div id="fillarea"> click on check </div> <button id="check">check</button> CSS for highlighting: .highlight{ background-color:yellow; } jQuery code: $('#check').on('click',function(){ var a = $("#inp1").val(); var b = $("#txt").val(); var x = b.indexOf(a); var first = b.substring(0,x); var middle = b.substring(x,x+a.length); var last = b.substring(x+a.length,b.length); var to_print = '<p>' + first + '<span class="highlight">' + middle + '</span> ' + last + '</p>'; $('#fillarea').empty(); $('#fillarea').append(to_print); }); Demo fiddle here
It helps you jsfiddle $('.submit').click(function(){ var content = $('.textarea').val(); var ans = content.replace($('.input').val(), "<span style='color:red;'>"+$('.input').val()+"</span>"); $('.text').html(ans); });
var input = $("#inp1").val(); var text = $("#txt").val(); var div = $("#div"); div.val(text.replace(new RegExp(input,'g'), makeSpan(input))); function makeSpan(str) { return '<span style="background-color:red">' + str + '</span>'; }
Just try this <html> <title></title> <head> <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script> <script> $(document).ready(function() { var a = "is"; var b = "this is beautiful"; var x = b.indexOf(a); if (x > -1) { var re = new RegExp(a, 'g'); res = b.replace(re, "<span style='color:red'>"+a+"</span>" ); $("#result").html(res); } }) </script> </head> <body> <div id="result"></div> </body>
You can use IndexOf Javascript function var str1 = "ABCDEFGHIJK"; var str2 = "DEFG"; if(str1.indexOf(str2) != -1){ alert(str2 + " found"); }
How to delete a selection of textarea
I'm making a a simple texteditor and for that I'm using a function which gets the selected text of a textarea. My problem is not getting the selected text but when i add some tags to the selected text, for example bold or italic, it appends. So what I want is to delete the selection first before adding it to the textarea. Here's my code: <input type="button" id="bold" value="BOLD"/> <input type="button" id="undo" value="UNDO"/> <textarea id="message" cols="50" rows="20"></textarea> var text = []; var textarea = document.getElementById('message'); //simple texteditor function edit(tag) { var startPos = textarea.selectionStart; var endPos = textarea.selectionEnd; var selection = textarea.value.substring(startPos, endPos); var surrounder = selection.replace(selection, "<" + tag + ">" + selection + "</" + tag + ">"); textarea.value += surrounder; updatePreview(); textarea.focus(); } document.getElementById('bold').onclick = function () { edit('b'); }; document.getElementById('undo').onclick = function () { document.execCommand('undo',false,null); }; thanks in advance!
I think this works for you: var text = []; var textarea = document.getElementById('message'); //simple texteditor function edit(tag) { var startPos = textarea.selectionStart; var endPos = textarea.selectionEnd; console.log(startPos); var selectionBefore = textarea.value.substring(0, startPos); var selection = textarea.value.substring(startPos, endPos); var selectionAfter = textarea.value.substring(endPos); var surrounder = selection.replace(selection, "<" + tag + ">" + selection + "</" + tag + ">"); var newText = selectionBefore + surrounder + selectionAfter; textarea.value = newText; updatePreview(); textarea.focus(); } document.getElementById('bold').onclick = function () { edit('b'); }; document.getElementById('undo').onclick = function () { document.execCommand('undo',false,null); }; https://jsfiddle.net/3L659v65/