URL is produced each radio click, how to stop - javascript

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>

Related

How to arrange the output in alphabetical order in javascript?

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;
}

How Can I append my array of objects in an HTML file?

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>

Keep Todo Results after browser refreshing

I created a todo app to add and remove tasks on the page.
however i would like to keep todo results when browser refreshed .
Is that possible to make this like storing data on db or any storage to save these results?
any idea to make this to save data ??
Now I posted the complete code hereee! because i cant posted code here before
let menu = document.querySelector(".bs");
let btn1 = document.querySelector(".btn");
let btn2 = document.querySelector(".btn3");
let irp = document.querySelector(".date");
let inp = document.querySelector(".input");
let bsd = document.querySelector(".sss");
let brs = document.querySelector(".marker");
let addBr = () => {
btn1.addEventListener("click", addBr);
let br = document.createElement("DIV");
let dd = document.createElement("H1");
dd.innerHTML = (inp.value);
br.className = "red";
var bn = document.createElement("H1");
bn.innerHTML = (irp.value);
menu.appendChild(br);
br.appendChild(dd);
br.appendChild(bn);
if( inp.value == "") {
br.remove();
}
else {
menu.appendChild(br);
}
if( irp.value == "") {
dd.innerHTML = "Albenis";
}
else {
menu.appendChild(br);
}
let ttt = document.createElement("BUTTON");
ttt.className = "marker";
ttt.innerHTML = "Remove";
br.appendChild(ttt);
// This is the important change. Part of creating the .ttt element
// is setting up its event listeners!
ttt.addEventListener('click', () => br.remove());
};
btn1.addEventListener("click", addBr);
// Call `addBr` once to add the initial element
addBr();
<html>
<body>
<div class="bs">
<input type="text" class="input">
<input type="date" class="date">
<button class="btn">
Add
</button>
</div>
</body>
</html>
TL;DR: use localStorage to read the items at page load and write the items when they change, like in the final version
To keep your todo entries, you need to store it in a Database. This can be either a local database in the website like localStorage. Or you need to build a backend which is connected to a Database and send and load the Data from there.
localStorage example:
const items = [{ name: "My Todo" }, { name: "My Todo 2" }];
const setItems = () => {
localStorage.setItem("items", JSON.stringify(items));
};
const getItems = () => {
return JSON.parse(localStorage.getItem("items"));
};
Including your code:
const getItems = () => {
return JSON.parse(localStorage.getItem("items"));
};
const items = getItems() || [];
const setItems = () => {
localStorage.setItem("items", JSON.stringify(items));
};
let addBr = (item) => {
let br = document.createElement("DIV");
let dd = document.createElement("H1");
dd.innerHTML = (item ? item.name : inp.value);
br.className = "red";
var bn = document.createElement("H1");
bn.innerHTML = (item ? item.name : irp.value);
if (!item) {
items.push({ name: inp.value });
setItems();
}
menu.appendChild(br);
br.appendChild(dd);
br.appendChild(bn);
if( inp.value == "") {
br.remove();
}
else {
menu.appendChild(br);
}
if( irp.value == "") {
dd.innerHTML = "Albenis";
}
else {
menu.appendChild(br);
}
let ttt = document.createElement("BUTTON");
ttt.className = "marker";
ttt.innerHTML = "Remove";
br.appendChild(ttt);
// This is the important change. Part of creating the .ttt element
// is setting up its event listeners!
ttt.addEventListener('click', () => br.remove());
};
for (const item of items) {
addBr(item);
}
btn1.addEventListener("click", () => addBr());

im trying to learn JavaScript, how can i make a certain section of doc.data clickable a new link

I have this code and I want the geolocation to be able to open a new window that directs to the data that it stores example: it only shows as text in (geolocation:https://www.google.com/maps/place/7.9911209,125.1280968)
here is my code :
const emergencyList = document.querySelector('#emergency-list');
const form = document.querySelector('#add-form');
function renderEmergencyList(doc) {
let li = document.createElement('li');
let name = document.createElement('span');
let accidenttype = document.createElement('span');
let geoloc = document.createElement('a');
let cross = document.createElement('div');
li.setAttribute('data-id', doc.id);
name.textContent = "Name: " + doc.data().user.fullname;
accidenttype.textContent = "Accident Type: " + doc.data().accident_type;
geoloc.textContent = "Geo Location: " + doc.data().geo_point;
cross.textContent = 'x';
li.appendChild(name);
li.appendChild(accidenttype);
li.appendChild(geoloc);
li.appendChild(cross);
emergencyList.appendChild(li);
// deleting data
geoloc.addEventListener('click', function() {
window.open(geo_point);
})
cross.addEventListener('click', (e) => {
e.stopPropagation();
let id = e.target.parentElement.getAttribute('data-id');
db.collection('Emergency Message').doc(id).delete()
})
}
<div id="content" class="content">
<a ul id="emergency-list" onclick="changeLink()">
Geolocation
</ul>
</div>
Here is the output, I want the geolocation to be clickable into new window that refers to the link
Name: undefined
Accident Type: it stores
Geo Location: https://www.google.com/maps/place/7.9911209,125.1280968 * it only shows as text in *

Effective solution to map names with groups

I have some staff names. Each staff can be in different groups. Say staff names are N1, N2, and N3, and group names are G1, and G2.
I need to show in a webpage which staff belongs which group (sorting by groups). E.g. G1 contains N1 and N2.
Also I need to show (when another button is clicked) for each staff what are the groups they belongs to. E.g. N1 belongs to G1 and G2.
What is the effective way to do this in a webpage?
I have create an object with staffname as key and groupsArray as value;
Others must be self-explanatory; Hope this helps
let staffsArray = ["N1","N2","N3"];
staffs = [{
"N1" : ["G1","G2","G3"]
},{
"N2" : ["G1"]
},
{
"N3" : ["G3"]
},
{
"N4" : ["G2","G3"]
}]
window.onload = appendStaffsToDropDown();
function appendStaffsToDropDown() {
staffsArray.map((staffName) => {
let staffNameDiv = document.createElement("option");
let x = document.createElement("OPTION");
x.setAttribute("value", staffName);
let t = document.createTextNode(staffName);
x.appendChild(t);
document.getElementById("staffDropDown").appendChild(x)
});
displayStaffDetails();
}
function displayStaffDetails() {
staffsArray.map((staffName) => {
staffs.map((staffObject) => {
if(staffObject[staffName] != undefined) {
let parentDiv = document.getElementById('staffDetails');
let staffNameDiv = document.createElement("div");
let staffNameContent = document.createTextNode("staffName :" + staffName);
staffNameDiv.appendChild(staffNameContent);
parentDiv.appendChild(staffNameDiv)
let staffGroupDiv = document.createElement("div");
let staffGroupContent = document.createTextNode("StaffGroup :" + staffObject[staffName]);
staffGroupDiv.appendChild(staffGroupContent);
parentDiv.appendChild(staffGroupDiv)
}
});
});
}
document.getElementById("staffDropDown").onchange = function () {
let staffName = document.getElementById("staffDropDown").value;
var filteredDetails = document.getElementById("filteredDetails");
while (filteredDetails.firstChild) {
filteredDetails.removeChild(filteredDetails.firstChild);
}
staffs.map((staffObject) => {
if(staffObject[staffName] != undefined) {
let parentDiv = document.getElementById('filteredDetails');
let staffNameDiv = document.createElement("div");
let staffNameContent = document.createTextNode("staffName :" + staffName);
staffNameDiv.appendChild(staffNameContent);
parentDiv.appendChild(staffNameDiv)
let staffGroupDiv = document.createElement("div");
let staffGroupContent = document.createTextNode("StaffGroup :" + staffObject[staffName]);
staffGroupDiv.appendChild(staffGroupContent);
parentDiv.appendChild(staffGroupDiv)
document.getElementById("staffDetails").style.display = 'none';
}
});
}
<div id="staffDetails">
</div>
<select id="staffDropDown">
<option>Select Staffs</option>
</select>
<button>
Filter groups
</button>
<div id="filteredDetails">
</div>

Categories