I return my select dynamically. I use the following code:
var data = [
{Id: "1", },
{Id: "2", },
{Id: "3", },
{Id: "4", },
{Id: "5", },
{Id: "6", },
];
$(document).on('click', '.dad-pagamento', function() {
var linha = ``;
for (var x = 0; x < data.length; x++) {
linha += `<div class="col-3">
<label id="atb11" style="margin-top: 5%;"><i class="pe-2x pe-va pe-7s-plus"></i> Ajudante</label>
<div id="atbb22" style="display:none;">
<select class="js-states form-control ajuste singlet" name="auxiliar[]">
<option></option>
<option value="${data[x].Id}">${data[x].Id}</option>
</select>
</div>
</div>`;
$(".pagmfalta").html(linha);
$('#minhaDiv1').show();
$(".singlet").select2({
placeholder: "Selecione Ajudante",
allowClear: true,
width: '100%'
});
$('#atb11').on('click', function() {
$('#atbb22').slideToggle('slow');
});
}
});
<link href="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.6-rc.0/css/select2.min.css" rel="stylesheet">
<link href="https://cdn.jsdelivr.net/npm/pixeden-stroke-7-icon#1.2.3/pe-icon-7-stroke/dist/pe-icon-7-stroke.min.css" rel="stylesheet">
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.13/js/select2.min.js"></script>
<button type="button" class="btn btn-info dad-pagamento" style="float: right; margin-right: 5%; margin-top: 4%;"><i class="metismenu-icon pe-7s-search"></i> Consultar </button>
<section id="s1">
<div style="display:none" id="minhaDiv1">
<div class="row pagmfalta">
</div>
</div>
</section>
I use this code to show and hide the select:
$('#atb11').on('click', function() {
$('#atbb22').slideToggle('slow');
});
The problem as it returns more than one select and I am using id, it only opens the first select and not the others.
I intend to open select one by one according to my needs. I don't want to click on a select and they all open
As I mentioned in the comments, you have some id for multiple elements. You have to append the index variable x with id to make ids unique for each element. Secondly, add .on(click) that delegates the event for both current and future elements.
check: This answer
See the working example below:
var data = [
{Id: "1", },
{Id: "2", },
{Id: "3", },
{Id: "4", },
{Id: "5", },
{Id: "6", },
];
$(document).on('click', '.dad-pagamento', function() {
var linha = ``;
for (var x = 0; x < data.length; x++) {
linha += `<div class="col-3">
<label id="atb11-${x}" style="margin-top: 5%;"><i class="pe-2x pe-va pe-7s-plus"></i> Ajudante</label>
<div id="atbb22-${x}" style="display:none;">
<select class="js-states form-control ajuste singlet" name="auxiliar[]">
<option></option>
<option value="${data[x].Id}">${data[x].Id}</option>
</select>
</div>
</div>`;
$(".pagmfalta").html(linha);
$('#minhaDiv1').show();
$(".singlet").select2({
placeholder: "Selecione Ajudante",
allowClear: true,
width: '100%'
});
$(document).on('click','#atb11-'+x,function(e){
e.stopImmediatePropagation(); //Keeps the rest of the handlers from being executed
$(this).next().slideToggle('slow');
});
}
});
<link href="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.6-rc.0/css/select2.min.css" rel="stylesheet">
<link href="https://cdn.jsdelivr.net/npm/pixeden-stroke-7-icon#1.2.3/pe-icon-7-stroke/dist/pe-icon-7-stroke.min.css" rel="stylesheet">
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.13/js/select2.min.js"></script>
<button type="button" class="btn btn-info dad-pagamento" style="float: right; margin-right: 5%; margin-top: 4%;"><i class="metismenu-icon pe-7s-search"></i> Consultar </button>
<section id="s1">
<div style="display:none" id="minhaDiv1">
<div class="row pagmfalta">
</div>
</div>
</section>
The issue you mentioned in comments ( .on() is triggering event multiple times) can be solved by adding event.stopImmediatePropagation().
Check docs, It will stops rest of the handlers from being executed.
Related
I am using Choices.js to create a multi select option menu.
In the <select> menu it is required to be able to select the same <option> multiple times.
This issue has been resolved by using the addEventListener function from Choices.js.
The Issue
When i want to load the selected options from a string or ajax call the <option> are only selected one time instead of multiple times.
For example: the values 1 - 1 - 2 - 3 - 3 will need to display in the <select> menu ONE - ONE - TWO - THREE - THREE.
But for now i only displays ONE - TWO - THREE.
The issue is that the addEventListener is not working when the setChoiceByValue is being used.
document.addEventListener("DOMContentLoaded", function() {
const query_task = new Choices(document.querySelector('#query_task'), {
removeItemButton: true,
maxItemCount: 10,
});
query_task.passedElement.element.addEventListener('addItem', function(e) {
query_task.setChoices([{
value: e.detail.value,
label: e.detail.label
}, ], 'value', 'label', false, );
}, false, );
$(document).on('click', '.ajax_data', function() {
let data = '1,1,2,3,3';
query_task.removeActiveItems();
query_task.setChoiceByValue(data.split(','));
console.log('Ajax data loaded');
});
});
<link href="https://cdnjs.cloudflare.com/ajax/libs/bootstrap/5.1.3/css/bootstrap.min.css" rel="stylesheet" />
<link href="https://choices-js.github.io/Choices/assets/styles/choices.min.css" rel="stylesheet" />
<script src="https://cdnjs.cloudflare.com/ajax/libs/bootstrap/5.1.3/js/bootstrap.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/choices.js/9.1.0/choices.min.js"></script>
<div class="row pt-2 px-5">
<div class="col-12 px-5">
<label for="query_task" class="form-label">SELECT TASKS</label>
<select id="query_task" class="form-control choices-multiple" multiple>
<option value="0">ZERO</option>
<option value="1">ONE</option>
<option value="2">TWO</option>
<option value="3">THREE</option>
<option value="4">FOUR</option>
</select>
<div>
<div>
<button type="button" class="ajax_data btn btn-primary">Load AJAX data</button>
</div>
</div>
Final result:
let query_data = [
{ value: "0", label: "ZERO" },
{ value: "1", label: "ONE" },
{ value: "2", label: "TWO" },
{ value: "3", label: "THREE" },
{ value: "4", label: "FOUR" }
];
document.addEventListener("DOMContentLoaded", function() {
const query_task = new Choices(document.querySelector('#query_task'), {
removeItemButton: true,
maxItemCount: 10,
choices: query_data
});
query_task.passedElement.element.addEventListener('addItem', () => reset(), false);
query_task.passedElement.element.addEventListener('removeItem', () => reset(), false);
function reset() {
query_task.clearChoices();
query_task.setChoices(query_data, "value", "label", false);
}
$(document).on('click', '.ajax_data', function() {
query_task.removeActiveItems();
let data = '1,1,2,3,3';
let selected_values = data.split(',')
$.each(selected_values, function(key, value) {
query_task.setChoiceByValue(value);
reset();
});
});
});
<link href="https://cdnjs.cloudflare.com/ajax/libs/bootstrap/5.1.3/css/bootstrap.min.css" rel="stylesheet" />
<link href="https://choices-js.github.io/Choices/assets/styles/choices.min.css" rel="stylesheet" />
<script src="https://cdnjs.cloudflare.com/ajax/libs/bootstrap/5.1.3/js/bootstrap.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/choices.js/9.1.0/choices.min.js"></script>
<div class="row pt-2 px-5">
<div class="col-12 px-5">
<label for="query_task" class="form-label">SELECT TASKS</label>
<select id="query_task" class="form-control choices-multiple" multiple>
</select>
<div>
<div>
<button type="button" class="ajax_data btn btn-primary">Load AJAX data</button>
</div>
</div>
The documentation is bit confusing 😵. There are two issues to fix:
To add duplicates you need to use setValue(items) method. Next point explains how to get rid of duplicates.
After you unselect an item it gets added back to the options list. This creates duplicate items. I couldn't find method to remove a single choice from options list. So as a workaround I am resetting entire options list.
Demo:
let labels = ['ZERO', 'ONE', 'TWO', 'THREE', 'FOUR'];
let query_task = null;
document.addEventListener("DOMContentLoaded", function() {
query_task = new Choices(document.querySelector('#query_task'), {
removeItemButton: true,
maxItemCount: 10,
duplicateItemsAllowed: true,
choices: defaults()
});
query_task.passedElement.element.addEventListener('addItem', function(e) {
query_task.setChoices([{
value: e.detail.value,
label: e.detail.label
}, ], 'value', 'label', false);
}, false);
query_task.passedElement.element.addEventListener('removeItem', () => reset(), false);
$(document).on('click', '.ajax_data', function() {
let data = '1,1,2,3,3';
query_task.removeActiveItems();
query_task.setValue(data.split(',').map((v) => ({value: v, label: labels[+v]})));
reset();
console.log('Ajax data loaded');
});
});
function defaults() {
return labels.map((lbl, i) => ({value: i, label: lbl}));
}
function reset() {
query_task.clearChoices();
query_task.setChoices(defaults(), 'value', 'label', false);
}
<link href="https://cdnjs.cloudflare.com/ajax/libs/bootstrap/5.1.3/css/bootstrap.min.css" rel="stylesheet" />
<link href="https://choices-js.github.io/Choices/assets/styles/choices.min.css" rel="stylesheet" />
<script src="https://cdnjs.cloudflare.com/ajax/libs/bootstrap/5.1.3/js/bootstrap.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/choices.js/9.1.0/choices.min.js"></script>
<div class="row pt-2 px-5">
<div class="col-12 px-5">
<label for="query_task" class="form-label">SELECT TASKS</label>
<select id="query_task" class="form-control choices-multiple" multiple></select>
<div>
<div>
<button type="button" class="ajax_data btn btn-primary">Load AJAX data</button>
</div>
</div>
</div>
</div>
Hi #Crezzur,
Thanks for posting the question, I got to know this tiny yet useful library.(I am definitely using this in my next project)
I did some digging and it seems you can not use setChoicesByValue() for your requirement due to a check in the library reference code:here
However I achieved it by using setValue() instead. Here is a working stackblitz link for you
This question already has answers here:
Event binding on dynamically created elements?
(23 answers)
Closed 2 years ago.
When user click on tag with class ".btn" it should console.log(1), if user click on "Next" button - .buttons>button should replace with given values in array tasks. It works well with replacement, but after replacement click ".btn" doen't work anymore.
What issue?
<div class="buttons">
<button class="btn">
<span class="text1">var 1</span>
</button>
<button class="btn">
<span class="text2">var 2</span>
</button>
</div>
<button class="right">
<span class="text">Next</span>
</button>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.5.1/jquery.js"></script>
<script>
$(".btn").on('click', function() {
console.log(1)
})
</script>
<script>
var tasks = [
["task1", "task_addition1", "1", "var1", "img1.url", "var1", "img1.url"],
["task2", "task_addition2", "2", "var2", "img1.url", "var2", "img2.url"],
["task3", "task_addition3", "1", "var3", "img1.url", "var3", "img3.url"],
];
var task_number = 0;
$(".right").on('click', function() {
let buttons = ""
for (var i = 3; i < tasks[task_number].length;) {
buttons += '<button class="btn btn-light"><span class="text1">{}</span></button>'.replace("{}", tasks[task_number][i])
i += 2;
};
$(".buttons").html(buttons);
task_number += 1
})
</script>
Your binded event will be removed when you replace buttons. In this case, you should bind an event to parent(I usually use body selector) and provide selector to find it's children.
var tasks = [
["task1", "task_addition1", "1", "var1", "img1.url", "var1", "img1.url"],
["task2", "task_addition2", "2", "var2", "img1.url", "var2", "img2.url"],
["task3", "task_addition3", "1", "var3", "img1.url", "var3", "img3.url"],
];
var task_number = 0;
$(".right").on('click', function() {
let buttons = ""
for (var i = 3; i < tasks[task_number].length;) {
buttons += '<button class="btn btn-light"><span class="text1">{}</span></button>'.replace("{}", tasks[task_number][i])
i += 2;
};
$(".buttons").html(buttons);
task_number += 1
})
$("body").on("click", ".btn", function() {
console.log(1)
});
<html>
<head>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.5.1/jquery.js"></script>
</head>
<body>
<div class="buttons">
<button class="btn">
<span class="text1">var 1</span>
</button>
<button class="btn">
<span class="text2">var 2</span>
</button>
</div>
<button class="right">
<span class="text">Next</span>
</button>
</body>
</html>
The only issue with my popovers, is that the “else” condition does not work for the very first search input/click. However, the “if” condition does work. Everything after the first input/click works fine. Any thoughts or suggestions??
<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.2/css/bootstrap.min.css" rel="stylesheet" />
<script src='http://code.jquery.com/jquery-2.1.3.min.js'></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.2/js/bootstrap.min.js"></script>
</head>
<body>
<style>
#closeBtn, #searchBtn{
background-color: #180D01;
color: #fed136;
}
#closeBtn, #searchBtn:hover{
color: #180D01;
background-color: #fed136;
}
</style>
<div class="form-group">
<label for="test" class="col-sm-3 control-label">Search a country!</label>
<div class="col-sm-3">
<input type="text" class="form-control" id="search" placeholder="Enter A Country">
</div>
</div>
<div class="form-group">
<div class="col-sm-offset-6 col-sm-3">
<!--==============SEARCH BUTTON ===============-->
<a href="#" tabindex="0" role="button" class="btn btn-default" id="searchBtn" data-container="body" data-toggle="popover" >Search</a>
</div>
</div>
<script>
$( document ).ready(function() {
//CASE SENSITIVE!!!
var validCountriesArray = [
"Sweden",
"France",
"Germany",
"United States", "usa",
"Austria",
"Switzerland",
"Denmark",
"Great Britain", "england", "UK", "U.K.",
"West Germany",
"United Team of Germany",
"Soviet Union", "Russia",
"Netherlands",
"Spain"];
function invalidPopoverShow(){
$('[data-toggle="popover"]').popover({
placement: "right",
trigger: "focus",
content: "Choose a valid country that had Dressage/Equestrain participants in the Olympics! (Click anywhere to make popover disappear)",
});
}
function invalidPopoverHide(){
$('[data-toggle="popover"]').popover('hide');
}
////========================
$('#searchBtn').click(function() {
var searchTerm = $('#search').val();
console.log(searchTerm);
//clears text in search box
for (var i=0; i<validCountriesArray.length; i++){
if (searchTerm.toLowerCase() == validCountriesArray[i].toLowerCase()){
//.toLowerCase unifies & converts user input to lowercase
console.log("Good pick!" + searchTerm);
invalidPopoverHide();
}
else {
invalidPopoverShow();
}
}
$("#search").val("");
});
//=====WHY DOESNT THE FIRST invalid SEARCHterm WORK??????=====//
});
</script>
</body>
</html>
<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.2/css/bootstrap.min.css" rel="stylesheet" />
<script src='http://code.jquery.com/jquery-2.1.3.min.js'></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.2/js/bootstrap.min.js"></script>
</head>
<body>
<style>
#closeBtn, #searchBtn{
background-color: #180D01;
color: #fed136;
}
#closeBtn, #searchBtn:hover{
color: #180D01;
background-color: #fed136;
}
</style>
<div class="form-group">
<label for="test" class="col-sm-3 control-label">Search a country!</label>
<div class="col-sm-3">
<input type="text" class="form-control" id="search" placeholder="Enter A Country">
</div>
</div>
<div class="form-group">
<div class="col-sm-offset-6 col-sm-3">
<!--==============SEARCH BUTTON ===============-->
<a href="#" tabindex="0" role="button" class="btn btn-default" id="searchBtn" data-container="body" data-toggle="popover" >Search</a>
</div>
</div>
<script>
$( document ).ready(function() {
//CASE SENSITIVE!!!
var validCountriesArray = [
"Sweden",
"France",
"Germany",
"United States", "usa",
"Austria",
"Switzerland",
"Denmark",
"Great Britain", "england", "UK", "U.K.",
"West Germany",
"United Team of Germany",
"Soviet Union", "Russia",
"Netherlands",
"Spain"];
function invalidPopoverShow(){
$('[data-toggle="popover"]').popover({
placement: "right",
trigger: "focus",
content: "Choose a valid country that had Dressage/Equestrain participants in the Olympics! (Click anywhere to make popover disappear)",
});
}
function invalidPopoverHide(){
$('[data-toggle="popover"]').popover('hide');
}
////========================
$('#searchBtn').click(function() {
var searchTerm = $('#search').val();
console.log(searchTerm);
//clears text in search box
for (var i=0; i<validCountriesArray.length; i++){
if (searchTerm.toLowerCase() == validCountriesArray[i].toLowerCase()){
//.toLowerCase unifies & converts user input to lowercase
console.log("Good pick!" + searchTerm);
invalidPopoverHide();
}
else {
invalidPopoverShow();
}
}
$("#search").val("");
});
//=====WHY DOESNT THE FIRST invalid SEARCHterm WORK??????=====//
});
</script>
</body>
</html>
I have the following Javascript that I am using to make a sort of flowchart where the user clicks through a set of questions. For certain responses i want to link to an external site where more info can be found. How do I add these links?
HTML
<!DOCTYPE html>
<html lang="en">
<head>
</head>
<body>
<div class="wrapper">
<div class="container">
<div class="row">
<div class="col-xs-12 text-right">
<button class="btn btn-default btn-corner" type="submit" data-bind="click: startOver, visible: queryData().id > 0">Start over</button>
</div>
</div>
</div>
<div class="container main">
<div class="row">
<div class="c12 text-center">
<h1 data-bind="text: queryData().text"></h1>
<h3 data-bind="text: queryData().subhead"></h3>
<div class="option-group" data-bind="foreach: queryData().answers">
<button class="btn btn-default btn-lg" type="submit" data-bind="click: $parent.goToTarget, text: text"></button>
</div>
<button class="btn btn-default" type="submit" data-bind="click: stepBack, visible: navHistory().length > 1">Previous Step</button>
</div>
</div>
</div>
<div class="push"></div>
</div>
<script src="http://ajax.aspnetcdn.com/ajax/knockout/knockout-3.3.0.js"></script>
<script src="app.js?v=0.4.0"></script>
<script>
</script>
</body>
</html>
The Javascript is as follows:
JS
var queries = [{
id: 0,
text: "Where to start?",
answers: [{
text: "Let's Begin!",
target: 1
}]
}, {
id: 1,
text: "Which genre do you want to start in?",
answers: [{
text: "Fantasy",
target: 100
}, {
text: "SciFi",
target: 2
}, {
text: "Neither",
target: 59
}]
}, {
id: 2,
text: "It's huge but it's worth it. The Cryptonomicon by Neal Stephenson",
answers: [{
text: "Amazon.co.uk",
target: "_blank"
}, {
text: "Amazon.com"
}]
}];
function QueryViewModel() {
var self = this;
self.querySet = ko.observable();
self.currentStep = ko.observable();
self.queryData = ko.observable();
self.sfw = ko.observable();
self.navHistory = ko.observableArray();
// Operations
self.goToTarget = function(obj) {
self.navHistory.push(self.currentStep());
self.currentStep(obj.target);
self.queryData(self.querySet()[obj.target]);
}
self.startOver = function() {
self.navHistory.removeAll();
self.goToTarget({target: 0});
}
self.stepBack = function() {
var lastStep = self.navHistory().length > 1 ? self.navHistory.pop() : 0;
self.currentStep(lastStep);
self.queryData(self.querySet()[lastStep]);
}
var paramsString = document.location.hash.substring(1);
var params = new Array();
if (paramsString) {
var paramValues = paramsString.split("&");
for (var i = 0; i < paramValues.length; i++) {
var paramValue = paramValues[i].split("=");
params[paramValue[0]] = paramValue[1];
}
}
params ? paramTarget = params['target'] : params = [];
self.sfw() ? self.querySet(queriesSFW) : self.querySet(queries);
if (paramTarget) {
self.navHistory.push(0);
self.currentStep(0);
self.goToTarget({target: paramTarget})
} else {
self.goToTarget({target: 0});
}
}
ko.applyBindings(new QueryViewModel());
In html you can do something like this:
<button type="button" onclick="window.open('https://google.com/', '_self')">Button</button>
You don't have to use a button, different elements can use onclick like text or images. This can also call js functions, just put the function name where "window.open..." is.
Of course the standard way to do it is
<a href='https://www.google.com/'>Link</a>
You can practice using js here: http://www.w3schools.com/js/tryit.asp?filename=tryjs_intro_inner_html
and learn more about it here: http://www.w3schools.com/js/js_intro.asp
I am not sure why you would show us the JSON for open a link to another page. Unless I misunderstood. This kind of basic information can be found by a quick Google search.
Add your link in the object like:
text: "Fantasy",
link: "http://www.stackoverflow.com",
target: 2
Now when you need to go to that link, use this function:
var link = obj.link;
window.open(link, "_blank");
I have written the following HTML & AngularJS code to update the Tree on HTML Page (View) on the Click of a Button.
When the Button is clicked, the changes appear for a fraction of second and disappear. I am not able to find the reason for this. Could you please let me know how I can overcome this problem?
Below is the HTML and JS Code. This is working in the Snippet Editor, but not in the Browser.
var module = angular.module('myapp', []);
module.controller("TreeCtrl", function($scope) {
$scope.categories = [];
$scope.$apply($scope.addTreeToView = function() {
$scope.categories = [{
title: 'Computers1',
categories: [{
title: 'Laptops1',
categories: [{
title: 'Ultrabooks1'
}, {
title: 'Macbooks1'
}]
}, {
title: 'Desktops1'
}, {
title: 'Tablets1',
categories: [{
title: 'Apple1'
}, {
title: 'Android1'
}]
}]
}, {
title: 'Printers1',
categories: [{
title: 'HP1'
}, {
title: 'IBM1'
}]
}];
});
});
<!DOCTYPE html>
<html lang="en">
<head>
<title>Tree Example</title>
<link rel="stylesheet" href="http://maxcdn.bootstrapcdn.com/bootstrap/3.2.0/css/bootstrap.min.css">
<script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.3.14/angular.min.js"></script>
</head>
<body>
<div ng-app="myapp">
<div class="col-sm-10 col-sm-offset-1" ng-controller="TreeCtrl">
<form action="#" method="post" class="form-horizontal" id="commentForm" role="form">
<div class="form-group" id="div_submitComment">
<div class="col-sm-offset-2 col-sm-10">
<button class="btn btn-success btn-circle text-uppercase" type="submit" ng-click="addTreeToView()"><span class="glyphicon glyphicon-send" id="qazwsx"></span> Create Tree</button>
</div>
</div>
</form>
<div class="page-header">
<h3 class="reviews">Tree</h3>
</div>
<script type="text/ng-template" id="categoryTree">
{{ category.title }}
<ul ng-if="category.categories">
<li ng-repeat="category in category.categories" ng-include="'categoryTree'">
</li>
</ul>
</script>
<ul>
<li ng-repeat="category in categories" ng-include="'categoryTree'"></li>
</ul>
</div>
</div>
<script src="self.js"></script>
</body>
try removing type="submit" from the buttom
I was using Form element type of Bootstrap. This has an action attribute. I removed the action attribute. Code works fine after removing it
< form method = "post"
class = "form-horizontal"
id = "commentForm"
role = "form" >
< div class = "form-group"
id = "div_submitComment" >
< div class = "col-sm-offset-2 col-sm-10" >
< button class = "btn btn-success btn-circle text-uppercase"
type = "submit"
ng - click = "addTreeToView()" > < span class = "glyphicon glyphicon-send"
id = "qazwsx" > < /span> Create Tree</button >
< /div>
</div >
< /form>
Because your html will be reloaded after you do "submit" action.So you have to replace "type="submit" by type="button" and disable "auto submit".