I need to be able to append to a list (it's a leaderboard, but that's not relevant) by submitting through a form and appending to an ordered list using jquery. When I press submit nothing happens other than the button being pressed. Where am I going wrong?
HTML:
<main>
<ol class="playerList">
<li>Profit - 12,565</li>
<li>carpe - 11,423</li>
<li>Fate - 11,003</li>
<li>Fleta - 10,931</li>
<li>Fury - 10,704</li>
<li>Gesture - 10,601</li>
<li>Choihyobin - 10,012</li>
<li>MekO - 9,879</li>
<li>Birdring - 9,850</li>
<li>Mano - 9,766</li>
</ol>
</main>
<footer>
<form id="submissionForm">
<label id="nameLabel" for="pName"><u>Player name:</u></label>
<input id="pName" type="text" placeholder="Enter player name...">
<label for="pElims"><u>Elimination Count:</u></label>
<input id="pElims" type="text" placeholder="Enter elimination count...">
<input id="submitBtn" type="submit">
</form>
</footer>
JQuery:
$(document).ready(function() {
$("#submissionForm").on('submit', function(event){
event.preventDefault();
error = false;
$(".error").hide();
var playerName = $("#pName").var();
var elimCount = $("#pElim").var();
var newItem = (playerName + " - "+ elimCount);
$('.playerList').append('<li>'+ newItem + '</li>');
return false;
});
});
.var() is not a valid way to get an input element's value.
Also, the id on the elim count does not match the id on the HTML element.
var playerName = $("#pName").var();
var elimCount = $("#pElim").var();
It should be:
var playerName = $("#pName").val();
var elimCount = $("#pElims").val();
Related
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>
So, i'm trying to make a code that after submiting 3 notes it can calculate the average and the maximun note, but when trying to pass that data from my javascript function to a html paragraph the page just refreshes and doesn't show the result.
function calculateAverage(){
var maths = document.getElementById('nMaths').value;
var language = document.getElementById('nLanguage').value;
var history = document.getElementById('nHistory').value;
var sumNotes = parseFloat(maths) + parseFloat(language) + parseFloat(history);
var average = sumNotes / 3;
var result = "Your average is " + average;
document.getElementById('average').innerHTML = result;
}
<form id = "form" method="POST" action="notes.html">
<div>
<label> Enter maths note: </label>
<input id = "nMaths">
</div>
<div>
<label> Enter language note: </label>
<input id = "nLanguage">
</div>
<div>
<label> Enter history note: </label>
<input id = "nHistory" type="numer">
</div>
<button onclick="calculateAverage()"> Calculate average </button>
<button onclick="calculateBestNote()"> Calculate your best note </button>
</form>
<div>
<p id = "average" name = "average"> Your average is: </p>
<p id = "bestNote" name = "bestNote"> Your best note is: </p>
</div>
var result = "Your average is " + average;
document.getElementById('average').innerHTML = result;
}
The HTML part contains a textarea with a label.The user has to enter text and the form should be submitted and refreshed for the user to enter text again for say 5 more times. How can I do this using Javascript?
This is the html code:
<form name="myform" method="post">
<div class="form-group col-sm-5">
<label for="ques"><p id="p1">Question:</p></label>
<textarea class="form-control" rows="5" id="ques"></textarea>
</div>
</form>
<button type="button" class="btn" id="sub" onclick="func()">Next</button>
The javascript code:
var x=1;
document.getElementById("p1").innerHTML="Question"+x;
function func()
{
var frm = document.getElementsByName('myform')[0];
frm.submit();
frm.reset();
return false;
}
Here are two methods you can use. Both of these require you to add a submit button to your form, like this:
<form name="myform" method="post">
<div class="form-group col-sm-5">
<label for="ques"><p id="p1">Question:</p></label>
<textarea class="form-control" rows="5" id="ques"></textarea>
</div>
<!-- add this button -->
<input type="submit" value="Submit" class="btn">
</form>
<!-- no need for a <button> out here! -->
Method 1: sessionStorage
sessionStorage allows you to store data that is persistent across page reloads.
For me info, see the MDN docs on sessionStorage. This method requires no external libraries.
Note that in this method, your page is reloaded on submit.
window.onload = function() {
var myForm = document.forms.myform;
myForm.onsubmit = function(e) {
// get the submit count from sessionStorage OR default to 0
var submitCount = sessionStorage.getItem('count') || 0;
if (submitCount == 5) {
// reset count to 0 for future submissions
} else {
// increment the count
sessionStorage.setItem('count', submitCount + 1);
}
return true; // let the submission continue as normal
}
// this code runs each time the pages loads
var submitCount = sessionStorage.getItem('count') || 0;
console.log('You have submited the form ' + submitCount + ' times');
if (submitCount == 4) {
console.log("This will be the final submit! This is the part where you change the submit button text to say \"Done\", etc.");
}
};
Method 2: AJAX with jQuery
If you don't mind using jQuery, you can easily make AJAX calls to submit your form multiple times without reloading.
Note that in this example your page is not reloaded after submit.
window.onload = function() {
var myForm = document.forms.myform;
var submitCount = 0;
myForm.onsubmit = function(e) {
$.post('/some/url', $(myForm).serialize()).done(function(data) {
submitCount++;
});
console.log('You have submited the form ' + submitCount + ' times');
if (submitCount == 4) {
console.log("This will be the final submit! This is the part where you change the submit button text to say \"Done\", etc.");
}
e.preventDefault();
return false;
};
};
Hope this helps!
You shuld create an array and push the value of the textbox to the array in func().
We can create a template using a <script type="text/template>, then append it to the form each time the button is clicked.
const btn = document.getElementById('sub');
const appendNewTextArea = function() {
const formEl = document.getElementById('form');
const textareaTemplate = document.getElementById('textarea-template').innerHTML;
const wrapper = document.createElement('div');
wrapper.innerHTML = textareaTemplate;
formEl.appendChild(wrapper);
}
// Call the function to create the first textarea
appendNewTextArea();
btn.addEventListener('click', appendNewTextArea);
<form name="myform" method="post" id="form">
</form>
<button type="button" class="btn" id="sub">Next</button>
<script id="textarea-template" type="text/template">
<div class="form-group col-sm-5">
<label for="ques"><p id="p1">Question:</p></label>
<textarea class="form-control" rows="5" id="ques"></textarea>
</div>
</script>
Ok, say I have a checkbox such as this:
<input type="checkbox" value="1" class="discount_select" name="select[101132]">
...and 3 text fields like this:
<input type="text" name="start[101132]">
<input type="text" name="end[101132]">
<input type="text" name="discount[101132]">
I am running some code right now that will update the text field values if the checkbox is checked, however I'm not sure if or how you can target the correct fields as they all have different ID's.
So I basically have this code to loop through the checked boxes, but not sure how to make updates to the correct text fields:
// Get values
var discount = $('#apply_discount').val();
var start = $('#apply_start_date').val();
var end = $('#apply_end_date').val();
$('.discount_select:checked').each(function() {
// How can I target the correct fields/ID's here?
});
Try
// Get values
var discount = $('#apply_discount').val();
var start = $('#apply_start_date').val();
var end = $('#apply_end_date').val();
$('.discount_select:checked').each(function() {
var num = this.name.substring(7, this.name.length - 1);
$('input[name="start[' + num + ']"]').val(start)
$('input[name="end[' + num + ']"]').val(end)
$('input[name="discount[' + num + ']"]').val(discount)
});
Change the name and ids of your fields to make it simpler
<input type="checkbox" value="1" class="discount_select" id="101132" name="select_101132">
<input type="text" name="start_101132">
<input type="text" name="end_101132">
<input type="text" name="discount_101132">
Then:
var discount = $('#apply_discount').val();
var start = $('#apply_start_date').val();
var end = $('#apply_end_date').val();
$('.discount_select:checked').each(function() {
var select_id = this.attr("id");
$('[name=start_'+select_id+']').val(start);
$('[name=end_'+select_id+']').val(end);
$('[name=discount_'+select_id+']').val(discount);
});
I have this html:
<input type="radio" name="r1" value="v1"><input name="asd1" title="text1" id="asd1"><br>
<input type="radio" name="r2" value="v2"><input name="asd2" title="text1" id="asd2"><br>
<input type="button" name="but1">
<textarea rows=6 cols=80 name="conclus" id="idConclus">
</textarea><br><br>
Is there a way on js to fill textarea with titles and values of inputs by selecting some of them and clicking a button?
e.g.: "text1 - value1, text2 - value2" etc.
thanks for material.
mmm... Felix King, in your examples the button updates the form. and if i need to put one testfield 1, then put some text in textarea manually, and then again textfield 2 and so on? i mean, without updating the textarea?
getElementById is your friend :-)
<script>
getValues = new function() {
var myTextArea = document.getElementById('idConclus');
var radio1 = document.getElementById('asd1');
var radio2 = document.getElementById('asd2');
myTextArea.value = radio1.title + ' - ' + radio1.value + ' ,'
+ radio2.title + ' - ' + radio2.value;
}
</script>
<input type="radio" name="r1" value="v1">
<input type="text" name="asd1" title="text1" id="asd1"><br>
<input type="radio" name="r2" value="v2">
<input type="text" name="asd2" title="text1" id="asd2"><br>
<input type="button" name="but1" handler = getValues>
I suggest you read about JavaScript and forms.
Assuming you have this HTML:
<form name="data">
<input name="asd1" title="text1" id="asd1"><br>
<input name="asd2" title="text2" id="asd2"><br>
<input type="button" name="but1" value="update">
<textarea rows=6 cols=80 name="conclus" id="idConclus"></textarea>
</form>
you can do this:
var inputs = ['asd1', 'asd2'];
var form = document.data;
var button = form.but1;
var textarea = form.conclus;
button.addEventListener('click', function() {
var text = Array();
for(var i = 0, length = inputs.length; i < length; i++) {
var input = form[inputs[i]];
text.push(input.title + " - " + input.value);
}
textarea.value = text.join(' ');
}, false);
See a live example here: http://jsfiddle.net/6kbtH/
Update:
If you want to control which values are put into the textbox, I would use checkboxes, give them the same name and the name of the input as value like so:
<input type="checkbox" name="take" value="asd1"><input name="asd1" title="text1" id="asd1">
<input type="checkbox" name="take" value="asd2"><input name="asd2" title="text2" id="asd2">
Then you can loop with nearly the same code over those values:
var form = document.data;
var inputs = form.take;
var button = form.but1;
var textarea = form.conclus;
button.addEventListener('click', function() {
var text = Array();
for(var i = 0, length = inputs.length; i < length; i++) {
if(inputs[i].checked) {
var input = form[inputs[i].value];
text.push(input.title + " - " + input.value);
}
}
textarea.value = text.join(' ');
}, false);
Live example: http://jsfiddle.net/sJdqb/
Note: You have to take care of cross-browser issues regarding attaching the event listener yourself if you don't use a JavaScript library. The examples I gave will work in Firefox and WebKit-based browsers.