I need help as soon as possible.
I try have tried various way on how to arrange the output in alphabetical order but none of them seems work.
The question is asked to arrange the output in alphabetical order without changing the base code.
The base code:
function add() {
var name = document.getElementById("id-name").value;
var address = document.getElementById("id-address").value;
var content = document.getElementById("id-content").innerHTML;
document.getElementById("id-content").innerHTML = content + name + "<br/>" + address + "<hr/>";
}
Name: <input type="text" id="id-name" name="name"><br /> Address: <textarea id="id-address" name="address"></textarea><br />
<button id="id-send" onclick="javascript: add();">Send</button>
<hr>
<div id="id-content"></div>
This is the example of the output that it should display:
You could create an array and sort it
I wrapped in a form to have simpler event handling. Also no need for javascript: label on an inline event handler
const list = []; // you can get this from localStorage if you want to save across reloads
window.addEventListener("DOMContentLoaded", () => {
const content = document.getElementById("id-content"),
nameField = document.getElementById("id-name"),
addressField = document.getElementById("id-address");
const show = () => {
list.sort((a, b) => a.name.localeCompare(b.name))
content.innerHTML = list.map(({ name, address }) => `${name}<br/>${address}`).join("<hr/>");
};
document.getElementById("myForm").addEventListener("submit", e => {
e.preventDefault();
const name = nameField.value;
const address = addressField.value;
list.push({ name, address });
show();
});
});
<form id="myForm">
Name: <input type="text" id="id-name" name="name"><br /> Address: <textarea id="id-address" name="address"></textarea><br />
<button id="id-send">Send</button>
</form>
<hr>
<div id="id-content"></div>
You could keep an array of submitted data and sort the array alpabetically. This solution should work:
let listOfData = [];
function add() {
var name = document.getElementById("id-name").value;
var address = document.getElementById("id-address").value;
var content = document.getElementById("id-content").innerHTML;
listOfData.push({
personName: name,
personAddress: address
});
document.getElementById("id-content").innerHTML = "";
listOfData.sort((a, b) => a.personName.localeCompare(b.personName));
for (let person of listOfData) {
document.getElementById(
"id-content"
).innerHTML += `${person.personName} <br/> ${person.personAddress}<br/> <hr/>`;
}
}
Use this code it will work
function add() {
var name = document.getElementById("id-name").value;
var address = document.getElementById("id-address").value;
let data = document.getElementById("id-content");
let content = data.innerHTML;
content = content + name + "<br/>" + address + "<hr>";
let dt = "";
let sortArr = content.split("<hr>").sort().join().split(",");
for (let i = 1; i < sortArr.length; i++) {
dt += sortArr[i] + "<hr>";
}
data.innerHTML = dt;
}
Related
Finally found an anchor code that puts a clickable URL where I want it, however the onclick of the radio buttons writes the URL for each click.
I need the URL to replace / reset the previous selection on each radio click so only 1 URL is ever showing - i will eventually have about 30 radio buttons - each will produce a different URL.
var roomNo = ""
var phoneNo = ""
var guestPin = ""
var roomLink = ""
var createLinkNode1 = ""
var createLinkNode2 = ""
var link369 = 'https://join.meet.video.justice.gov.uk/';
var link453 = 'https://join.meet.video.justice.gov.uk/';
function H369() {
document.getElementById("roomNo").innerHTML = "CVP Room: " + "HMCTS369";
document.getElementById("phoneNo").innerHTML = "Telephone Number: " + "02920 ";
document.getElementById("guestPin").innerHTML = "Guest Pin Number: " + "4444";
document.getElementById("roomLink").innerHTML = "<b>" + "Full Clickable URL Link: " + "</b>";
createLinkNode1(link369, document.body);
function createLinkNode1(url, parent) {
const linkTextNode = document.createTextNode(url);
const linkNode = document.createElement('a');
linkNode.href = url;
linkNode.appendChild(linkTextNode);
parent.appendChild(linkNode);
}
}
function H453() {
document.getElementById("roomNo").innerHTML = "CVP Room: " + "HMCTS453";
document.getElementById("phoneNo").innerHTML = "Telephone Number: " + "02920";
document.getElementById("guestPin").innerHTML = "Guest Pin Number: " + "5555";
document.getElementById("roomLink").innerHTML = "<b>" + "Full Clickable URL Link: " + "</b>";
createLinkNode2(link453, document.body);
function createLinkNode2(url, parent) {
const linkTextNode = document.createTextNode(url);
const linkNode = document.createElement('a');
linkNode.href = url;
linkNode.appendChild(linkTextNode);
parent.appendChild(linkNode);
}
}
<html>
<body>
<input type="radio" name="CVPRoom" onclick = "H369()">HMCTS369</br>
<input type="radio" name="CVPRoom" onclick = "H453()">HMCTS453</br>
<p id="demo"></p>
<p id="demo2"></p>
<p id="demo3"></p>
<div id="roomNo"></div>
<div id="phoneNo"></div>
<div id="guestPin"></div>
<div id="roomLink"></div>
<script src="CVPScripts.js">
</script>
</body>
</html>
I had it working on my previous code version, but the anchor would put the URL at the bottom of the HTML so was useless - stupidly overwrote the code so no example to demo
I suggest you delegate and create an object to hold the values
Then you are much more DRY (Don't Repeat Yourself)
I additionally use template literals
const radioContainer = document.getElementById("radioContainer");
const linkBase = 'https://join.meet.video.justice.gov.uk/HMCTS/#/';
const emailBase = '#meet.video.justice.gov.uk';
const output = document.getElementById("output");
const rooms = {
"hmcts369": {
"telephone": "02920 376411",
"guestPin": "4444"
},
"hmcts453": {
"telephone": "02920 376400",
"guestPin": "5555"
}
};
// create the room radios
radioContainer.innerHTML = Object
.keys(rooms)
.map(key => `<label><input type="radio" name="CVPRoom" />${key.toUpperCase()}</label>`).join("<br/>");
radioContainer.addEventListener("click", function(e) { // click anywhere in the label to select and show the details
const tgt = e.target.closest("label");
if (!tgt) return
const thisRoom = tgt.textContent.trim();
const thisRoomKey = thisRoom.toLowerCase();
const details = rooms[thisRoomKey];
if (!details) {
alert(`Sorry, room ${thisRoom} not found`);
return;
}
const href = `${linkBase}?conference=${thisRoomKey}${emailBase}`; //
output.innerHTML = `<div id="roomNo">CVP Room: ${thisRoom}</div>
<div id="phoneNo">Telephone Number: ${details.telephone}</div>
<div id="guestPin>Guest Pin Number: ${details.guestPin}</div>
<div id="roomLink"><b>Full Clickable URL Link</b></div>`;
})
<div id="radioContainer"></div>
<div id="output"></div>
Note the URL is not a truly valid URL with the /#/ in the middle.
If you have a better URL, you can do
const linkBase = new URL('https://join.meet.video.justice.gov.uk/HMCTS/#/'); // invalid URL - fix it and we can use the URL API
linkBase.searchParams.set("conference", `${thisRoomKey}${emailBase}`); // set the conference parameter
const href = linkBase.toString(); // get the URL
Here is a version that does not manipulate the DOM but just changes the text and attributes
const radioContainer = document.getElementById("radioContainer");
const linkBase = 'https://join.meet.video.justice.gov.uk/HMCTS/#/';
const emailBase = '#meet.video.justice.gov.uk';
const output = document.getElementById("output");
const roomNo = document.getElementById("roomNo");
const phoneNo = document.getElementById("phoneNo");
const guestPin = document.getElementById("guestPin");
const roomLink = document.getElementById("roomLink");
const rooms = {
"hmcts369": {
"telephone": "02920 376411",
"guestPin": "4444"
},
"hmcts453": {
"telephone": "02920 376400",
"guestPin": "5555"
}
};
// create the room radios
radioContainer.innerHTML = Object
.keys(rooms)
.map(key => `<label><input type="radio" name="CVPRoom" />${key.toUpperCase()}</label>`).join("<br/>");
radioContainer.addEventListener("click", function(e) { // click anywhere in the label to select and show the details
const tgt = e.target.closest("label");
if (!tgt) return
output.hidden = true;
const thisRoom = tgt.textContent.trim();
const thisRoomKey = thisRoom.toLowerCase();
const details = rooms[thisRoomKey];
if (!details) {
alert(`Sorry, room ${thisRoom} not found`);
return;
}
const href = `${linkBase}?conference=${thisRoomKey}${emailBase}`; //
roomNo.textContent = thisRoom;
phoneNo.textContent = details.telephone;
guestPin.textContent = details.guestPin;
roomLink.href = href;
output.hidden = false;
})
<div id="radioContainer"></div>
<div id="output" hidden>
<div>CVP Room: <span id="roomNo"></span></div>
<div>Telephone Number: <span id="phoneNo"></span></div>
<div>Guest Pin Number: <span id="guestPin"></span></div>
<div><a id="roomLink" href=""><b>Full Clickable URL Link</b></a></div>
</div>
The best way is create a object with the data, and not repeat functions that do the same thing. Create one function for each functionality and pass the data from the object to the functions.
Check this:
let conferences = [
{
id: "369",
input: {
name : "CVPRoom",
value: "HMCTS369"
},
info: {
room: "HMCTS369",
phone: "02920 376411",
pin: "4444",
link: "https://join.meet.video.justice.gov.uk/HMCTS/#/?conference=hmcts369#meet.video.justice.gov.uk"
}
},
{
id: "453",
input: {
name : "CVPRoom",
value: "HMCTS453"
},
info: {
room: "HMCTS453",
phone: "02920 376400",
pin: "5555"
}
}
]
let divInputs = document.querySelector('#inputs')
let divData = document.querySelector('#data')
conferences.forEach( c => {
let label = document.createElement('label')
let radio = document.createElement('input')
radio.setAttribute('type', 'radio')
radio.value = c.input.value
radio.name = c.input.name
radio.id = c.id
radio.addEventListener( 'change', e=>{
changeData( c )
} )
label.appendChild(radio)
label.appendChild( document.createTextNode( c.input.value ) )
divInputs.appendChild( label )
} )
function changeData( conferenceData ){
while( divData.hasChildNodes() ){
divData.removeChild( divData.firstChild )
}
let divRoom = document.createElement('div')
divRoom.appendChild(document.createTextNode(`CVP Room: ${conferenceData.info.room}`))
divData.appendChild( divRoom )
let divPhone = document.createElement('div')
divPhone.appendChild(document.createTextNode(`Telephone Number: ${conferenceData.info.phone}`))
divData.appendChild( divPhone )
let divPin = document.createElement('div')
divPin.appendChild(document.createTextNode(`Guest Pin Number: ${conferenceData.info.pin}`))
divData.appendChild( divPin )
let aLink = document.createElement('a')
aLink.appendChild(document.createTextNode('Full Clickable Link'))
aLink.href = `https://join.meet.video.justice.gov.uk/HMCTS/#/?conference=${conferenceData.info.room.toLowerCase()}#meet.video.justice.gov.uk`
divData.appendChild( aLink )
}
<html>
<body>
<div id="inputs">
</div>
<div id="data">
</div>
</body>
</html>
I'm currently working with form builder and am running into following error
fb.actions.getData is not a function
Whenever I'm initiating the form builder from existing form data and then trying to save the form again afterwards (e.g. after making changes to the form.)
This is the code I'm using to build the (multi-page) form.
const result = <?php echo $questiondata->json_question;?>;
let length = result.length;
var stepLen = length;
var res = result;
for (let i = 1; i <= stepLen; i++) {
var tabId = "step-" + i;
const $newPageTemplate = $(document.getElementById("new-page"));
const $newPage = $newPageTemplate.clone().attr("id", tabId).addClass("fb-editor");
const $newTab = $('#add-page-tab').clone().removeAttr("id");
const $tabLink = $("a", $newTab).attr("href", "#" + tabId).text("Step " + i);
$newPage.insertBefore($newPageTemplate);
$newTab.insertBefore('#add-page-tab');
$fbPages.tabs("refresh");
$fbPages.tabs("option", "active", 0);
fbInstances.push($newPage.formBuilder());
$(tabId).formBuilder().promise.then(function(fb) {
let formadata = res[i - 1];
fb.actions.setData(formadata);
});
}
//--------json form data update-------------
$(document.getElementById("save-all")).click(function() {
let allData = fbInstances.map((fb) => {
console.log(fb.actions.getData()); // This line is throwing the error
return fb.actions.getData(); // This line is throwing the error
});
saveFormData(allData);
});
I'm not sure I have enough information. Would you please include the HTML?
I see you used this technique: https://formbuilder.online/docs/formBuilder/promise/
Have you tried this technique?
https://formbuilder.online/docs/formBuilder/actions/getData/
It's possible the data isn't available yet and the setData() call isn't working, but I don't think that's the case because you used technique #1. If the data isn't available yet, you could try this first and then do your setData() call afterwards:
var formBuilder = $(fbEditor).formBuilder();
All formbuilder code is here. i am sharing all code like view page code , render code and save code. render 4 tabbed different json form but after save getting only last array 4 time.
view page code
<form method="POST" id="form-builder-pages" action="{{
url('question/updatequestion', $questiondata->id) }}">
#csrf
<div class="col-md-12 text-center"><button id="save-all" type="button"
class="btn btn-primary">Save</button></div>
<input type="hidden" name="formid" value="{{ $questiondata->id }}">
<textarea id="jsondata" name="json_question" style="display:none"></textarea>
<div class="col-md-12 p-3">
<input id="form_title" type="text" class="form-control #error('form_title') is-invalid #enderror" name="form_title" readonly value="{{ $questiondata->form_title }}" required autocomplete="form_title" autofocus>
<span id="msg"></span>
</div>
<ul id="tabs">
<!-- <li>Page 1</li> -->
<li id="add-page-tab">+ Page</li>
</ul>
<div id="page-1" class="fb-editor"></div>
<div id="new-page"></div>
</form>
enter image description here
Get result here
[[{"type":"textarea","required":true,"label":"message","className":"form-control","name":"textarea-1655308420860-0","access":false,"subtype":"textarea"}],[{"type":"textarea","required":true,"label":"message","className":"form-control","name":"textarea-1655308420860-0","access":false,"subtype":"textarea"}],[{"type":"textarea","required":true,"label":"message","className":"form-control","name":"textarea-1655308420860-0","access":false,"subtype":"textarea"}]]
<script>
jQuery(($) => {
"use strict";
var $fbPages = $(document.getElementById("form-builder-pages"));
var addPageTab = document.getElementById("add-page-tab");
var fbInstances = [];
$fbPages.tabs({
beforeActivate: function (event, ui) {
if (ui.newPanel.selector === "#new-page") {
return false;
}
}
});
addPageTab.addEventListener(
"click",
(click) => {
const tabCount = document.getElementById("tabs").children.length;
const tabId = "page-" + tabCount.toString();
const $newPageTemplate = document.getElementById("new-page");
const $newTabTemplate = document.getElementById("add-page-tab");
const $newPage = $newPageTemplate.cloneNode(true);
$newPage.setAttribute("id", tabId);
$newPage.classList.add("fb-editor");
const $newTab = $newTabTemplate.cloneNode(true);
$newTab.removeAttribute("id");
const $tabLink = $newTab.querySelector("a");
$tabLink.setAttribute("href", "#" + tabId);
$tabLink.innerText = "Page " + tabCount;
$newPageTemplate.parentElement.insertBefore($newPage, $newPageTemplate);
$newTabTemplate.parentElement.insertBefore($newTab, $newTabTemplate);
$fbPages.tabs("refresh");
$fbPages.tabs("option", "active", tabCount - 1);
fbInstances.push($($newPage).formBuilder());
},
false
);
// ----render json form data is working fine
const result = <?php echo $questiondata->json_question;?>;//json form data
let length = result.length;
var stepLen= length;
var res = result;
for (let i = 1; i <= stepLen; i++) {
var tabId = "step-" + i;
var $newPageTemplate = $(document.getElementById("new-page"));
var $newPage = $newPageTemplate.clone().attr("id",tabId).addClass("fb-editor");
var $newTab = $('#add-page-tab').clone().removeAttr("id");
var $tabLink = $("a", $newTab).attr("href", "#" + tabId).text("Step " + i);
$newPage.insertBefore($newPageTemplate);
$newTab.insertBefore('#add-page-tab');
$fbPages.tabs("refresh");
$fbPages.tabs("option", "active", 0);
let $newInstance = $newPage.formBuilder();
$newInstance.promise.then(function (fb) {
fbInstances.push(fb);
let formadata=res[i - 1];
fb.actions.setData(formadata);
});
}
//update json form array -------
$(document.getElementById("save-all")).click(function () {
const allData = fbInstances.map((fb) => {
console.log(fb.actions.getData());
return fb.actions.getData();
});
let jsondata = JSON.stringify(allData);
console.log(jsondata); // error here
});
});
</script>
console.log here
[[{"type":"textarea","required":true,"label":"message","className":"form-control","name":"textarea-1655308420860-0","access":false,"subtype":"textarea"}],[{"type":"textarea","required":true,"label":"message","className":"form-control","name":"textarea-1655308420860-0","access":false,"subtype":"textarea"}],[{"type":"textarea","required":true,"label":"message","className":"form-control","name":"textarea-1655308420860-0","access":false,"subtype":"textarea"}]]
I have this HTML code:
<label for="AccountName">Account Name:</label>
<input type="text" id="mytext">
<label for="Deposit">Deposit: </label>
<input type="text" class="deposit" id="deposit">
<button type="submit" id="createAccount" onclick="createAccount()">Create new Account</button>
<textarea name="mytextarea" id="mytextarea" cols="140" rows="20"></textarea>
...and I wrote some code in JavaScript to get values from the input fields and construct account object from it and add those objects to accountInfoList which is a list. And finally I want to update the content of mytextarea with the accountInfoList. Sample run looks like this:
The JavaScript code I wrote is:
var accountInfoList = [];
const makeCounter = function() {
let name = document.getElementById('mytext').value;
let balance = document.getElementById('deposit').value;
function createAccount(AccountName, AccountBalance) {
this.AccountName = AccountName;
this.AccountBalance = AccountBalance;
}
var account = createAccount(name, balance);
accountInfoList.push(account);
}
// document.getElementById('createAccount').onclick = createAccount;
function createAccount() {
makeCounter();
// console.log(account1);
// const account2 = makeCounter(a)
// accountInfoList.push(account1);
console.log(typeof accountInfoList)
for (var i = 0; i < accountInfoList.length; i++) {
console.log("Account Name: " + accountInfoList[i].AccountName + "Balance: " + accountInfoList[i].balance);
}
// document.getElementById('mytextarea').value = accountInfoList[0].name;
}
...which doesn't seem to be working. Any idea is appreciated.
I finally come to the solution after long hours of debugging the script:
var accountInfoList = [];
const makeCounter = function() {
let name = document.getElementById('mytext').value;
console.log(name);
let balance = document.getElementById('deposit').value;
console.log(balance);
var account = new Account(name, balance);
accountInfoList.push(account);
console.log(typeof accountInfoList);
console.log(accountInfoList.length);
}
class Account {
constructor(name, balance) {
this.name = name;
this.balance = balance;
}
}
function createAccount() {
makeCounter();
var text = "";
for (var i = 0; i < accountInfoList.length; i++) {
text += "Account name: " + accountInfoList[i].name + " " + "Balance: " + accountInfoList[i].balance + "\n";
}
document.getElementById('mytextarea').value = text;
}
I get two values as name and number from input and make an object by a constructor , then I push it to an array.
I want to append those values to my HTML file by each click from user
and also use map to show only names.
How can I do that?
please help me , this is my code < br/>
const name = document.getElementById("name");
const number = document.getElementById('number');
const container = document.getElementById("container");
const sendBtn = document.getElementById("send-btn");
const contacts = [];
function ContactMaker (name, number) {
this.name = name;
this.number = number;
}
sendBtn.addEventListener('click', () => {
const newContact = new ContactMaker(name.value, number.value);
contacts.push(newContact);
name.value ='';
number.value = '';
})
You can map through the contacts and add them to the DOM:
const name = document.getElementById("name");
const number = document.getElementById('number');
const container = document.getElementById("container");
const sendBtn = document.getElementById("send-btn");
const contacts = [];
function ContactMaker(name, number) {
this.name = name;
this.number = number;
}
const addToDOM = () => {
const contactList = contacts.map(({
name
}) => `<li>${name}</li>`).join('');
container.innerHTML = `<ul>${contactList}</ul>`;
}
sendBtn.addEventListener('click', () => {
const newContact = new ContactMaker(name.value, number.value);
contacts.push(newContact);
name.value = '';
number.value = '';
addToDOM();
})
<input id="name" type="text" />
<input id="number" type="text" />
<button id="send-btn">Send</button>
<div id="container"></div>
I am trying to delete the item but cant get why the item is not removing from the array its in last line on delete item function but the item is not getting delete from data array i splice the array but thats also not work for me if there is any better solution plz help me out
Its in deleteitem function
//Constructor for student form
var studentForm = function(iD,name,city,college,course,age){
this.id = iD;
this.name = name;
this.city = city;
this.college = college;
this.course = course;
this.age = age;
}
//all data store here as object
var data = [];
//function to submit and display form
var submitForm = function(){
//getInput data from the field
var getInput = {
name:document.querySelector('.name').value,
city:document.querySelector('.city').value,
college:document.querySelector('.college').value,
course:document.querySelector('.course').value,
age:document.querySelector('.age').value,
}
//store the data which you get previous to use that
var input = getInput;
//Create a new id
var ID;
if(data.length > 0){
ID = data[data.length - 1].id +1;
}else{
ID =1;
}
//Use the constructor and make a new data
var newForm = new studentForm(ID,input.name,input.city,input.college,input.course,input.age);
//Add the student data into the ds
data.push(newForm);
//Display the data in the Document
//html line to display data of object
var html = '<tr id="id-%roll%"><td>%id%</td><td class="tname">%name%</td><td class="tcity">%city%</td><td class="tcollege">%college%</td><td class="tcourse">%course%</td><td class="tage">%age%</td><td><button class="delbtn">Delete</button></td></tr>';
//Replace the placeHOlder With actual data
var newHtml = html;
//newHtml = "<td class=\"id-%id%\">%id%</td>".replace(/%id%/g, ID)
newHtml = newHtml.replace('%roll%',ID);
newHtml = newHtml.replace('%id%',ID);
newHtml = newHtml.replace('%name%',input.name);
newHtml = newHtml.replace('%city%',input.city);
newHtml = newHtml.replace('%college%',input.college);
newHtml = newHtml.replace('%course%',input.course);
newHtml = newHtml.replace('%age%',input.age);
//Get the element which after you wants to print the data
document.querySelector('.tablemain').insertAdjacentHTML('beforeend',newHtml);
//Clearint the fields
var fields = document.querySelectorAll('.name' + ', ' + '.city' + ', ' + '.college' + ', ' + '.course' + ', ' + '.age');
//Convert it into array
var fieldsArr = Array.prototype.slice.call(fields);
//Loopthrough all fields to clear the fields
fieldsArr.forEach(function(current,index,array){current.value = '';});
fieldsArr[0].focus();
//Deleting element
// parent element class = table id = id delete button class =delbtn
console.log(newForm);
return newForm;
}
document.querySelector('.btn').addEventListener('click',submitForm);
//Delete section
//Deleting element
// parent element class = table id = id delete button class =delbtn
document.querySelector('.table').addEventListener('click',delItem);
function delItem(e){
var iTemId,splitID;
iTemId = e.target.parentNode.parentNode.id;
if(iTemId){
splitID = iTemId.split('-');
var ElementID = parseInt(splitID[1]);
var deleteItem = function(id){
var ids = data.map(function(cur){
return cur.id;
});
var index = ids.indexOf(id);
if(index !== -1){
data.slice(index,1);
}
};
deleteItem(ElementID);
};
};
<input type="text" placeholder="name" class="name">
<input type="text" placeholder="city" class="city">
<input type="text" placeholder="college" class="college">
<input type="text" placeholder="Course" class="course">
<input type="number" placeholder="age" class="age">
<button class="btn" value="submit">Submit</button>
<div class="table">
<table class="tablemain">
<tr class="table-heading"><th>ID</th><th>Name</th><th>City</th><th>College</th><th>Course</th><th>Age</th><th>Delete</th></tr>
</table>
</div>
Splice and Slice both are JavaScript Array functions. The splice() method returns the removed item(s) in an array while mutating the original array and slice() method returns the selected element(s) in an array, as a new array object without mutating the original array.
What you have used here is slice instead of splice. If you want to use slice, return the resulting array or replace slice with splice
if(index !== -1){
data.splice(index,1);
}
// Or
if(index !== -1){
const newData = data.slice(index,1);
}
For future questions, you'll get more responses if you can simplify your question as much as possible. The code you posted is a little tough to grok.
That being said, I think the issue is here data.slice(index,1);. Array.prototype.slice does not mutate the original array. It returns a new array. For this reason, sometimes folks use it to create copies of an array to avoid mutation with something like const arrCopy = originalArr.slice();.
I think you are looking for the array splice method.
Hope this gets you closer. Where is data declared? I see you're doing all sorts of things to it and treating as a global var but not sure where you declare it.
I just modified delItem function
delete table row
set index to -1 (because array starts from 0)
//Constructor for student form
var studentForm = function(iD,name,city,college,course,age){
this.id = iD;
this.name = name;
this.city = city;
this.college = college;
this.course = course;
this.age = age;
}
//all data store here as object
var data = [];
//function to submit and display form
var submitForm = function(){
//getInput data from the field
var getInput = {
name:document.querySelector('.name').value,
city:document.querySelector('.city').value,
college:document.querySelector('.college').value,
course:document.querySelector('.course').value,
age:document.querySelector('.age').value,
}
//store the data which you get previous to use that
var input = getInput;
//Create a new id
var ID;
if(data.length > 0){
ID = data[data.length - 1].id +1;
}else{
ID =1;
}
//Use the constructor and make a new data
var newForm = new studentForm(ID,input.name,input.city,input.college,input.course,input.age);
//Add the student data into the ds
data.push(newForm);
//Display the data in the Document
//html line to display data of object
var html = '<tr id="id-%roll%"><td>%id%</td><td class="tname">%name%</td><td class="tcity">%city%</td><td class="tcollege">%college%</td><td class="tcourse">%course%</td><td class="tage">%age%</td><td><button class="delbtn">Delete</button></td></tr>';
//Replace the placeHOlder With actual data
var newHtml = html;
//newHtml = "<td class=\"id-%id%\">%id%</td>".replace(/%id%/g, ID)
newHtml = newHtml.replace('%roll%',ID);
newHtml = newHtml.replace('%id%',ID);
newHtml = newHtml.replace('%name%',input.name);
newHtml = newHtml.replace('%city%',input.city);
newHtml = newHtml.replace('%college%',input.college);
newHtml = newHtml.replace('%course%',input.course);
newHtml = newHtml.replace('%age%',input.age);
//Get the element which after you wants to print the data
document.querySelector('.tablemain').insertAdjacentHTML('beforeend',newHtml);
//Clearint the fields
var fields = document.querySelectorAll('.name' + ', ' + '.city' + ', ' + '.college' + ', ' + '.course' + ', ' + '.age');
//Convert it into array
var fieldsArr = Array.prototype.slice.call(fields);
//Loopthrough all fields to clear the fields
fieldsArr.forEach(function(current,index,array){current.value = '';});
fieldsArr[0].focus();
//Deleting element
// parent element class = table id = id delete button class =delbtn
console.log(newForm);
return newForm;
}
document.querySelector('.btn').addEventListener('click',submitForm);
//Delete section
//Deleting element
// parent element class = table id = id delete button class =delbtn
document.querySelector('.table').addEventListener('click',delItem);
function delItem(e){
// Delete table row
document.getElementById(e.target.parentNode.parentNode.id).remove();
var iTemId,splitID;
iTemId = e.target.parentNode.parentNode.id;
if(iTemId){
splitID = iTemId.split('-');
var ElementID = parseInt(splitID[1]);
var deleteItem = function(id){
var ids = data.map(function(cur){
return cur.id;
});
var index = ids.indexOf(id);
if(index !== -1){
// delete array in data (array start with 0)
data = data.slice(index-1,1);
}
};
deleteItem(ElementID);
};
};
<input type="text" placeholder="name" class="name">
<input type="text" placeholder="city" class="city">
<input type="text" placeholder="college" class="college">
<input type="text" placeholder="Course" class="course">
<input type="number" placeholder="age" class="age">
<button class="btn" value="submit">Submit</button>
<div class="table">
<table class="tablemain">
<tr class="table-heading"><th>ID</th><th>Name</th><th>City</th><th>College</th><th>Course</th><th>Age</th><th>Delete</th></tr>
</table>
</div>