Trying to add an option to select with append, and nothing happens - javascript

My code has two sections: a section to input new items, and a section to interact with them. I'm trying to update the dropdown list every time a new item is added with jQuery, but my current method does nothing. By nothing, I mean that the dropdown list would remain empty. I've tried previous answers to this question, but none worked. (I'm pretty new to Javascript, so me just being a noob is completely possible).
Here's the html:
<!DOCTYPE html>
<head>
<script src = "https://ajax.googleapis.com/ajax/libs/jquery/1.12.0/jquery.min.js"></script>
<link rel = "stylesheet" type = "text/css" href = "deletion.css"></link>
<script src = 'chemical.js'></script>
</head>
<body>
<form id = "newChemicalForm">
<p id = newChemicalText> Submit new chemicals here: </p>
<input type = "text" id = "newChemicalInput" onfocus = "this.select()" placeholder = "Enter new chemical here"/>
<button id = "newChemicalButton" onclick = "addChemical()" > Submit </button>
</form>
<form id = "newUsageForm">
<p id= "newUsageText"> Name your chemical and a usage amount. Check if the usage is daily. </p>
<select id = "chemicalDropdown">
</select>
<input type = "text" id = "newUsage" placeholder = "Ex: 250"/>
<input type = "checkbox" id = 'dailyCheckbox'/>
<p id = "dateText"> Enter the end date below: </p>
<input type = "date" id = "dateInput"/>
<button id = "newUsageButton" onclick = "addUsage()"> Submit </button>
</form>
</body>
And the Javascript:
chemicals = [];
function addChemical() {
var chemical = new Chemical();
chemicals.push(chemical);
$('#chemicalDropdown').append('<option value = "' + chemical.name + '"> ' + chemical.name + '</option> \n');
}
function Chemical() {
this.name = $('#newChemicalInput').val();
this.amount = 0;
this.usages = [];
}

There are a couple of things going on. First of all, When you press the submit button it tries to submit the first form. Second: It seems like the onclick event is not binding to the method which should add the item to the dropdownlist.
I've updated a couple of things:
Added $(document).ready(...); as it is best practice.
I've removed the inline onclick and bind the click event via jQuery.
JSFiddle here...
<form id = "newChemicalForm">
<p id = newChemicalText> Submit new chemicals here: </p>
<input type = "text" id = "newChemicalInput" onfocus = "this.select()" placeholder = "Enter new chemical here"/>
<button type="button" id = "newChemicalButton" > Submit </button>
</form>
<form id = "newUsageForm">
<p id= "newUsageText"> Name your chemical and a usage amount. Check if the usage is daily. </p>
<select id = "chemicalDropdown">
</select>
<input type = "text" id = "newUsage" placeholder = "Ex: 250"/>
<input type = "checkbox" id = 'dailyCheckbox'/>
<p id = "dateText"> Enter the end date below: </p>
<input type = "date" id = "dateInput"/>
<button id = "newUsageButton" onclick = "addUsage()"> Submit </button>
</form>
and the JS:
$(document).ready(function(){
var chemicals = [];
$("#newChemicalButton").on("click",function(){
addChemical();
});
function addChemical() {
var chemical = new Chemical();
chemicals.push(chemical);
$('#chemicalDropdown').append("<option value=" + chemical.name + ">" + chemical.name + "</option>");
}
function Chemical() {
this.name = $('#newChemicalInput').val();
this.amount = 0;
this.usages = [];
}
});

Possible the "\n" behind the append code make this not working. Try to remove it.

Related

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>

How to add info while copying from multiple fields using javascript?

How can I add JavaScript to a single button as to copy text to the clipboard from multiple HTML inputareas including fixed text, while inserting a line break between each field?
To give you a better idea, it's simply a webpage that will allow us at work to take very repetitive notes that we always write (same points) made of 10 points, and with a click it'll copy the fields and the text that refers to the input in a form that is ready to be pasted anywhere.
<!DOCTYPE html>
<head>
<title>Repeater</title>
</head>
<body>
<button id = "button" onclick = "myFunction()">CLICK ME!</button>
<input class = "text" name = "text" type = "text" id = "textone">
<input class = "text" name = "textone" type = "text" id = "texttwo">
<input class = "text" name = "texttwo" type = "text" id = "textthree">
<input class = "text" name = "textthree" type = "text" id = "textfour">
<input class = "text" name = "textfour" type = "text" id = "textfive">
<script>
var total;
function myFunction(){
var inputarray = document.getElementByClass("text);
for(var i = 0;i < inputarray.length; i++){\
var now = inputarray[i].value;
total = total + now;
total = tatal + "____________________________________________________________________________"
}
total.select();
document.execCommand("Copy");
}
</script>
</body>
</html>
Try this

Javascript Html Event handling

When I use this code, I am unable to get it to display the data upon clicking the display button. The code is supposed to save the input upon clicking the next button and display the array upon clicking display and clear the array when clicking clear. How do I go about resolving this?
Whenever I click the buttons nothing happens. I want to display the array inside the text area.
<html>
<head>
<script language = "javascript">
var full_name;
var dob;
var gender;
var memberList= new Array();
function saveMember() {
// getElementById may only be used to get one item at a time
// store the .value in the variable
full_name = document.getElementById('full_name').value;
dob = document.getElementById('dob').value;
gender = document.getElementById('gender').value;
// add the values to the array
// (when storing the contents of a variable, use the variable name without quotes)
memberList.push(full_name, dob, gender);
}
function displayMembers() {
var str = " ";
var listLength = memberList.length;
// append all the elements in the array into a single string
for(var i = 0; i < listLength; i+=3) {
str += memberList[i]+", "+memberList[i+1]+", "+memberList[i+2]+"\n";
}
// Replace the contents of the textarea with the value in str
document.getElementById("textBox").value = str;
}
function clearList() {
memberList = [];
}
</script>
<title>INTERNET TECHNOLOGIES CLUB MEMBER LIST </title>
</head>
<body>
<form name = "memberForm">
<h1>
INTERNET TECHNOLOGIES CLUB MEMBER LIST
</h1>
Full Name: <input type = "text" id = "full_name" value = ""/>
Date of Birth: <input type = "text" id ="dob" value = ""/>
<br>
Gender: <input type = "text" id = "gender" value = ""/>
<br>
<textarea id = "textBox" rows = "10" cols = "70">
</textarea>
<br>
<input type = "button" value = "NEXT" onclick ="saveMember()"></button>
<input type = "button" value = "DISPLAY" onclick ="displayMembers()">
</button>
<input type = "button" value = "CLEAR" onclick ="clearList()"></button>
</form>
</body>
</html>
your code is working..remove </button> in your html
I thing you expecting like this: declare the array like var memberList= [];.If you click the clear button Array was empty and textarea also empty.If you need only empty with array.remove document.getElementById("textBox").value=""; in clearlist()
var full_name;
var dob;
var gender;
var full_name;
var memberList= [];
function saveMember() {
// getElementById may only be used to get one item at a time
// store the .value in the variable
full_name = document.getElementById('full_name').value;
dob = document.getElementById('dob').value;
gender = document.getElementById('gender').value;
// add the values to the array
// (when storing the contents of a variable, use the variable name without quotes)
memberList.push(full_name, dob, gender);
}
function displayMembers() {
var str = " ";
var listLength = memberList.length;
// append all the elements in the array into a single string
for(var i = 0; i < listLength; i+=3) {
str += memberList[i]+", "+memberList[i+1]+", "+memberList[i+2]+"\n";
}
document.getElementById("textBox").value = str;
}
function clearList() {
memberList = [];
document.getElementById("textBox").value="";
}
<form name = "memberForm">
<h1>
INTERNET TECHNOLOGIES CLUB MEMBER LIST
</h1>
Full Name: <input type = "text" id = "full_name" value = ""/>
Date of Birth: <input type = "text" id ="dob" value = ""/>
<br>
Gender: <input type = "text" id = "gender" value = ""/>
<br>
<textarea id = "textBox" rows = "10" cols = "70">
</textarea>
<br>
<input type = "button" value = "NEXT" onclick ="saveMember()">
<input type = "button" value = "DISPLAY" onclick ="displayMembers()">
<input type = "button" value = "CLEAR" onclick ="clearList()">
</form>
you have written "</button>" as closing tag, which is incorrect syntax for input tag.
<input type = "button" value = "NEXT" onclick ="saveMember()"></button>
<input type = "button" value = "DISPLAY" onclick ="displayMembers()"></button>
<input type = "button" value = "CLEAR" onclick ="clearList()"></button>
replace this with the following and your code will work fine.
<input type = "button" value = "NEXT" onclick ="saveMember()"/>
<input type = "button" value = "DISPLAY" onclick ="displayMembers()"/>
<input type = "button" value = "CLEAR" onclick ="clearList()"/>
also change these functions for proper functioning
function saveMember() {
full_name = document.getElementById('full_name').value;
dob = document.getElementById('dob').value;
gender = document.getElementById('gender').value;
memberList.push(full_name, dob, gender);
document.getElementById('full_name').value = "";
document.getElementById('dob').value = "";
document.getElementById('gender').value = "";
}
function clearList() {
memberList = [];
document.getElementById("textBox").value = str;
}

Using the required attribute on a password input

I'm trying to set a password input as required in JavaScript.
I have learnt from this post how to do it but it doesn't seem to work with my password input.
<div class = "login">
<input type = "password" class = "enterPassword">
<button class = "submit">Submit</button>
</div>
var p = document.querySelector(".enterPassword");
p.required = true;
p.style.backgroundColor = "gray";
var s = document.querySelector(".submit");
s.addEventListener("click", clickHandler.bind(p));
function clickHandler() {
console.log("Password: " + this.value);
}
jsfiddle
Although I do,
var p = document.querySelector(".enterPassword");
p.required = true;
as you can see, there is no required popup when a user fails to enter a password. Does anyone know why not?
Wrap the elements in a form
<form>
<input type = "password" class = "enterPassword">
<button class = "submit">Submit</button>
</form>
You can also check it without using form
document.querySelector(".enterPassword").validity.valid
this will return a Boolean value , but you wont see the error pop up
JSFIDDLE

Change display property onfocus/onblur

I've looked up a few other questions on the site, but am still at a loss. I wanted to use Javascript (no JQuery) to take the form below:
<!doctype html>
<html>
<head>
<meta charset = "UTF-8"/>
<title>Account Sign-Up</title>
</head>
<body>
<h1>Profile Sign-Up</h1>
<fieldset>
<p>
<p><label for = "first_name">First Name: </label>
<input type = "text" id = "first_name" onfocus = "javascript:showText(1)"/>
<div id = "div1" style = "display:none">Enter your first name</div>
<p><label for = "last_name">Last Name: </label>
<input type = "text" id = "last_name" onfocus = "showText(2)"/>
<div id = "div2" style = "display:none">Enter your last name</div>
<p><label for = "email">E-Mail: </label>
<input type = "text" id = "email" onfocus = "showText(3)"/>
<div id = "div3" style = "display:none">Enter E-Mail</div>
<p><label for = "username">Username: </label>
<input type = "text" id = "username" onfocus = "showText(4)"/>
<div id = "div4" style = "display:none">Enter your desired screen name</div>
<p><label for = "password">Password: </label>
<input type = "password" id = "password" onfocus = "showText(5)"/>
<div id = "div5" style = "display:none">Enter the password you will use to log into your account in the future</div>
<p><label for = "retype_password">Retype your password again: </label>
<input type = "password" id = "retype_password" onfocus = "showText(6)"/>
<div id = "div6" style = "display:none">Type your password again</div>
<p><button name = "submit" type = "button" id = "submit">Submit</button>
</p>
</fieldset>
<script src = "Q10.js"></script>
</body>
</html>
and apply the following script to display some hidden text whenever the text boxes gain focus. I don't wish to go beyond the scope of what is described. So no, I can't use pop-up tooltips or text in a single div element in a footer, etc. I'm also unconcerned with data injections or the vulnerability/security of the code, as I am not using it for anything practical.
var enableBtn = function () {
document.getElementById("submit").disabled = false;
};
//function enables submit button
var disableBtn = function () {
document.getElementById("submit").disabled = true;
};
//disables submit button
var checkInput = function () {
if (document.getElementById("password").value.length > 0 && document.getElementById("username").value.length > 0 && document.getElementById("password").value === document.getElementById("retype_password").value) {
enableBtn();
}
else {
disableBtn();
}
};
var showText = function (numb) {
document.getElementById("div" + numb).style = "display:inline";
};
var hideText = function(numb) {
document.getElementById("div" + numb).style = "display:none";
};
document.onfocus = checkInput
//if password and username have an input- and retype password is the same as password, button is usable. If not, it's disabled.
document.getElementById("retype_password").oninput = checkInput;
document.getElementById("password").oninput = checkInput
//document.getElementById("password").onclick = function() {alert(document.getElementById("password").value.length)};
//
I'm currently running into a hiccup because I can't get the events to run scripts on focus, and don't know where else to turn. Please help ><
I'm not sure whether this is the way you want it, check the snippet. If not i will close down this answer. what i did is to add/change some code in showText(). and i think it would be better to show those divs you used on hiding texts to span(or <p>)tag as well. i added css for hiding texts class named description. you can remove other codes that you made which is not useful.
var enableBtn = function () {
document.getElementById("submit").disabled = false;
};
//function enables submit button
var disableBtn = function () {
document.getElementById("submit").disabled = true;
};
//disables submit button
var checkInput = function () {
if (document.getElementById("password").value.length > 0 && document.getElementById("username").value.length > 0 && document.getElementById("password").value === document.getElementById("retype_password").value) {
enableBtn();
}
else {
disableBtn();
}
};
var showText = function(numb) {
var desc = document.getElementsByClassName("description");
for (var i = 0; i < desc.length; i++) {
desc[i].style.display ="none";
}
document.getElementById("div" + numb).style.display = "inline";
};
var hideText = function(numb) {
document.getElementById("div" + numb).style = "display:none";
};
document.onfocus = checkInput
//if password and username have an input- and retype password is the same as password, button is usable. If not, it's disabled.
document.getElementById("retype_password").oninput = checkInput;
document.getElementById("password").oninput = checkInput
//document.getElementById("password").onclick = function() {alert(document.getElementById("password").value.length)};
.description:before {
content: '*';
}
.description {
display: none;
color: red;
}
<h1>Profile Sign-Up</h1>
<fieldset>
<p>
<p><label for = "first_name">First Name: </label>
<input type = "text" id = "first_name" onfocus = "javascript:showText(1)"/>
<span id="div1" class="description">Enter your first name</span>
<p><label for = "last_name">Last Name: </label>
<input type = "text" id = "last_name" onfocus = "showText(2)"/>
<span id="div2" class="description">Enter your last name</span>
<p><label for = "email">E-Mail: </label>
<input type = "text" id = "email" onfocus = "showText(3)"/>
<span id="div3" class="description">Enter E-Mail</span>
<p><label for = "username">Username: </label>
<input type = "text" id = "username" onfocus = "showText(4)"/>
<span id="div4" class="description">Enter your desired screen name</span>
<p><label for = "password">Password: </label>
<input type = "password" id = "password" onfocus = "showText(5)"/>
<span id="div5" class="description">Enter the password you will use to log into your account in the future</span>
<p><label for = "retype_password">Retype your password again: </label>
<input type = "password" id = "retype_password" onfocus = "showText(6)"/>
<span id="div6" class="description">Type your password again</span>
<p><button name = "submit" type = "button" id = "submit">Submit</button>
</p>
</fieldset>
<!-- <script src = "Q10.js"></script> -->
It should work fine but there could be possible Problems:
1.If you are running this on JSFiddle then you can try. window.showText. Working fiddle: https://jsfiddle.net/24sck8rs/5/
window.showText = function (numb) {
document.getElementById("div" + numb).style = "display:inline";
};
2.Possible cause of hoisting. I have declared function variable at the top and removed var. Working fiddle: https://jsfiddle.net/24sck8rs/6/
3.Declare your script in head before function call

Categories