I'm just trying to use a simple select box but when I select a value it does not get selected. While in the example it does. I have imported the css and javascript but it just doesn't work.
<link rel="stylesheet" href="https://fonts.googleapis.com/icon?family=Material+Icons">
<link rel="stylesheet" href="https://code.getmdl.io/1.3.0/material.indigo-pink.min.css">
<script defer src="https://code.getmdl.io/1.3.0/material.min.js"></script>
<div class="mdl-textfield mdl-js-textfield getmdl-select">
<input type="text" value="" class="mdl-textfield__input" id="sample2" readonly>
<input type="hidden" value="" name="sample2">
<i class="mdl-icon-toggle__label material-icons">keyboard_arrow_down</i>
<label for="sample2" class="mdl-textfield__label">Country</label>
<ul for="sample2" class="mdl-menu mdl-menu--bottom-left mdl-js-menu">
<li class="mdl-menu__item" data-val="DEU">Germany</li>
<li class="mdl-menu__item" data-val="BLR">Belarus</li>
<li class="mdl-menu__item" data-val="RUS">Russia</li>
</ul>
</div>
Your example doesn't include getmdl-select sources.
Please attach sources from http://creativeit.github.io/getmdl-select.
<!-- getmdl -->
<link rel="stylesheet" href="https://fonts.googleapis.com/icon?family=Material+Icons">
<link rel="stylesheet" href="your_path_to/material-design-lite/material.min.css">
<script defer src="your_path_to/material-design-lite/material.min.js"></script>
<!--getmdl-select-->
<link rel="stylesheet" href="path_to/getmdl-select/getmdl-select.min.css">
<script defer src="path_to/getmdl-select/getmdl-select.min.js"></script>
UPDATE: detmdl-select sources was added
{
'use strict';
(function () {
function whenLoaded() {
getmdlSelect.init('.getmdl-select');
};
window.addEventListener ?
window.addEventListener("load", whenLoaded, false) :
window.attachEvent && window.attachEvent("onload", whenLoaded);
}());
var getmdlSelect = {
_addEventListeners: function (dropdown) {
var input = dropdown.querySelector('input');
var hiddenInput = dropdown.querySelector('input[type="hidden"]');
var list = dropdown.querySelectorAll('li');
var menu = dropdown.querySelector('.mdl-js-menu');
var arrow = dropdown.querySelector('.mdl-icon-toggle__label');
var label = '';
var previousValue = '';
var previousDataVal = '';
var opened = false;
var setSelectedItem = function (li) {
var value = li.textContent.trim();
input.value = value;
list.forEach(function (li) {
li.classList.remove('selected');
});
li.classList.add('selected');
dropdown.MaterialTextfield.change(value); // handles css class changes
setTimeout(function () {
dropdown.MaterialTextfield.updateClasses_(); //update css class
}, 250);
// update input with the "id" value
hiddenInput.value = li.dataset.val || '';
previousValue = input.value;
previousDataVal = hiddenInput.value;
if ("createEvent" in document) {
var evt = document.createEvent("HTMLEvents");
evt.initEvent("change", false, true);
menu['MaterialMenu'].hide();
input.dispatchEvent(evt);
} else {
input.fireEvent("onchange");
}
}
var hideAllMenus = function () {
opened = false;
input.value = previousValue;
hiddenInput.value = previousDataVal;
if (!dropdown.querySelector('.mdl-menu__container').classList.contains('is-visible')) {
dropdown.classList.remove('is-focused');
}
var menus = document.querySelectorAll('.getmdl-select .mdl-js-menu');
[].forEach.call(menus, function (menu) {
menu['MaterialMenu'].hide();
});
var event = new Event('closeSelect');
menu.dispatchEvent(event);
};
document.body.addEventListener('click', hideAllMenus, false);
//hide previous select after press TAB
dropdown.onkeydown = function (event) {
if (event.keyCode == 9) {
input.value = previousValue;
hiddenInput.value = previousDataVal;
menu['MaterialMenu'].hide();
dropdown.classList.remove('is-focused');
}
};
//show select if it have focus
input.onfocus = function (e) {
menu['MaterialMenu'].show();
menu.focus();
opened = true;
};
input.onblur = function (e) {
e.stopPropagation();
};
//hide all old opened selects and opening just clicked select
input.onclick = function (e) {
e.stopPropagation();
if (!menu.classList.contains('is-visible')) {
menu['MaterialMenu'].show();
hideAllMenus();
dropdown.classList.add('is-focused');
opened = true;
} else {
menu['MaterialMenu'].hide();
opened = false;
}
};
input.onkeydown = function (event) {
if (event.keyCode == 27) {
input.value = previousValue;
hiddenInput.value = previousDataVal;
menu['MaterialMenu'].hide();
dropdown.MaterialTextfield.onBlur_();
if (label !== '') {
dropdown.querySelector('.mdl-textfield__label').textContent = label;
label = '';
}
}
};
menu.addEventListener('closeSelect', function (e) {
input.value = previousValue;
hiddenInput.value = previousDataVal;
dropdown.classList.remove('is-focused');
if (label !== '') {
dropdown.querySelector('.mdl-textfield__label').textContent = label;
label = '';
}
});
//set previous value and data-val if ESC was pressed
menu.onkeydown = function (event) {
if (event.keyCode == 27) {
input.value = previousValue;
hiddenInput.value = previousDataVal;
dropdown.classList.remove('is-focused');
if (label !== '') {
dropdown.querySelector('.mdl-textfield__label').textContent = label;
label = '';
}
}
};
if (arrow) {
arrow.onclick = function (e) {
e.stopPropagation();
if (opened) {
menu['MaterialMenu'].hide();
opened = false;
dropdown.classList.remove('is-focused');
dropdown.MaterialTextfield.onBlur_();
input.value = previousValue;
hiddenInput.value = previousDataVal;
} else {
hideAllMenus();
dropdown.MaterialTextfield.onFocus_();
input.focus();
menu['MaterialMenu'].show();
opened = true;
}
};
}
[].forEach.call(list, function (li) {
li.onfocus = function () {
dropdown.classList.add('is-focused');
var value = li.textContent.trim();
input.value = value;
if (!dropdown.classList.contains('mdl-textfield--floating-label') && label == '') {
label = dropdown.querySelector('.mdl-textfield__label').textContent.trim();
dropdown.querySelector('.mdl-textfield__label').textContent = '';
}
};
li.onclick = function () {
setSelectedItem(li);
};
if (li.dataset.selected) {
setSelectedItem(li);
}
});
},
init: function (selector) {
var dropdowns = document.querySelectorAll(selector);
[].forEach.call(dropdowns, function (dropdown) {
getmdlSelect._addEventListeners(dropdown);
componentHandler.upgradeElement(dropdown);
componentHandler.upgradeElement(dropdown.querySelector('ul'));
});
}
};
}
<link rel="stylesheet" href="https://fonts.googleapis.com/icon?family=Material+Icons">
<link href="https://code.getmdl.io/1.3.0/material.indigo-pink.min.css" rel="stylesheet"/>
<script src="https://code.getmdl.io/1.3.0/material.min.js"></script>
<div class="mdl-textfield mdl-js-textfield getmdl-select">
<input type="text" value="" class="mdl-textfield__input" id="sample1" readonly>
<input type="hidden" value="" name="sample1">
<label for="sample1" class="mdl-textfield__label">Country</label>
<ul for="sample1" class="mdl-menu mdl-menu--bottom-left mdl-js-menu">
<li class="mdl-menu__item" data-val="DEU">Germany</li>
<li class="mdl-menu__item" data-val="BLR">Belarus</li>
<li class="mdl-menu__item" data-val="RUS">Russia</li>
</ul>
</div>
I have edited your code slightly, if I understood your problem correctly I think this is what you are looking for. Here's a working example.
//grab all the list items
let listItems = document.querySelectorAll( "li[class=mdl-menu__item]" );
//grab the input field
let textField = document.getElementById( "sample2" );
//add an eventListener on selection to change value the input field as well as display text
for ( let i = 0; i < listItems.length; i++ ) {
listItems[ i ].addEventListener( "click", function() {
textField.setAttribute("value", listItems[ i ].dataset.val );
textField.value = listItems[ i ].innerHTML;
});
}
<link rel="stylesheet" href="https://fonts.googleapis.com/icon?family=Material+Icons">
<link rel="stylesheet" href="https://code.getmdl.io/1.3.0/material.indigo-pink.min.css">
<script defer src="https://code.getmdl.io/1.3.0/material.min.js"></script>
<div class="mdl-textfield mdl-js-textfield getmdl-select">
<input type="text" value="" class="mdl-textfield__input" id="sample2" placeholder="Country" readonly>
<input type="hidden" value="" name="sample2">
<i class="mdl-icon-toggle__label material-icons">keyboard_arrow_down</i>
<ul for="sample2" class="mdl-menu mdl-menu--bottom-left mdl-js-menu">
<li class="mdl-menu__item" data-val="DEU">Germany</li>
<li class="mdl-menu__item" data-val="BLR">Belarus</li>
<li class="mdl-menu__item" data-val="RUS">Russia</li>
</ul>
</div>
Related
I'm creating something similar to a to-do-list project, but whenever I refresh the page I lose all the added items, I've tried using:
`
window.onbeforeunload = function () {
localStorage.setItem("list", $("#listItem").val());
};
window.onload = function () {
var name = localStorage.getItem("list");
if (name !== null) $("#listItem").val("list");
};
`
but still it doesn't work, I may have used it in the wrong place or wrong way. any help please?
here is my full code:
HTML:
`
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.1/jquery.min.js"></script>
<link rel="stylesheet" href="style.css" />
<title>To Do List</title>
</head>
<body>
<section class="section-center">
<form class="todolist-form">
<h3>To Do List!</h3>
<div class="input-button">
<input type="text" id="items-input" placeholder="e.g. eggs" />
<input
type="button"
class="submit-btn"
onclick="addItems()"
value="Submit"
/>
</div>
<div class="added-items">
<ul id="faves"></ul>
</div>
</form>
</section>
<script src="main.js"></script>
</body>
</html>
`
Javascript:
`
function addItems() {
var li = document.createElement("LI");
li.setAttribute("id", "listItem");
var input = document.getElementById("items-input");
li.innerHTML = input.value;
input.value = "";
document.getElementById("faves").appendChild(li);
var deleteBtn = document.createElement("button");
deleteBtn.classList.add("delete-btn");
deleteBtn.innerHTML = "Delete";
deleteBtn.type = "button";
document.getElementById("faves").appendChild(deleteBtn);
var hrzBreak = document.createElement("br");
document.getElementById("faves").appendChild(hrzBreak);
/*********/
window.onbeforeunload = function () {
localStorage.setItem("list", $("#listItem").val());
};
window.onload = function () {
var name = localStorage.getItem("list");
if (name !== null) $("#listItem").val("list");
};
}
`
What am I doing wrong? I've included jQuery's CDN too, but still it doesn't work.
var texts = [];
function addItems() {
var input = document.getElementById("items-input");
createElement(input.value)
input.value = "";
}
function createElement(value) {
var li = document.createElement("LI");
li.setAttribute("id", "listItem");
li.innerHTML = value;
document.getElementById("faves").appendChild(li);
var deleteBtn = document.createElement("button");
deleteBtn.classList.add("delete-btn");
deleteBtn.innerHTML = "Delete";
deleteBtn.type = "button";
document.getElementById("faves").appendChild(deleteBtn);
var hrzBreak = document.createElement("br");
document.getElementById("faves").appendChild(hrzBreak);
texts.push(value)
}
window.onbeforeunload = function () {
// Store text array in storage
localStorage.setItem("list", JSON.stringify(texts));
};
window.onload = function () {
// get list grom storage
var list = localStorage.getItem("list");
if (list !== null) {
list = JSON.parse(list)
for (let index = 0; index < list.length; index++) {
const element = list[index];
// create your dom element
createElement(element)
}
}
};
Using an Array to manage the data flow. This will do the job but still a mess.
Try adding event listeners once and outside of your function
window.onbeforeunload = function () {
localStorage.setItem("list", $("#listItem").val());
};
window.onload = function () {
var name = localStorage.getItem("list");
if (name !== null) $("#listItem").val("list")
};
function addItems() {
...
}
Assuming that $("#listItem").val() will return the data you want, place below block outsite of the addItems() function
window.onbeforeunload = function () {
localStorage.setItem("list", $("#listItem").val());
};
window.onload = function () {
var name = localStorage.getItem("list");
if (name !== null) $("#listItem").val("list");
};
Can anyone guide me in the correct direction please? I'm stuck with checked and not checked checkboxes. What I am trying to add:
Text in the text field & checkbox checked - hides the div element
Text in the text field & checkbox unchecked by entry - hides the first li element
Empty text field by entry & checkbox checked hides the second li element
What I have now:
let txt = document.getElementById("name")
let but = document.getElementById("send")
let out = document.getElementById("greeting")
let divv = document.getElementById("errors")
let nameError = document.getElementById("name-error")
let consError = document.getElementById("consent-error")
let cons = document.getElementById("consent")
but.disabled = true
divv.style.display = "block"
cons.addEventListener("input", function() {
if (cons.checked && txt.value !== '') {
consError.style.display = "none"
but.disabled = false
} else {
consError.style.display = "block"
but.disabled = true
}
})
txt.addEventListener("input", function() {
if (txt.value !== '' && cons.checked === false) {
but.disabled
} else {
but.disabled = false
}
})
function fun() {
out.textContent = "Hey " + txt.value + "!"
}
but.addEventListener("click", fun)
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>A checkbox</title>
</head>
<body>
<label for="name">Name</label>
<input id="name" placeholder="Name">
<label>
<input id="consent" type="checkbox">
I agree
</label>
<input id="send" type="button" value="Submit">
<p id="greeting"></p>
<div id="errors" style="color: red; display: none;">
<p>Error:</p>
<ul>
<li id="name-error">Please enter a name</li>
<li id="consent-error">Please give consent</li>
</ul>
</div>
<script src="index.js"></script>
</body>
</html>
Before I had cons.addEventListener like this and it was hiding the second li element but didn't keep the button disabled
cons.addEventListener("input", function() {
if (cons.checked){
consError.style.display = "none"
} else {
consError.style.display = "block"
}
})
move the validator outside to single function like this
function validator() {
if (cons.checked && txt.value !== '') {
but.disabled = false
divv.style.display = "none"
} else {
but.disabled = true
divv.style.display = "block"
}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>A checkbox</title>
</head>
<body>
<label for="name">Name</label>
<input id="name" placeholder="Name">
<label>
<input id="consent" type="checkbox"> I agree </label>
<input id="send" type="button" value="Submit">
<p id="greeting"></p>
<div id="errors" style="color: red; display: none;">
<p>Error:</p>
<ul>
<li id="name-error">Please enter a name</li>
<li id="consent-error">Please give consent</li>
</ul>
</div>
<script>
let txt = document.getElementById("name")
let but = document.getElementById("send")
let out = document.getElementById("greeting")
let divv = document.getElementById("errors")
let nameError = document.getElementById("name-error")
let consError = document.getElementById("consent-error")
let cons = document.getElementById("consent")
but.disabled = true
divv.style.display = "block"
function validator() {
if (cons.checked && txt.value !== '') {
but.disabled = false
divv.style.display = "none"
} else {
but.disabled = true
divv.style.display = "block"
}
}
cons.addEventListener("change", function () {
if (cons.checked) {
consError.style.display = "none"
} else {
consError.style.display = "block"
}
validator();
})
txt.addEventListener("input", function () {
if (txt.value !== '') {
nameError.style.display = "none"
} else {
nameError.style.display = "block"
}
validator()
})
function fun() {
out.textContent = "Hey " + txt.value + "!"
}
but.addEventListener("click", fun)
</script>
</body>
</html>
I am trying to make a To Do list but I have encountered a problem with storing it in local storage. I have tried storing the task in a var than it in localStorage but than when a new task is added it overwrites the variable and when I tried to store it in array and than when I tried to retrieve it from array all tasks appeared in a single task div. I want to store the tasks in local storage and have the task be edited, deleted, marked done also for localStorage too. I am providing the code.
<--JS-->
let tasksDiv = document.getElementById("tasks");
let oldTasksDiv = document.getElementById("old-tasks");
let input = document.getElementById('input');
var clear = document.getElementById('clear');
input.value = "What do you have planned?";
addBtn.addEventListener('click' , onclickBtn);
input.addEventListener('keypress' , function(){
if(event.keyCode === 13){
onclickBtn();
}
});
input.addEventListener('click' , function (){
if(input.value === "What do you have planned?"){
input.value ="";
}
})
clear.addEventListener('click' , function (){
input.value ="";
})
function onclickBtn(){
if(input.value.length !== 0){
var tasksName = document.createElement('div');
tasksName.classList.add("tasks-div")
var task = document.createElement('p');
task.innerText = input.value;
task.classList.add("task");
var del = document.createElement('button');
del.classList.add("del");
del.innerHTML = '<i class="fas fa-solid fa-trash"></i>';
var edit = document.createElement('button');
edit.classList.add("edit");
edit.innerHTML = '<i class="fas fa-solid fa-pen-to-square"></i>';
var save = document.createElement('button');
save.classList.add("save");
save.innerHTML = '<i class="fas fa-solid fa-floppy-disk"></i>';
var chkbox = document.createElement('input');
chkbox.classList.add("chkbox")
chkbox.type = "checkbox";
tasksName.appendChild(chkbox);
tasksName.appendChild(task);
tasksName.appendChild(del);
tasksName.appendChild(edit);
tasksName.appendChild(save);
tasksDiv.appendChild(tasksName);
chkbox.addEventListener('click' , function(){
if(chkbox.checked === true){
task.style.textDecoration = "line-through red";
edit.style.display = "none";
save.style.display = "none";
}
else{
task.style.textDecoration = "none";
edit.style.display = "block";
}
})
del.addEventListener('click' , function(){
tasksDiv.removeChild(tasksName);
})
edit.addEventListener('click' , function(){
task.contentEditable = true;
task.focus();
edit.style.display = "none";
save.style.display = "block";
})
save.addEventListener('click' , function(){
if(task.innerHTML === '<br>'){
alert('This task will be deleted');
tasksDiv.removeChild(tasksName);
}
task.contentEditable = false;
task.blur();
edit.style.display = "block";
save.style.display = "none";
})
}
else{
alert("Please enter a task");
}
}
<-- HTML -->
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Tasks Keeper</title>
<link rel="stylesheet" href="./css/style.css">
<link rel="stylesheet" href="./css/resp.css">
<script src="https://kit.fontawesome.com/6bf6193572.js" crossorigin="anonymous"></script>
<script src="https://kit.fontawesome.com/9b41c17796.js" crossorigin="anonymous"></script>
</head>
<body>
<header>
<div class="brand-div">
<h1><span class="brand">Tasks Keeper</span></h1>
<span class="made-by">Made By Raghav Srvt</span>
</div>
<div class="input-div">
<div class="input-div-clear">
<input type="text" placeholder="What do you have planned?" id="input" value="What do you have planned?">
<i class="fa-solid fa-xmark" id="clear"></i>
</div>
<button type="submit" id="add-btn">Add</button>
</div>
</header>
<div id="tasks">
</div>
<script src = "./app.js"></script>
</body>
</html>
You can insert todos as object into an Array and store it on LocalStorage.
It is a Functionality that makes it Easy for you.
function LsHandling() {
return {
get: function (key) {
const item = localStorage.getItem(key);
if (item) {
return JSON.parse(item);
}
},
set: function (todo, key) {
const item = localStorage.getItem(key);
if (item) {
const itemToArray = [...JSON.parse(item)];
for (data in itemToArray) {
if (itemToArray[data].id === todo.id) {
return;
} else {
itemToArray.push(todo)
localStorage.setItem(key, JSON.stringify(itemToArray));
}
}
} else {
const defaultArray = [todo];
localStorage.setItem(key, JSON.stringify(defaultArray));
}
},
};
}
And you can use it Like This :
for getting the todosArray : LsHandling().get(yourKey)
for setting a todo in todosArray : LsHandling().set(todoObject, yourKey)
Note : for deleting or editing todos , you must define an id for each todo
I am trying to cretae an expand/collapse menu using javascript. The structure something like this.
.menu
.subItem
.subItem
this a part of css
ul.menu {
display: none
}
but menu items not expandind from the collapse
this the js file
window.onload = initAll;
function initAll() {
var allLink = document.getElementsByTagName("a");
for (var i = 0; i < allLink.length; i++) {
if (allLink[i].className.indexOf("menuLink") > -1) {
allLink[i].onclick = togle;
}
}
}
function togle() {
var startMenu = this.href.lastIndexOf("/") + 1;
var stopMenu = this.href.lastIndexOf(".");
var thisMenuName = this.href.substring(startMenu, stopMenu);
var thisMenu = document.getElementById(thisMenuName).style;
if (thisMenu.display == "block") {
thisMenu.display = "none";
} else {
thisMenu.display = "block";
}
return false;
}
when I open up chrome developer tools I have realize that Its been pointed out
this line once click the menu
var thisMenu = document.getElementById(thisMenuName).style;
What am doing wrong again again again
#Edit:I forgot to add html file
<link rel="stylesheet" href="css.css">
<script src="js.js"></script>
a
</head>
<body>
<div>
trajedi
<ul class="menu" id="menu1">
<li>deneme</li>
<li>deneme</li>
</ul>
</div>
I don't know what you tried to do with the substring part in togle function. That's the only problem with your code. Change the line:
var thisMenu = document.getElementById(thisMenuName).style;
to
var thisMenu = document.getElementById('menu1').style;
and it will work. Take a look:
window.onload = initAll;
function initAll() {
var allLink = document.getElementsByTagName("a");
for (var i = 0; i < allLink.length; i++) {
if (allLink[i].className.indexOf("menuLink") > -1) {
allLink[i].onclick = togle;
}
}
}
function togle(e) {
// can't understand the use of the 3 lines below:
var startMenu = this.href.lastIndexOf("/") + 1;
var stopMenu = this.href.lastIndexOf(".");
var thisMenuName = this.href.substring(startMenu, stopMenu);
var thisMenu = document.getElementById('menu1').style;
if (thisMenu.display == "block") {
thisMenu.display = "none";
} else {
thisMenu.display = "block";
}
return false;
}
ul.menu {
display: none
}
<div>
trajedi
<ul class="menu" id="menu1">
<li>deneme</li>
<li>deneme</li>
</ul>
</div>
a much simpler and modern version of your code would be:
function initAll() {
Array.from(document.getElementsByTagName("a"))
.filter((link)=>link.className.indexOf("menuLink") > -1)
.forEach((link)=>link.onclick = ()=>{
var thisMenu = document.getElementById('menu1').style;
thisMenu.display = (thisMenu.display == "block") ? 'none' : 'block';
return false;
});
}
window.onload = initAll;
ul.menu {
display: none
}
<div>
trajedi
<ul class="menu" id="menu1">
<li>deneme</li>
<li>deneme</li>
</ul>
</div>
I have a case in which I need to divide tags when the user put a comma separation, for the moment the user can only add tags one by one, what I want to do is allows user to enter more than one tag in the input separated by a comma:
This is what I have now :
this is what I want to do :
what I have so far :
<div class="form-group">
<label>Mes centres d'intérêt</label>
<div class="input-group" style="margin-bottom: 8px;">
<input id="tagInsert" type="text" name="newTag" ng-model="newTag" ng-model-options="{debounce: 100}" typeahead="tag for tag in getTags($viewValue)" class="form-control" typeahead-loading="loadingTags" ng-keydown="addInterestOnEvent($event)" ng-disabled="interestLimit" autocomplete="off">
<span class="input-group-btn"><span class="btn btn-primary" ng-click="addInterest()" analytics-on="click" ng-disabled="interestLimit" analytics-event="Ajout Interet" analytics-category="Profil">Ajouter</span></span>
</div>
<p class="form__field__error" ng-show="interestLimit">Vous avez atteint la limite de 10 centres d'intérêt.</p>
<ul class="tags">
<li class="tag" ng-repeat="name in user.interests track by $index">{{ name }} <i class="icon-close" ng-click="removeInterest($index)" analytics-on analytics-event="Supprimer Interet" analytics-category="Profil"></i></li>
</ul>
</div>
My controller :
$scope.getTags = function (name) {
return $http.get('/api/tags/' + name.replace('/', '')).then(function (result) {
var tags = result.data;
for (var i = tags.length; i--; ) {
var tagName = tags[i].name;
if ($scope.user.interests.indexOf(tagName) !== -1) tags.splice(i, 1);
else tags[i] = tagName;
}
return tags;
});
};
$scope.removeInterest = function (id) {
$scope.interestLimit = false;
$scope.user.interests.splice(id, 1);
}
$scope.addInterest = function () {
if ($scope.interestLimit) return;
var element = $document[0].getElementById('tagInsert'),
value = element.value;
if (value.length) {
element.value = '';
if ($scope.user.interests.indexOf(value) === -1) {
$scope.user.interests.push(value);
$scope.interestLimit = $scope.user.interests.length === 10;
}
}
};
$scope.addInterestOnEvent = function (event) {
if (event.which !== 13) return;
event.preventDefault();
$scope.addInterest();
};
$scope.remove = function () {
$scope.confirmModal = Modal.confirm.delete(function () {
User.remove(function () {
submit = true;
Auth.logout();
$location.path('/');
});
})('votre compte');
};
You should split value with comma and do for loop.
Change "addInterest" function like this:
$scope.addInterest = function () {
if ($scope.interestLimit) return;
var element = $document[0].getElementById('tagInsert'),
value = element.value.split(',');
if (value.length) {
element.value = '';
for (var i = 0; i < value.length; i++) {
if ($scope.interestLimit) break;
if ($scope.user.interests.indexOf(value[i]) === -1) {
$scope.user.interests.push(value[i]);
$scope.interestLimit = $scope.user.interests.length === 10;
}
}
}
};
As far as I understand , you want to split text into string array by comma
Try this code please
<input id='tags' type="text" />
<input type="button" value="Click" onclick="seperateText()" />
<script>
function seperateText(){
var text= document.getElementById("tags").value;
var tags = text.split(',');
console.log(text);
console.log(tags);
}
</script>