How to check for specific object key and update if exists - javascript

I have text inputs that are writing to a model. I want those objects to write to the model and update if the key exists.
For example: If I submit,
Id: "1", Value: "Foo"
And I update it with a new value:
Id: "1", Value: "Bar"
My array should read:
0 { Id: "1", Value: "Bar"}
Not
0 { Id: "1", Value: "Foo"}
1 { Id: "1", Value: "Bar"}
Example here: JSFiddle
<div id="wrapper">
<div>
<input id="1" type="text" value="input_1">
<button>Button 1</button>
</div>
<br>
<div>
<input id="2" type="text" value="input_2">
<button>Button 2</button>
</div>
<br>
<div>
<input id="3" type="text" value="input_3">
<button>Button 3</button>
</div>
<br>
</div>
jQuery -- will add to the array but not sure how to update if key exists. Looked at other examples but still not getting it
var obj = {
pairs: []
}
$("button").on("click", function() {
var keyValuePairs = {
id: "",
value: ""
}
var input_id = $(this).prev().prop('id');
var dynamic_value = $(this).prev().prop('value');
if(obj.pairs.length > 0){
$.each(obj.pairs, function(i, pair) {
if($(this).id !== input_id){
obj.pairs.push(keyValuePairs);
return false;
} else {
obj.pairs.splice(i, 1);
obj.pairs.push(keyValuePairs);
}
});
} else {
obj.pairs.push(keyValuePairs);
}
keyValuePairs.id = input_id;
keyValuePairs.value = dynamic_value;
console.log(obj);
});

Try this https://jsfiddle.net/y6rgm7z8/93/
$(document).ready(function() {
var obj = {
pairs: []
}
$("button").on("click", function() {
var keyValuePairs = {
id: "",
value: ""
}
var input_id = $(this).prev().prop('id');
var dynamic_value = $(this).prev().prop('value');
var pair = obj.pairs.find(item => item.id === input_id)
if(pair){
pair.value = dynamic_value;
} else {
keyValuePairs.id = input_id;
keyValuePairs.value = dynamic_value;
obj.pairs.push(keyValuePairs);
}
console.log(obj);
});
});
The find() method executes the function once for each element present in the array:
If it finds an array element where the function returns a true value, find() returns the value of that array element (and does not check the remaining values)
Otherwise it returns undefined
The find() is better for performance than each().
And we don't need splice() with push() for updating because after find() we have link to the object, so we can change the value.
If find() returns undefined we will push the new object to the array

See if this helps
$(document).ready(function() {
var obj = {
pairs: []
}
$("button").on("click", function() {
var found = false;
var input_id = $(this).prev().prop('id');
var dynamic_value = $(this).prev().prop('value');
var keyValuePairs = {
id: input_id,
value: dynamic_value
}
if(obj.pairs.length > 0){
$.each(obj.pairs, function(i, pair) {
if(pair[Object.keys(pair)[0]] === input_id){
obj.pairs[i] = keyValuePairs;
found = true;
return false;
}
});
if(!found)
obj.pairs.push(keyValuePairs);
} else {
obj.pairs.push(keyValuePairs);
}
console.log(obj);
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="wrapper">
<div>
<input id="1"type="text" value="input_1">
<button>Button 1</button>
</div>
<br>
<div>
<input id="2" type="text" value="input_2">
<button>Button 2</button>
</div>
<br>
<div>
<input id="3" type="text" value="input_3">
<button>Button 3</button>
</div>
<br>
</div>

I finally changed a lot...
I used a flag to know if the update was done...
So I run the .each() loop first. It doesn't run if there is no key/pair already. Then a comparison if the change was not yet done, to push a new value.
var obj = {
pairs: []
}
$("button").on("click", function() {
var keyValuePairs = {
id: "",
value: ""
}
var change_done=false;
var input_id = $(this).prev().prop('id');
var dynamic_value = $(this).prev().prop('value');
$.each(obj.pairs, function(i, pair) {
if(obj.pairs[i].id == input_id){ // Change is here.
obj.pairs[i].id=input_id;
obj.pairs[i].value=dynamic_value;
change_done=true;
return false;
}
});
if(!change_done || obj.pairs.length == 0){
obj.pairs.push(keyValuePairs);
}
keyValuePairs.id = input_id;
keyValuePairs.value = dynamic_value;
console.log(obj);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="wrapper">
<div>
<input id="1 "type="text" value="input_1">
<button>Button 1</button>
</div>
<br>
<div>
<input id="2" type="text" value="input_2">
<button>Button 2</button>
</div>
<br>
<div>
<input id="3" type="text" value="input_3">
<button>Button 3</button>
</div>
<br>
</div>

I have rewritten a bit. If ID exists, its value will be updated and new row will not be inserted:
$(document).ready(function() {
var obj = {
pairs: []
}
$("button").on("click", function() {
var input_id = $(this).prev().prop('id');
var dynamic_value = $(this).prev().prop('value');
var isUpdated = false;
var keyValuePairs = {
id: input_id,
value: dynamic_value
};
if (obj.pairs.length == 0) {
obj.pairs.push(keyValuePairs);
return false;
}
$.each(obj.pairs, function(i, pair) {
if (obj.pairs[i].id === input_id) {
obj.pairs[i].value = dynamic_value;
isUpdated = true;
return false;
}
});
if (!isUpdated) {
obj.pairs.push(keyValuePairs);
}
console.log(obj);
});
});
Tested and it works.

You can do it like this:
const pair = obj.pairs.find(pair => pair.id === input_id);
if (pair) {
obj.pairs[input_id] = {...keyValuePairs}
} else {
obj.pairs.push(keyValuePairs)
}

Related

jQuery saving data and loading every refresh page

Hey im really newbie of walking around in js, saw a nice code about to-do list and would like to save it in every refresh page (in local storage). Have tried savy.js plugin but it doesn't really work. Was thinking about making some json file but don't really know how it would work in jQuery. here is my code:
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="list">
<input type="text" class="txtb" placeholder="Add a task">
<div class="notcomp">
<h3>Not Completed</h3>
</div>
<div class="comp">
<h3>Completed</h3>
</div>
</div>
<script type="text/javascript">
$(".txtb").on("keyup", function(e) {
if (e.keyCode == 13 && $(".txtb").val() != "") {
var task = $("<div class='task'></div>").text($(".txtb").val());
var del = $("<i class='fas fa-trash-alt'></i>").click(function() {
var p = $(this).parent();
p.fadeOut(function() {
p.remove();
})
});
var check = $("<i class='fas fa-check'></i>").click(function() {
var p = $(this).parent();
p.fadeOut(function() {
$(".comp").append(p);
p.fadeIn();
});
$(this).remove();
});
task.append(del, check);
$(".notcomp").append(task);
$(".txtb").val("");
}
});
</script>
Aprieciate for any help.
try this code or check the example at Task List
HTML
<div class="list">
<input type="text" class="txtb" placeholder="Add a task">
<div class="notcomp">
<h3>Not Completed</h3>
</div>
<div class="comp">
<h3>Completed</h3>
</div>
</div>
jQuery
$(document).ready(function() {
var data = localStorage.getItem("todo");
if (data != "" && data != null) {
data = JSON.parse(data);
for (const [key, value] of Object.entries(data)) {
insertTask(value);
}
} else {
data = [];
}
function insertTask(data) {
var task = $("<div class='task'></div>").text(data.value);
var del = $("<i class='fa fa-trash' ></i>").click(function() {
removeData(data.id);
$(this)
.parent(".task")
.fadeOut("slow", function() {
$(this).remove();
});
});
task.append(del);
$(".notcomp").append(task);
}
function removeData(id) {
console.log(id);
for (const [key, value] of Object.entries(data)) {
if (value.id === id) {
data.splice(key, 1);
localStorage.setItem("todo", JSON.stringify(data));
return false;
}
}
}
$(".txtb").on("keyup", function(e) {
if (e.keyCode == 13 && $(".txtb").val() != "") {
let val = $(".txtb").val();
var unix = Math.round(+new Date() / 1000);
var taskData = {
value: val,
id: unix
};
data.push(taskData);
insertTask(taskData);
localStorage.setItem("todo", JSON.stringify(data));
$(".txtb").val("");
}
});
});

Issue with multi dimensional becoming empty after assigning to var

I'm having a very strange issue with javascript where I'm building a multi dimensional array and somehow it's being emptied to [[]] on var assignment.
The target being passed to the buildFormObject function is a html form element.
if (!Element.prototype.closest) {
Element.prototype.closest = function(s) {
var el = this;
if (!document.documentElement.contains(el)) return null;
do {
if (el.matches(s)) return el;
el = el.parentElement || el.parentNode;
} while (el !== null && el.nodeType === 1);
return null;
};
}
var submit = document.getElementsByClassName('submit');
submitForm_click(submit);
function submitForm_click (trigger) {
if (trigger.length > 0) {
for (var t of trigger) {
t.addEventListener('click', function (e) {
e.preventDefault();
submitForm(t.parentNode);
});
}
} else {
trigger.addEventListener('click', function (e) {
e.preventDefault();
submitForm(trigger.parentNode);
});
}
}
function submitForm (target) {
var info = buildFormObject(target);
console.log(buildFormObject(target));
console.log(info);
}
function buildFormObject (target) {
var inputs = target.querySelectorAll('input,select');
var results = [];
var multi = [];
var iter = 0;
var pos = 0;
for (var input of inputs) {
if (iter > 0) {
iter = iter - 1;
continue;
}
if (input.parentNode.closest('.multiInput') != null) {
var obj = [];
var parent = input.parentNode.closest('.multiInput');
var children = parent.querySelectorAll('input,select');
for (var i of children) {
if (checkIfValueExist(i, i.type)) {
obj[i.name] = i.value;
}
}
multi[pos] = obj;
results[parent.attributes.name.nodeValue] = multi;
pos = pos + 1;
iter = children.length-1;
} else if (checkIfValueExist(input, input.type)) {
results[input.name] = input.value;
pos = 0;
multi = [];
}
}
return results;
}
function checkIfValueExist (target, type) {
switch (type) {
case 'text':
return (target.value == "" ? false : true);
break;
case 'select-one':
return (target.value == "" ? false : true);
break;
case 'checkbox':
return (target.checked === false ? false : true);
break;
case 'radio':
return (target.checked === false ? false : true);
break;
case 'button':
return false;
break;
case 'submit':
return false;
break;
default:
return true;
break;
}
}
<form id="ct">
<input type="hidden" name="task" value="createTable"/>
<div id="tableSection" class="flexContainer">
<div class="block">
<label for="dbName">Select Database</label>
<select name="dbName" class="dbList" required>
<option value="" disabled selected>Please Select</option>
<option value="1">test</option>
</select>
</div>
<div class="block">
<label for="tableName">Table Name</label>
<input type="text" name="tableName" required/>
</div>
</div>
<div class="row flexContainer multiInput" name="tableRow">
<div class="trColumn">
<label for="columnName">Name</label>
<input type="text" name="columnName" required/>
</div>
<div class="trColumn">
<label for="columnType">DataType</label>
<select name="columnType" required>
<option value="" disabled selected>Please Select</option>
<option value="1">CHAR</option>
</select>
</div>
<div class="trColumn">
<label for="columnLength">Length</label>
<input type="text" name="columnLength"/>
</div>
<div class="trColumn">
<label for="columnPK">PK</label>
<input type="checkbox" name="columnPK" value="1"/>
</div>
<div class="trColumn">
<label for="columnDefault">DefaultValue</label>
<input type="text" name="columnDefault"/>
</div>
</div>
<input type="button" class="submit" value="Submit" />
</form>
Result 1:
[task: "createDBTable", dbName: "1", tableName: "tester", tableRow: Array(1)]
dbName: "1"
tableName: "tester"
tableRow: [Array(0)]
task: "createDBTable"
length: 0
__proto__: Array(0)
Result 2:
[task: "createDBTable", dbName: "1", tableName: "tester", tableRow: Array(1)]
dbName: "1"
tableName: "tester"
tableRow: "[[]]"
task: "createDBTable"
length: 0
__proto__: Array(0)
What I don't understand is why the tableRow is going from an Array(6) value to [[]] just because I setting the original variable, the returned value from the buildFormObject function, to a variable.
ADDITIONAL INFORMATION
In the code snippet above I have included the code I'm working with. There seems to be a small quirk where the console.log is only showing [], but you you type one of the property names that should be there like, "tableName"then you can access the value. This isn't true for the problem property of "tableRow" since the nested array is showing as []. I'm not sure if it's the testing software, but if you try it on a local test environment then you shouldn't have any issues seeing what my initial problem is.

Angularjs devade tags when user put comma

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>

Defining JSON dynamically - can't find what I am doing wrong

I am trying to put form content in a JSON dynamically.
It worked before, but after I added a extra layer (arrays in arrays) there seem to be something that I am doing wrong:
aJSON = {};
aJSON['properties'] = [];
aJSON['options'] = [];
aJSON['arrays'] = [];
$('input').each(function () {
if($(this).attr('name') != undefined) {
if($(this).attr('name').indexOf('[]') > -1) {
if(aJSON['arrays'][$(this).attr('name')] == undefined) {
aJSON['arrays'][$(this).attr('name')] = [];
}
if($(this).is(':checked')) {
aJSON['arrays'][$(this).attr('name')][$(this).attr('value')] = 1;
} else {
aJSON['arrays'][$(this).attr('name')][$(this).attr('value')] = 0;
}
} else {
aJSON['properties'][$(this).attr('name')] = $(this).val();
}
}
});
$('select').each(function () {
if($(this).attr('name') != undefined) {
aJSON['properties'][$(this).attr('name')] = $(this).val();
}
});
var array = getUrlVars();
aJSON['options']['type'] = array['type'];
aJSON['options']['id'] = array['id'];
aJSON['options']['view'] = pageSpecificVariables['view'];
The top 4 lines are just a tryout, I also tried:
aJSON = {'properties':[], 'options':[], 'arrays':[]}
But the only result I am getting is an object with empty arrays of properties, options and arrays.
Before I put all the values directly in aJSON and that worked perfectly.
But for categorizing, I need the 3 categories to exist.
Any idea why my values aren't written to the aJSON?
EDIT
Added JSfiddle here: http://jsfiddle.net/abayob/pob32fs1/
I assume you are trying to serialise a form.
Use jQuery's serializeArray function instead
var myform = $("#myform");
var data = JSON.stringify( myform.serializeArray() );
Update
Because you're trying to use arrays like object-maps
Solution: http://jsfiddle.net/pob32fs1/8/
var oJSON = {
properties: {},
options: {},
arrays: {}
};
$('input[name]').each(function(){
var $el = $(this),
value = $el.attr("value"),
name = $el.attr('name');
if(name.indexOf('[]') >= 0)
{
oJSON.arrays[name] = oJSON.arrays[name] || {};
oJSON.arrays[name][value] = $el.is(':checked') ? 1 : 0;
} else {
oJSON.properties[name] = $el.val();
}
});
$('select[name]').each(function(){
var $el = $(this);
oJSON.properties[$el.attr('name')] = $el.val();
});
oJSON.options['type'] = 'user';
oJSON.options['id'] = 1;
oJSON.options['view'] = 'user-settings';
console.log(oJSON);
Assuming that the name and value attributes of your various inputs are strings, and not just numbers, you should be using nested objects, not nested arrays. You're trying to use associative arrays, which are not available in JavaScript.
var oJSON = {};
$('._save, .btn-success').click(function() {
oJSON = {
properties: {},
options: {},
arrays: {}
};
$('input').each(function() {
if ($(this).attr('name') != undefined) {
if ($(this).attr('name').indexOf('[]') > -1) {
if (oJSON['arrays'][$(this).attr('name')] == undefined) {
oJSON['arrays'][$(this).attr('name')] = {};
}
if ($(this).is(':checked')) {
oJSON['arrays'][$(this).attr('name')][$(this).attr('value')] = 1;
} else {
oJSON['arrays'][$(this).attr('name')][$(this).attr('value')] = 0;
}
} else {
oJSON['properties'][$(this).attr('name')] = $(this).val();
}
}
});
$('select').each(function() {
if ($(this).attr('name') != undefined) {
oJSON['properties'][$(this).attr('name')] = $(this).val();
}
});
oJSON['options']['type'] = 'user';
oJSON['options']['id'] = 1;
oJSON['options']['view'] = 'user-settings';
console.log(oJSON);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div class="tab-content">
<div id="tab-general" class="tab-pane active">
<h4>Gebruikersnaam</h4>
<input type="text" value="John Doe" name="username" class="form-control" required="" placeholder="J. Average">
<h4>E-mailadres</h4>
<input type="email" value="info#info.info" name="mailaddress" class="form-control" required="" placeholder="E-mail#adres.nl">
<div class="row">
<div class="col-md-6">
<input type="password" name="password" minlength="10" class="form-control" placeholder="Nieuw wachtwoord">
</div>
<div class="col-md-6">
<input type="password" name="password_retype" minlength="10" class="form-control" placeholder="Herhaal wachtwoord">
</div>
</div>
<input type="password" name="password_old" class="form-control margin-y-10" placeholder="Huidig Wachtwoord">
</div>
<div id="tab-sites" class="tab-pane">
<h4>Websites</h4>
<div id="site_container">
<div class="checkbox block">
<input name="sites[]" checked="" type="checkbox" value="0">
<label>A</label>
</div>
<div class="checkbox block">
<input name="sites[]" checked="" type="checkbox" value="1">
<label>B</label>
</div>
<div class="checkbox block">
<input name="sites[]" checked="" type="checkbox" value="2">
<label>C</label>
</div>
</div>
</div>
</div>
<div class="panel-footer">
<button type="button" class="btn btn-warning _cancel">Annuleren</button>
<button type="button" class="btn btn-success _save">Opslaan</button>
</div>

How to seperate the values of textbox so that I can sort by each value

I have a textbox where the user can input a value into a listbox. Then, I have buttons to either Delete that value, or Sort the value.
My problem is that I want the value to be sorted by those 2 separated values. For example, the user would enter City=Chicago in the textbox. And there would be 2 sort buttons, to 'Sort by City' and 'Sort by Value' where value in this case is Chicago.
So after hours of trying I can't figure out how to:
1. Restrict the user to only be able to enter a value like %=% (e.g. City=Chicago)
2. Have separate sort buttons for the values on either side of the equal sign
http://jsfiddle.net/uudff585/6/
<div class='teststyles'>
<h3>Test</h3>
Name/Value Pair
<br />
<input id="PairTextbox" type="text" value="city" />=<input id="PairTextbox1" type="text" />
<input type="button" value="Add" id="addButton" />
<br />
<br />Name/Value Pair List
<br />
<select multiple="multiple" id="PairListbox"></select>
<input type="button" value="Sort By Name" sort-type="0" id="sortName">
<input type="button" value="Sort By Value" sort-type="1" id="sortValue"><br>
<input type="button" value="Delete" id="deleteButton" />
Script:
var listArray = [];
function addNewItem() {
console.log("ok2");
var textbox = document.getElementById('PairTextbox');
var textbox1 = document.getElementById('PairTextbox1');
var listbox = document.getElementById('PairListbox');
var newOption = document.createElement('option');
newOption.value = listArray.length-1; // The value that this option will have
newOption.innerHTML = textbox.value + "=" + textbox1.value; // The displayed text inside of the <option> tags
listbox.appendChild(newOption);
listArray.push([textbox.value, textbox1.value, ]);
}
function deleteItem() {
var listbox = document.getElementById('PairListbox');
if (listbox.selectedIndex != -1) {
console.log(listbox.selectedIndex);
delete listArray[listbox.value];
listbox.remove(listbox.selectedIndex);
}
}
function sortItems(e) {
var sorttype = e.target.getAttribute("sort-type");
var $listbox = document.getElementById('PairListbox');
var $options = listArray.map(function (option) {
return option;
});;
$options.sort(function (a, b) {
var an = a[sorttype],
bn = b[sorttype];
if (an > bn) {
return 1;
}
if (an < bn) {
return -1;
}
return 0;
});
$listbox.innerHTML = "";
$options.forEach(function ($option, index) {
var newOption = document.createElement('option');
newOption.value = index; // The value that this option will have
newOption.innerHTML = $option[0] + "=" + $option[1]; // The displayed text inside of the
$listbox.appendChild(newOption);
});
}
document.getElementById('addButton').addEventListener('click', addNewItem);
document.getElementById('sortName').addEventListener('click', sortItems);
document.getElementById('sortValue').addEventListener('click', sortItems);
document.getElementById('deleteButton').addEventListener('click', deleteItem);
For those who would like to use jQuery, validation and auto-sorting this FIDDLE. The HTML is:
<div class='teststyles'>
<h3>Test</h3>
<p>Name/Value Pair</p>
<p><input id="PairTextbox" type="text" /> <input type="button" value="Add" id="addButton" /></p>
<p>Name/Value Pair List</p>
<p><select multiple="multiple" id="PairListbox"></select></p>
<p>
<input id="byname" type="radio" name="sortby" value="name" checked="checked" /> <label for="byname">sort by name</label><br />
<input id="byvalue" type="radio" name="sortby" value="value" /> <label for="byvalue">sort by value</label>
</p>
<p><input type="button" value="Delete selected" id="deleteButton" /></p>
</div>
and the script:
// Keep your pairs in memory
var pairs = [];
// Keep record of dynamic elements
var listbox = $('#PairListbox');
var textbox = $('#PairTextbox');
var sortInput = $('input[name=sortby]');
function sortItems() {
sortType = sortInput.filter(':checked').val();
if ( sortType=='name' ) {
// Sort by key
console.log( 'sort by key' );
pairs = pairs.sort(function (a, b) {
return a.k.localeCompare(b.k);
});
} else {
// Sort by value
console.log( 'sort by val' );
pairs = pairs.sort(function (a, b) {
return a.v.localeCompare(b.v);
});
};
console.log( pairs );
console.log( '----------' );
};
function printItems() {
var optionsHtml = '';
$.each(pairs, function(i, item) {
optionsHtml += '<option value="' + item.k + '=' + item.v + '">' + item.k + '=' + item.v + '</option>';
});
listbox.html(optionsHtml);
};
// Customize validation of new input
function validateInput() {
var str = textbox.val().replace(/\s+/g, '_');
var splited = str.split('=');
if (splited.length == 2 && splited[0] && splited[1]) {
// Maybe also check if pair already exists in array?
pairs.push({
k: splited[0],
v: splited[1]
});
return true;
} else {
false;
};
}
function addNewItem() {
if (validateInput()) {
sortItems();
printItems();
} else {
alert('Wrong input value!');
}
}
function deleteItem() {
var selectedItems = listbox.find('option:selected');
selectedItems.each(function(i) {
var thisItem = $(this);
var thisValueSplit = thisItem.val().split('=');
pairs = pairs.filter(function (el) {
return !(el.k==thisValueSplit[0] && el.v==thisValueSplit[1]);
});
printItems();
});
}
$('#addButton').on('click', addNewItem);
$('#deleteButton').on('click', deleteItem);
sortInput.on('change', function(e) {
sortItems();
printItems();
});

Categories

Resources