Not able to get the value from script in paragraph(<p></p>) - javascript

<p><input type="text" name="adcode" id="cityName"
style="border:none;color:green;"/></p>
<script>
window.onload = function() {
document.getElementById('cityName').value = GetDivElement();
}
</script>
The above code, I am not able to call the "GetDivElement" in paragraph
<p id="cityName"></p>
How to pass the GetElementId in p id??

If you want to get the GetDivElement() method's return value to the paragraph, you can do it like below:
window.onload = function() {
let getDivElement = () => {
return 'Div element data';
};
let inputbox = document.getElementById('cityInput');
let cityParagraph = document.getElementById('cityValue');
inputbox.value = cityParagraph.innerHTML = getDivElement();
}
<div>
<input id="cityInput" />
<p id="cityValue"></p>
</div>
As I understood from your later comment, if you want to get the paragraph value if the id='coimbatore' which you get from the GetDivElement() method you can do the following:
window.onload = function() {
let getDivElement = () => {
return 'coimbatore';
};
let paraId = getDivElement();
let textboxId = `${paraId}CityInput`;
let inputbox = document.getElementById(textboxId);
let cityParagraph = document.getElementById(paraId);
console.log(`Text field value is : ${inputbox.value}`);
console.log(`Paragraph value is : ${cityParagraph.innerHTML}`);
}
<div>
<input id="delhiCityInput" value="delhi input"/>
<p id="delhi">
Delhi city data
</p>
</div>
<div>
<input id="mumbaiCityInput" value="mumbai input"/>
<p id="mumbai">
Mumbai city data
</p>
</div>
<div>
<input id="coimbatoreCityInput" value="coimbatore input"/>
<p id="coimbatore">
Coimbatore city data
</p>
</div>
Couple of things you need to understand here is,
You can't set the same id for multiple html elements
If you want to get the value from a paragraph you should use innerHTML
Hope this helps.

Related

Trying to change the element style when clicking on button

I have already found a way to get what I want, but I'm trying to understand why the next code doesn't work.
If to be more precise why does the function showHideTaskDetails() doesn't seem to do what it should do (BTW leave aside its name, it's not an indication of its purpose)
I expect the following to happen:
When clicking on the button with the class "fa-solid fa-circle-chevron-down", the value of the variable hideContent change to the opposite of the current value (if it's true to become false and vice versa).
After that if the hideContent is true the variable color will be "background-color: red" so the style of all dives will change to have background with the color red.
But instead, nothing happens!
HTML
<body>
<div class="container">
<form action="">
<label for="task-headline">Task Headline</label>
<input type="text" id="task-headline">
<label for="deadline">Task Deadline</label>
<input type="date" id="deadline">
<label for="task-details">Task Details</label>
<textarea name="" id="task-details" cols="80" rows="10"></textarea>
<button id="add-task">Add Task</button>
</form>
<div class="tasks-area"></div>
</div>
</body>
JS
const headLineEl = document.getElementById("task-headline")
const deadlineEl = document.getElementById("deadline")
const taskDetailsEl = document.getElementById("task-details")
const TasksAreaEl = document.querySelector(".tasks-area")
addTaskBtn = document.getElementById("add-task")
let hideContent = true
let color = ""
showTasks()
addTaskBtn.addEventListener("click", (e) => {
e.preventDefault()
const newTask = collectTaskInfo()
saveToLs(newTask)
showTasks()
})
//get from the local storage the current tasks
function getLsData() {
let currentLsContent = JSON.parse(localStorage.getItem("tasks"))
if (currentLsContent === null) {
currentLsContent = []
}
return currentLsContent
}
//show the tasks on the dom
function showTasks() {
const array = getLsData()
let tasksContainer = []
array.map(task => {
const readyTask =
`
<div class="task-container" style=${color}>
<div class="main-basic-info">
<p> <span>Task:</span> ${task.headline} </p>
<div class="left-part">
<p> <span>Deadline:</span> ${task.deadline} </p>
<i class="fa-solid fa-circle-chevron-down" onClick="showHideTaskDetails()"></i>
</div>
</div>
<p class="details"> <span>Details:</span> ${task.details} </p>
</div>
<br>
`
tasksContainer.push(readyTask)
})
TasksAreaEl.innerHTML = tasksContainer
}
//hide unhide details
function showHideTaskDetails() {
hideContent = !hideContent
console.log(hideContent);
if (hideContent) color = "background-color: red"
// const test = document.getElementsByTagName('div')
// test.style = "background-color: red"
}
//collect task information to object
function collectTaskInfo() {
const obj = {
headline: headLineEl.value,
deadline: deadline.value,
details: taskDetailsEl.value
}
return obj
}
//update the current array in local storage with the new task
function addNewTaskToLsArray(newTask) {
const currentTaskArrayInLs = getLsData()
currentTaskArrayInLs.push(newTask)
const updatedTaskArray = currentTaskArrayInLs
return updatedTaskArray
}
//save data to local storage
function saveToLs(task) {
const arrayWithTheNewTask = addNewTaskToLsArray(task)
localStorage.setItem("tasks", JSON.stringify(arrayWithTheNewTask))
}
You showHideTasksDetails function is not re-rendering the page by itself.
You can modify it so that the showTasks function is called again when the showHideTaskDetails is called.
function showHideTaskDetails() {
hideContent = !hideContent;
console.log(hideContent);
if (hideContent) {
color = "'background-color: red'";
} else {
color = "";
}
// const test = document.getElementsByTagName('div')
// test.style = "background-color: red"
showTasks();
}
first it's onclick not onClick
Second initial value of hideContent is set to true and you're changing it to false when you're calling the showHideTaskDetails fn before if statement

How to clone or create a nested DOM node and change all its containing id values according to a current id?

I need to display some numbers, strings from a class named Student, but i can't figure it out how i can change the id from children element. I have to use JavaScript.
what i tried to do:
class Student{
static count = 0;
constructor(nume, prenume, data_nasterii, foaie_matricola){
this.IdClasa = ++Student.count;
//definirea atributelor
this.nume = nume;
this.prenume = prenume;
this.data_nasterii = data_nasterii;
this.foaie_matricola = foaie_matricola;
}
afiseazaVarsta(){
}
afiseazaNotele(){
}
calculeazaMedia(){
}
adaugaNota(nota_noua){
}
}
var Stud = [new Student("Name", "Name1", "2000.01.01", "0123123"),
new Student("Green", "Blue", "2022/12.12", "321321")];
function afisareStudenti(){
let i = 0; let bol = false;
for(let x=1; x<=Student.count; x++) {
console.log(document.getElementById("AfisareStudenti"+x)==null);
if(document.getElementById("AfisareStudenti"+x)==null)
{
i = x;
bol = true;
break;
} else {
bol = false;
}
}
if((i<=Student.count)&&(bol==true)){
for(i; i<=Student.count; i++) {
console.log("i="+i);
var div = document.querySelector('#AfisareStudenti1');
var divClone = div.cloneNode(true);
console.log(divClone);
divClone.id = 'AfisareStudenti'+(i);
div.after(divClone);
var NumeStud = document.getElementById("NumeStudent"+(i-1));
var PrenumeStud = document.getElementById("PrenumeStudent"+(i-1));
var dataNastStud = document.getElementById("intData"+(i-1));
var FoaiaMatStud = document.getElementById("FoaiaMatStud"+(i-1));
NumeStud.id = "NumeStudent"+(i);
PrenumeStud.id = "PrenumeStud"+(i);
dataNastStud.id = "intData"+(i);
FoaiaMatStud.id = "FoaiaMatStud"+(i);
}
}
}
and this is the html file(the div that i want to clone):
<!--AFISARE-->
<div id="AfisareStudenti1">
<h2> Afisare Student 1</h2>
<label>Ce student doriti sa modificati? </label>
<form>
<label>Nume:</label><br>
<input type="text" id="NumeStudent1"><br>
<label>Prenume:</label><br>
<input type="text" id="PrenumeStudent1"><br>
<label>Data Nasterii:</label><br>
<input type="date" id="intData1"><br>
<label>Foaie matricola:</label><br>
<input type="text" id="FoaiaMatStud1"><br><br>
<input class="butoane" type="submit" value="Afisare"
onclick="afisareMeniuAfisStudenti()">
</form>
</div>
the class is saved in a dynamic array (could be n object of the class) so i have to make somehow to display the information dynamic. My version changes the id from all elements with the same id (every incrementation of i, the idnumber from id is incremented also). I tried to create that div with document.createElement but is impossible(at least for me) xD . I started coding in javascript 2 days ago, so please take it slow on me :(
I think i found the problem, but it doesn't solve it. (i need to put (i-1) when calling for getting the ids). (Newbie mistake)
Having commented ...
"I have the feeling that if provided with the broader picture the audience could be of much more help since the OP could be provided back with leaner/cleaner and better maintainable approaches."
... I nevertheless hereby lately provide a template-based approach which, besides supporting the OP's id based querying of student-items, is also easier to read and to maintain.
The code provided within the example-code's main function does not just implement the usage of the template-based node-creation via template literals and DOMParser.parseFromString but also prevents the default behavior of each student-form's submit-button by making use of event-delegation.
function createStudentElement(studentId) {
const markup =
`<div class="student-item" id="AfisareStudenti${ studentId }">
<h2> Afisare Student ${ studentId }</h2>
<label>Ce student doriti sa modificati? </label>
<form>
<label>Nume:</label><br>
<input type="text" id="NumeStudent${ studentId }"><br>
<label>Prenume:</label><br>
<input type="text" id="PrenumeStudent${ studentId }"><br>
<label>Data Nasterii:</label><br>
<input type="date" id="intData${ studentId }"><br>
<label>Foaie matricola:</label><br>
<input type="text" id="FoaiaMatStud${ studentId }"><br><br>
<input
class="butoane" type="submit" value="Afisare"
onclick="afisareMeniuAfisStudenti(${ studentId })"
>
</form>
</div>`;
const doc = (new DOMParser).parseFromString(markup, 'text/html');
return doc.body.removeChild(doc.body.firstElementChild);
}
// the button click handler.
function afisareMeniuAfisStudenti(studentId) {
console.log({ studentId })
}
function main() {
const itemsRoot = document.querySelector('.student-items');
// - prevent any form-submit by making use of event-delegation.
itemsRoot.addEventListener('submit', evt => evt.preventDefault());
// - just for demonstration purpose ...
// ... create student-items from a list of student IDs.
[1, 2, 3, 4, 5].forEach(studentId =>
itemsRoot.appendChild(
createStudentElement(studentId)
)
);
}
main();
.as-console-wrapper { left: auto!important; width: 50%; min-height: 100%; }
<div class="student-items"></div>
Tom's answer above is what you want for the element id problem that you asked about.
For your code in particular, you are going to have a couple other problems:
Because the final input is type="submit", its going to reload the page by default when it is clicked. The name of the "onclick" function also needs to match the function you defined (afisareStudenti).
You have:
<input class="butoane" type="submit" value="Afisare" onclick="afisareMeniuAfisStudenti()">
Change this to:
<input class="butoane" type="submit" value="Afisare" onclick="afisareStudenti(event)">
Now, when you click that button, it will call the afisareStudenti function and pass in the "event". So if you change:
function afisareStudenti(){
let i = 0; let bol = false;
to:
function afisareStudenti(event){
event.preventDefault()
let i = 0; let bol = false;
This will correctly call your function, and prevent the "default" action of that submit button from reloading the page.
To change the id attribute of children elements, you could use Element.querySelector() on divClone.
Because if you use Document.querySelector() or Document.getElementById() you will get the first element that matches your selector (i.e.children of div#AfisareStudenti1).
let i = 2;
var div = document.querySelector('#AfisareStudenti1');
var divClone = div.cloneNode(true);
divClone.id = 'AfisareStudenti'+(i);
divClone.querySelector("h2").innerText = "Afisare Student " + i;
var NumeStud = divClone.querySelector("#NumeStudent1");
var PrenumeStud = divClone.querySelector("#PrenumeStudent1");
var dataNastStud = divClone.querySelector("#intData1");
var FoaiaMatStud = divClone.querySelector("#FoaiaMatStud1");
NumeStud.id = "NumeStudent"+(i);
PrenumeStud.id = "PrenumeStud"+(i);
dataNastStud.id = "intData"+(i);
FoaiaMatStud.id = "FoaiaMatStud"+(i);
div.after(divClone);
<div id="AfisareStudenti1">
<h2> Afisare Student 1</h2>
<label>Ce student doriti sa modificati? </label>
<form>
<label>Nume:</label><br>
<input type="text" id="NumeStudent1" /><br>
<label>Prenume:</label><br>
<input type="text" id="PrenumeStudent1" /><br>
<label>Data Nasterii:</label><br>
<input type="date" id="intData1" /><br>
<label>Foaie matricola:</label><br>
<input type="text" id="FoaiaMatStud1" /><br><br>
<input class="butoane" type="submit" value="Afisare" onclick="afisareMeniuAfisStudenti()" />
</form>
</div>

calculating from an input

I'm starting studying the DOM in javascript and I'd like to create a program which makes the sum of two numbers given on input and show it.
I'd like to know what functions should I use, and what functions it is better I didn't.
This is my (very simple) html code:
let warp = document.getElementById('warp');
let first = document.getElementById('first').value;
let one = parseInt(first);
let second = document.getElementById('second').value;
let two = parseInt(second);
let res = document.getElementById('res');
//res.addEventListener('click', calcul);
//res.onclick(calcul);
let nouveau = document.createElement('div');
nouveau.id = 'nouveau';
nouveau.textContent = "nouveau";
warp.appendChild(nouveau);
function calcul(first, second) {
console.log(one + two);
event.preventDefault();
}
<!DOCTYPE html>
</head>
<body>
<div id="warp">
<form>
<input id="first" type="number">first number</input>
<input id="second" type="number">second number</input>
<input id="res" type="submit" value="Envoyer" onclick="calcul()" />
</form>
<div>
</body>
let answerElemenet = document.createElement("h1");
// You can create a h1 element to display your answer after calculating it
document.body.appendChild(answerElemenet);
// Inside the calculate Function you get the values of input one and two
// and then you store the sum value in a variable and just change your
// answerElement to have the innerHTML value of the finalSum Variable
function calculate(){
let valueOne = parseFloat(document.getElementById('first').value);
let valueTwo = parseFloat(document.getElementById('second').value);
let finalSum = valueOne + valueTwo;
answerElemenet.innerHTML = finalSum;
}
Welcome to Stackoverflow!
I copied your answer and made some small changes. Here comes a brief description and explanation of what you could do better:
If you don't plan to change these references use const instead of let. Also try to keep input elements separated from their values. The reference to the input probably won't change but their value most certainly will.
const warp = document.getElementById('warp');
const first = document.getElementById('first');
const second = document.getElementById('second');
const res = document.getElementById('res');
When calculating input values, you usually want them as fresh as possible so instead of saving input values right at the beginning of the script, you get them when you need them, in the calcul() function.
You will also need some kind of validation. Here we try to convert the input to a number and set to zero if not possible:
function calcul() {
event.preventDefault();
const one = parseFloat(first.value) || 0;
const two = parseFloat(second.value) || 0;
console.log(one + two);
}
The preferred way of adding event handlers to DOM elements is using the event API. So to call the calcul()function you use the line you had commented:
res.addEventListener('click', calcul);
This also means you should remove the onClick attribute from the DOM. Also, input cannot have children:
<input id="first" type="number" />
<input id="second" type="number" />
<input id="res" type="submit" value="Envoyer"/>
All together looks like this:
const warp = document.getElementById('warp');
const first = document.getElementById('first');
const second = document.getElementById('second');
const res = document.getElementById('res');
function calcul() {
event.preventDefault();
const one = parseFloat(first.value) || 0;
const two = parseFloat(second.value) || 0;
console.log(one + two);
}
res.addEventListener('click', calcul);
let nouveau = document.createElement('div');
nouveau.id = 'nouveau';
nouveau.textContent = "nouveau";
warp.appendChild(nouveau);
<!DOCTYPE html>
</head>
<body>
<div id="warp">
<form>
<input id="first" type="number" />
<input id="second" type="number" />
<input id="res" type="submit" value="Envoyer"/>
</form>
<div>
</body>
Keep up the good job and never stop asking questions!
This will work. You just need to call the values based on their id in the calcul() function itself.
let warp = document.getElementById('warp');
let res = document.getElementById('res');
let nouveau = document.createElement('div');
nouveau.id = 'nouveau';
nouveau.textContent = "nouveau";
warp.appendChild(nouveau);
function calcul() {
let first = document.getElementById('first').value;
let one = parseInt(first);
let second = document.getElementById('second').value;
let two = parseInt(second);
if(isNaN(one) || isNaN(two)){
event.preventDefault();
return
}
console.log(one + two);
event.preventDefault();
}
<!DOCTYPE html>
</head>
<body>
<div id="warp">
<form>
<input id="first" type="number">first number</input>
<input id="second" type="number">second number</input>
<input id="res" type="submit" value="Envoyer" onclick="calcul()" />
</form>
<div>
</body>

Is it possible to get only the first letter of what is written in the input?

I want to get only the first letter of what is written in the input. Can help me?
<input id="texte" type="text" placeholder="type your name here" oninput="copyText('texte', 'text')">
<div id="text">first letter here</div>
<script type="text/javascript">
function copyText(texteId, text1Id) {
var data = document.getElementById(texteId).value;
document.getElementById(text1Id).innerHTML = data;
}
</script>
Yes you can split the variable data as an array:
function copyText(texteId, text1Id) {
var data = document.getElementById(texteId).value[0];
document.getElementById(text1Id).innerHTML = data;
}
<input id="texte" type="text" placeholder="type your name here" oninput="copyText('texte', 'text')">
<div id="text">first letter here</div>
Use [number] to get the value at some point.
Or you could use the slice() function:
function copyText(texteId, text1Id) {
var data = document.getElementById(texteId).value;
document.getElementById(text1Id).innerHTML = data.slice(0,1);
}
<input id="texte" type="text" placeholder="type your name here" oninput="copyText('texte', 'text')">
<div id="text">first letter here</div>
Or as suggested in the other answer charAt().
Use charAt(0) to get the first character:
function copyText(inputId,displayId) {
var data = document.getElementById(inputId).value;
var firstLetter = data.charAt(0);
document.getElementById(displayId).innerHTML = "The first letter is: " + firstLetter;
}
<label for ="texte">Type your name here</label>
<input id="texte" type="text" onkeyup="copyText('texte','text')">
<p id="text"></p>
function copyText( texteId, text1Id ) {
var d = document;
d.g = d.getElementById;
var data = d.g( texteId ).value[0];
d.g( text1Id ).innerHTML = data;
}
<input id="texte" type="text" placeholder="type your name here" oninput="copyText('texte', 'text')">
<div id="text">first letter here</div>
In JavaScript you may treat a string as if it were an array. So by specifying the zeroeth index of value, the code grabs the first letter and that becomes the content of the div with the id of "text" using that element's innerHTML property.
const input = document.querySelector('#texte');
const text = document.querySelector('#text');
// keydown and keyup are alternate events
input.addEventListener('input', function() {
text.innerHTML = this.value[0];
});

Getting value of <p> without the use of innerHTML

first of all I'm sorry if this is a long code segment however, I'm trying to make a modal window which writes the thing you wrote in my user form and asks you to confirm it. I am currently in a class to learn Javascript and I'm not allowed to use innerHTML and I must write the "Firstname:" etc dynamically (the text for firstname) and am not allowed to just write it inside the popup window. I've gotten most stuff to work but the "Firstname:" "Lastname" etc comes up as "undefined" or (as you can see the thing I tried with just the first name in this case) comes up as "null".
Hopefully someone can shed some light on this subject for me, this is the HTML:
<form action="http://voyager.lnu.se/tekinet/kurser/dtt/wp_webbteknik/process_form.php" method="POST" id="userform" target="_blank">
<p id="formQuestion1">Förnamn</p>
<div id="error1"></div>
<input type="text" name="firstName" id="test"/>
<p id="formQuestion2">Efternamn</p>
<div id="error2"></div>
<input type="text" name="lastName" />
<p id="formQuestion3">Postnummer</p>
<div id="error3"></div>
<input type="text" name="postCode" id="codeText"/>
<p id="formQuestion4">E-post</p>
<div id="error4"></div>
<input type="text" name="eMail" />
<br />
<br />
<label id="model" class="formQuestion" for="priceModel">Prismodell</label>
<br />
<select name="Type" id="priceModel">
<option value="Låg" selected>Låg</option>
<option value="Medel">Medel</option>
<option value="Hög">Hög</option>
</select>
<br />
<br />
<br />
<input id="sendButton" type="submit" value="Genomför Köp" />
</form>
And here is the segment for the modal window (Javascript)
function popup(backgroundDiv) {
var popForm = document.getElementById("userform");
var myDiv = document.createElement("div");
myDiv.className = "popupWindow";
var priceModel = document.getElementById("priceModel");
// Knappar
var newButton = document.createElement("button");
var newerButton = document.createElement("button");
newButton.setAttribute("value", "Skicka");
newButton.innerHTML = "Skicka"; // Here I actually use innerHTML because I don't know
newerButton.innerHTML = "Stäng"; // any other way to set the text inside the button
newButton.className = "popupButton";
newerButton.className = "popupButton";
newButton.setAttribute("id", "Skicka");
newerButton.setAttribute("id", "Avbryt");
myDiv.appendChild(newButton);
myDiv.appendChild(newerButton);
// Information
var h1 = document.createElement("h1");
h1.setAttribute("id", "popuph1");
var h1Text = document.createTextNode("Vänligen kontrollera dina uppgifter");
var text = document.getElementById("formQuestion1");
var writeFname = text.nodeValue + popForm.elements.firstName.value;
var writeLname = document.getElementById("formQuestion2").value + popForm.elements.lastName.value;
var writeCode = document.getElementById("formQuestion3").value + popForm.elements.postCode.value;
var writeMail = document.getElementById("formQuestion4").value + popForm.elements.eMail.value;
var writePlan = document.getElementById("model").value + priceModel.value;
var p1 = document.createTextNode(writeFname);
var p2 = document.createTextNode(writeLname);
var p3 = document.createTextNode(writeCode);
var p4 = document.createTextNode(writeMail);
var p5 = document.createTextNode(writePlan);
h1.appendChild(h1Text);
myDiv.appendChild(h1);
myDiv.appendChild(p1);
myDiv.appendChild(document.createElement('br'));
myDiv.appendChild(p2);
myDiv.appendChild(document.createElement('br'));
myDiv.appendChild(p3);
myDiv.appendChild(document.createElement('br'));
myDiv.appendChild(p4);
myDiv.appendChild(document.createElement('br'));
myDiv.appendChild(p5);
document.body.appendChild(myDiv);
newButton.onclick = function () {
document.body.removeChild(myDiv);
document.body.removeChild(backgroundDiv);
return true;
};
If you don't want to use innerHTML then you can use those options, suppose you want value from this node <p id="formQuestion1">Förnamn</p>
Then your code would be
var dom = document.getElementById('formQuestion1');
1) var res = dom.innerText;
OR
2) var res = dom.textContent;
OR
3) var res = dom.firstChild.nodeValue;

Categories