my javascript for creating unique IDs isn't working - javascript

I'm trying to create unique ids, and I can't see why it's not working. Guess I'm blind staring at the same code for too long. I would appreciate if someone could help me! :)
function laggtill(cool, namnVara) {
var date = new Date();
var id = "" + date.getHours() + date.getMinutes() + date.getSeconds() + date.getMilliseconds();
var vara = document.createElement("li");
var checkBox = document.createElement("input");
checkBox.type = "checkbox";
var span = document.createElement("span");
span.innerText = namnVara;
vara.appendChild(checkBox);
vara.appendChild(span);
cool.appendChild(vara);
}
var button = document.getElementById("knapp");
button.onclick = function() {
var skriva = document.getElementById("skriva")
var namnVara = skriva.value;
if (!namnVara || namnVara == "" || namnVara == " ") {
return false;
}
};

Stole this from jQuery UI. It's as simple as it's effective:
// at initialization
var uuid = 0;
// and when you need a unique id
var uniqueId = 'uid-' + (++uuid);
No need for complicated stuff like getting dates etc. unique != complicated
And to set the ID to an element:
var element = document.createElement('div');
element.id = uniqueId;
And if you want to use it more often in a script, you could create a function:
var uuid = 0; // put it in the 'global scope'
var uniqueId = function() {
return 'uid-' + (++uuid);
};
alert(uniqueId()); // uid-1
alert(uniqueId()); // uid-2

if you really want to keep the date.
var d = new Date();
var id = "" + d.getHours() + d.getMinutes() + d.getSeconds()+ d.getMilliseconds();
add some stuff to generate guid to :
var guid = (function() {
function s4() {
return Math.floor((1 + Math.random()) * 0x10000)
.toString(16)
.substring(1);
}
return function() {
return s4() + s4() + '-' + s4() + '-' + s4() + '-' +
s4() + '-' + s4() + s4() + s4();
};
})();
http://jsfiddle.net/mz4qpg1L/1/
if you want to append id to youre control, i like appending html directly :
vara.appendChild('<span id=' + id + ' ></span>');
this way you can put any attribute you want.

Related

Deleting an object from an array on click of a button

I am trying to create my own small Twitter.
It is all working fine but I cannot find a way to delete specific tweet on click of a button. I have tried splice() but it deletes the first object of an array always.
Here is my code:
var tweets = []
function postNewTweet() {
var today = new Date();
var date = today.getDate() + '-' + (today.getMonth() + 1) + '-' + today.getFullYear();
var time = today.getHours() + ':' + today.getMinutes();
var id = tweets.length + 1;
var li = document.createElement('li');
var inputValue = document.getElementById('newTweet').value;
var finalValue = id + ' ' + inputValue + ' ' + date + ' ' + time;
var t = document.createTextNode(finalValue);
li.appendChild(t);
tweets.push({
id: id,
content: inputValue,
date: date + ' ' + time
});
document.getElementById('list').appendChild(li);
document.getElementById('newTweet').value = "";
console.log(tweets);
var buttonDelete = document.createElement("button");
buttonDelete.innerHTML = '<i class="far fa-trash-alt"></i>';
buttonDelete.onclick = deleteItem;
function deleteItem(e) {
var ul = document.getElementById('list');
ul.removeChild(li);
var list = document.getElementById('list');
list.addEventListener('click', function(e) {
var index = e.target.getAttribute('value');
tweets.splice(index, 1);
console.log(tweets)
});
}
li.appendChild(buttonDelete);
}
<div id='post'>
<textarea maxlength="160" id='newTweet'></textarea>
<button id='postIt' onclick="postNewTweet()">Post</button>
</div>
<ul id='list'>
</ul>
So it deletes it in HTML, but not in array correctly.
The second part of your deleteItem function's body seems useless. While there are couple of ways to resolve it, I suggest the following:
function deleteItem(e) {
var ul = document.getElementById('list');
ul.removeChild(li);
var foundIndex = tweets.findIndex(function (tweet) {
return tweet.id == id;
});
if (foundIndex > -1) {
tweets.splice(foundIndex, 1);
}
}
There are two issues:
If you just take the length of the array as the id you will get duplicate entries, if you delete an entry. Perhaps go to a timestamp - i just used the one you already had there but added seconds
You retrieve the value-attribute but for splice you need the index of the element. I just added the timestampt as an attribute to the button and used it for removal.
Probably not my best code but I hope it gives you the right hints.
var tweets = []
function postNewTweet() {
var today = new Date();
var date = today.getDate() + '-' + (today.getMonth() + 1) + '-' + today.getFullYear();
var time = today.getHours() + ':' + today.getMinutes() + ':' + today.getSeconds();
var id = tweets.length + 1;
var li = document.createElement('li');
var inputValue = document.getElementById('newTweet').value;
var finalValue = id + ' ' + inputValue + ' ' + date + ' ' + time;
var t = document.createTextNode(finalValue);
li.appendChild(t);
tweets.push({
id: id,
content: inputValue,
date: date + ' ' + time
});
document.getElementById('list').appendChild(li);
document.getElementById('newTweet').value = "";
console.log(tweets);
var buttonDelete = document.createElement("button");
buttonDelete.innerHTML = '<i class="far fa-trash-alt" del-date="'+date + ' ' + time +'">del</i>';
buttonDelete.onclick = deleteItem;
function deleteItem(e) {
var ul = document.getElementById('list');
ul.removeChild(li);
var list = document.getElementById('list');
list.addEventListener('click', function(e) {
var delDate = e.target.getAttribute('del-date');
let index = tweets.map((item) => item.date).indexOf(delDate);
console.log(index);
tweets.splice(index, 1);
console.log(tweets)
});
}
li.appendChild(buttonDelete);
}
<div id='post'>
<textarea maxlength="160" id='newTweet'></textarea>
<button id='postIt' onclick="postNewTweet()">Post</button>
</div>
<ul id='list'>
</ul>
As you have access to li in your delete function, you have access to all the other data too. You can use them to find out the element to remove from the tweets array.
For example, in your current code, you can use the id:
tweets.splice(id - 1, 1)
Or you can use filter with any of the data that you store in tweets.And I don't see any use for this part:
var list = document.getElementById('list');
list.addEventListener('click', function(e) {
var index = e.target.getAttribute('value');
tweets.splice(index, 1);
console.log(tweets)
});
You can just remove the tweet under the ul.removeChild

all objects in array are updating with same value while pushing the object with unique id into an array

on calling pushValue() function each time generating unique id by calling getGUID() after that assigning to objectJson.id and pushing to array but in console.log() it displays all object with same unique id.
<button onclick="pushValue()">
Click
</button>
<p id='displayjson'>
</p>
<script>
var arrayJson = [];
var objectJson = {
name: "New Widget",
sizeX: 4,
sizeY: 1,
lib: 'fsf',
id:""
};
var pushValue = function(){
objectJson.id = getGUID();
arrayJson.push(objectJson);
document.getElementById("displayjson").innerText = JSON.stringify(arrayJson);
console.log(arrayJson);
}
function getGUID() {
//DOCS : -http://guid.us/GUID/JavaScript
function S4() {
return (((1 + Math.random()) * 0x10000) | 0).toString(16).substring(1);
}
var guid = ('svg_id_' + S4() + S4() + "_" + S4() + "_4" + S4().substr(0, 3) + "_" + S4() + "_" + S4() + S4() + S4()).toLowerCase();
return guid;
}
</script>
click on this link https://jsfiddle.net/Akkikumar77/noLhzbwr/
It's happening because you push the objectJson reference to the array. So if you change the object, it changes in every occurence. To avoid this, you need to clone the object before pushing to the array with Object.assign()
arrayJson.push(Object.assign({}, objectJson));
Here is the updated fiddle.
You are changing same object each time, so you are pushing that object only (a reference) not newly created object. Make a simple factory function and you're good to go. Or clone the object.
var arrayJson = [];
var createObject = function(){
return{
name: "New Widget",
sizeX: 4,
sizeY: 1,
lib: 'fsf',
id: getGUID()
}
}
var pushValue = function(){
arrayJson.push(createObject());
document.getElementById("displayjson").innerText = JSON.stringify(arrayJson);
console.log(objectJson);
}
This is as a result of mutation.
Each time you call objectJSON.id = getGUID() you change the id value of the original objectJSON.
To stop referencing the original objectJSON object you use the concat method which makes a deep copy of it as opposed to using the push method.
Like this
arrayJson.concat([objectJSON]);
instead of
arrayJson.push(objectJson);
You were changing the object, not duplicating it or creating a new one. Here's one way to do it using most of your code:
Fiddle here
<button onclick="pushValue()">
Click
</button>
<p id='displayjson'>
</p>
<script>
var arrayJson = [];
var objectJson = {
name: "New Widget",
sizeX: 4,
sizeY: 1,
lib: 'fsf',
id:"",
};
function CreateObject(name, id){
this.name = name;
this.sizeX = 4;
this.sizeY = 1;
this.lib = 'fsf';
this.id = id;
}
var pushValue = function(){
var myNewObject = new CreateObject('someName', getGUID());
arrayJson.push(myNewObject);
document.getElementById("displayjson").innerText = JSON.stringify(arrayJson);
console.log(objectJson);
}
function getGUID() {
//DOCS : -http://guid.us/GUID/JavaScript
function S4() {
return (((1 + Math.random()) * 0x10000) | 0).toString(16).substring(1);
}
var guid = ('svg_id_' + S4() + S4() + "_" + S4() + "_4" + S4().substr(0, 3) + "_" + S4() + "_" + S4() + S4() + S4()).toLowerCase();
return guid;
}
</script>

Jquery Clone method increment name tag

Hello I am trying to add increment in my all form fields from zero to the number whenever I add new clone it assigns the next number to the name tag, I tried all the ways but no any methods works for me.
Here is my fiddle
https://jsfiddle.net/o5wam5r2/
and here is my JS code
var formItem;
$(document).ready(function() {
//Clone and remove your div instead of hiding it
formItem = $('.ScheduleextraPartTemplate').clone();
$('.ScheduleextraPartTemplate').remove();
formItem.addClass('clone clone-1');
$('#Schedulecontainer').append(formItem);
});
$(document).on('click', '#ScheduleaddRow', function() {
var cloneForm = $('.clone').last().clone();
var cloneNum = $('.clone').length;
cloneForm.removeClass('clone-'+cloneNum).addClass('clone-' + (cloneNum+1));
var date = cloneForm.find('[name="txtSchedule"]').val();
cloneForm.find('[name="txtSchedule"]').val(addOneMonth(date));
$('#Schedulecontainer').append(cloneForm);
})
function addOneMonth(date) {
var year = parseInt(date.split("-")[0]);
var month = parseInt(date.split("-")[1]) + 1;
var day = parseInt(date.split("-")[2]);
if(month > 12) {
month = month - 12;
year++
}
return year + "-" + month + "-" + day;
}
I fixed it by changing a little piece of code
var formItem;
var counter = 0;
$(document).ready(function() {
//Clone and remove your div instead of hiding it
formItem = $('.ScheduleextraPartTemplate').clone();
formItem.find('[name^=txtSchedule]')[0].name = "txtSchedule" + counter;
formItem.find('[name^=txtScheduleAmountPay]')[0].name = "txtScheduleAmountPay" + counter;
$('.ScheduleextraPartTemplate').remove();
formItem.addClass('clone clone-1');
$('#Schedulecontainer').append(formItem);
});
$(document).on('click', '#ScheduleaddRow', function() {
var lens = counter++;
var cloneForm = $('.clone').last().clone();
var cloneNum = $('.clone').length;
cloneForm.removeClass('clone-'+cloneNum).addClass('clone-' + (cloneNum+1));
var date = cloneForm.find('[name^="txtSchedule"]').val();
cloneForm.find('[name^="txtSchedule"]').val(addOneMonth(date));
cloneForm.find('[name^=txtSchedule]')[0].name = "txtSchedule" + (lens+1);
cloneForm.find('[name^=txtScheduleAmountPay]')[0].name = "txtScheduleAmountPay" + (lens+1);
$('#Schedulecontainer').append(cloneForm);
})
function addOneMonth(date) {
var d = new Date( date );
d.setMonth( d.getMonth( ) + 1 );
return d.getFullYear() + '-' + ("0" + ((d.getMonth() + 1))).slice(-2) + '-' + ("0" + (d.getDate())).slice(-2);
}

Javascript string to Guid

in javascript, what is the easiest way to convert this string
798205486e954fa880a0b366e6725f71
to GUID format like this
79820548-6e95-4fa8-80a0-b366e6725f71
this is the messy way I do it :) im looking for the cleanest way
var employeeId = shift.employee.id.substring(0, 8) + "-" + shift.employee.id.substring(8, 12)
+ "-" + shift.employee.id.substring(12, 16) + "-" + shift.employee.id.substring(16, 20) + "-" + shift.employee.id.substring(20, 32);
Cleanest way?
Shortest:
var txt = shift.employee.id;
txt.replace(/([0-z]{8})([0-z]{4})([0-z]{4})([0-z]{4})([0-z]{12})/,"$1-$2-$3-$4-$5");
//"79820548-6e95-4fa8-80a0-b366e6725f71"
or if you don't care about the acceptable characters, it can be be even shorter (and cleaner):
txt.replace(/(.{8})(.{4})(.{4})(.{4})(.{12})/,"$1-$2-$3-$4-$5"); //boom!
Some don't like using regex for everything, but I liked it.
I did it in string manipulation
var str = "798205486e954fa880a0b366e6725f71";
var parts = [];
parts.push(str.slice(0,8));
parts.push(str.slice(8,12));
parts.push(str.slice(12,16));
parts.push(str.slice(16,20));
parts.push(str.slice(20,32));
var GUID = parts.join('-');
console.log(GUID) // prints expected GUID
I did it this way because I don't like inserting characters between strings. If there is any problem tell me.
Or you could use a for loop like bellow
var str = "798205486e954fa880a0b366e6725f71";
var lengths = [8,4,4,4,12];
var parts = [];
var range = 0;
for (var i = 0; i < lengths.length; i++) {
parts.push(str.slice(range,range+lengths[i]));
range += lengths[i];
};
var GUID = parts.join('-');
console.log(GUID);
You could use an regular expression:
var rxGetGuidGroups = /(\w{8})(\w{4})(\w{4})(\w{4})(\w{12})/,
employeeId = shift.employee.id.replace(rxGetGuidGroups, '$1-$2-$3-$4-$5');
jsFiddle
Try this function, It will return string in GUID format
function getGuid(str){
return str.slice(0,8)+"-"+str.slice(8,12)+"-"+str.slice(12,16)+
"-"+str.slice(16,20)+"-"+str.slice(20,str.length+1)
}
Or you would try-
var guid = (function () {
function s4() {
return Math.floor((1 + Math.random()) * 0x10000)
.toString(16)
.substring(1);
}
return function () {
return s4() + s4() + '-' + s4() + '-' + s4() + '-' +
s4() + '-' + s4() + s4() + s4();
};
})();
Where
Your new guid be like-
var newGuid= guid();
newGuid returns- 7d4b3ef0-b5bb-5c42-2a02-80a4371babf8

Unique ID that gets a date in specific format?

I have code that will generate a random unique id.. but is there a way I can edit this code so that it grabs a date in a specific way like yyyy-mm-dd-0001. the last 4 digits I want it to add 1 each time the generateid button is clicked. so it will change to 0002. Here is the current code I have. Is there a function that can grab the date automatically?
var counter = 0000;
function Counter() {
if((document.getElementById("generateid").clicked == true)
{
Counter++
return counter;
}
}
function Month() {
var m = new Date();
var mm = m.getMonth() + 1;
if (mm < 10) {
mm = '0' + mm;
return mm;
}
}
function Year() {
var y = new Date();
var yy = y.getFullYear();
return yy;
}
function Day() {
var d = new Date();
var dd = d.getDate();
return dd;
}
//generate id
function guidGenerator() {
var theID = (Year() + "-" + Month() + "-" + Day() + "-" + Counter);
return theID;
}
function generateID() {
var TheTextBox = document.getElementById("generateidtxt");
TheTextBox.value = TheTextBox.value + guidGenerator();
document.getElementById("generateid").disabled = true;
}
You can use the following object:
var idGenerator = {
seq: 0,
generateId: function () {
this.seq++;
return (new Date()).toISOString().substring(0, 10) + '-' + ('000' + this.seq).substr(-4)
}
}
after declaration like this, try
function generateID() {
var TheTextBox = document.getElementById("generateidtxt");
TheTextBox.value = TheTextBox.value + idGenerator.generateId();
document.getElementById("generateid").disabled=true;
}
If you are asking for a way to keep track of how many times an ID is generated by all your site visitors using javascript alone then, no it is not possible without tying in some back end to keep track. However, the following code will do what you ask per visitor.
jsfiddle
var ttlIds = 0;
function guidGenerator() {
var S4 = function () {
return (((1 + Math.random()) * 0x10000) | 0).toString(16).substring(1);
}
return (S4() + S4() + S4());
}
function generateID() {
var TheTextBox = document.getElementById("generateidtxt");
TheTextBox.value = TheTextBox.value + guidGenerator().toString().toUpperCase();
//document.getElementById("generateid").disabled=true;
ttlIds++;
if(ttlIds < 10){
ttlIds_formatted = '000'+ttlIds;
}else if(ttlIds < 100){
ttlIds_formatted = '00'+ttlIds;
}else if(ttlIds < 1000){
ttlIds_formatted = '0'+ttlIds;
}
d = new Date();
var funkydate = d.getFullYear() +'-' + (d.getMonth()+1) + '-' + d.getDate() + '-' + ttlIds_formatted;
document.getElementById("funkydate").value = funkydate;
}

Categories

Resources