So i need to display the user id that has been generated in javascript but i have problem to display it on textbox.
here's the javascript coding:
function AddDetails(){
var button = document.getElementById('button');
button.addEventListener('click', SaveDetails, false);
}
function SaveDetails(){
var CreateuserID = generateuserID();
document.getElementById('userID').value = CreateuserID;
var name = document.getElementById('userName').value;
var occupation = document.getElementById('userOccupation').value;
sessionStorage.setItem(name, occupation);
display();
var name = document.getElementById('userName').value = "";
var occupation = document.getElementById('userOccupation').value = "";
}
function display(){
var output = document.getElementById('output');
output.innerHTML = "";
for(var i=0;i<sessionStorage.length;i++)
{
var name = sessionStorage.key(i);
var occupation = sessionStorage.getItem(name);
output.innerHTML += name+"|"+occupation+"<br>";
}
}
function generateuserID()
{
var userIDnum = 1;
userIDnum++;
}
window.addEventListener('load', AddDetails, false);
This is the HTML code:
<!DOCTYPE HTML>
<html>
<head>
<link rel="stylesheet" href="Style.css">
<script src="script.js"></script>
</head>
<br>
<body>
<section id="input">
<form>
ID : <input type="number" readonly id="userID" value="">
Name : <input type="text" id="userName" >
Occupation : <input type="text" id="userOccupation">
<input type="button" id="button" value="Add">
</form>
</section>
<br>
<br>
Sort by: <select name="sort">
<option value ="userID">userID</option>
<option value ="userID">userName</option>
<option value ="userID">userOccupation</option>
</select>
<br>
<section id="output">
</section
</body>
</html>
Please help me i have been doing this for days and cant think of solution. I tried using ECMAScript and it wont work either. I'm still new and lack of knowledge.
Your generateuserID() method doesn't return anything. Even if your returned userIDnum everyone's user id will be 2. Do you realize that JavaScript just runs in the browser? None of the variables will exist between different users.
There are many mistakes in your sample. You don't need sessionStorage just for static content. Here is the working codepen [ https://codepen.io/vivekamin/pen/gQMRPx ] .I have created for you from your code. Please check it out. Here is the code. I have used createElement just for sake of working example. However, if you have many elements to append you can use createDocumentFragment which is more efficient. I am just adding the last data to HTML, output element in form of paragraph text
HTML:
<body>
<section id="input">
<form>
ID : <input type="number" readonly id="userID" value="">
Name : <input type="text" id="userName" >
Occupation : <input type="text" id="userOccupation">
<input type="button" id="button" value="Add">
</form>
</section>
<br>
<br>
Sort by: <select name="sort" id ="sortBy">
<option value ="userID">userID</option>
<option value ="name">userName</option>
<option value ="occupation">userOccupation</option>
</select>
<br>
<section id="output">
</section
</body>
JS Code:
let counter = 1;
let data = [];
function AddDetails(){
var button = document.getElementById('button');
button.addEventListener('click', SaveDetails, false);
let sortBy = document.getElementById('sortBy');
sortBy.addEventListener('change', SortAndDisplay, false);
document.getElementById('userID').value = counter;
}
function SortAndDisplay(){
console.log("Sorting", document.getElementById('sortBy').value);
let sortBy = document.getElementById('sortBy').value;
if(sortBy === "userID"){
data.sort(function (a, b) {
return a.id - b.id;
});
}
else{
sortByNameOrOccupation(sortBy);
}
console.log(data);
displayAfterSort();
}
function SaveDetails(){
let name = document.getElementById('userName');
let occupation = document.getElementById('userOccupation');
data.push({id: counter, name: name.value, occupation: occupation.value });
console.log(data);
counter++;
document.getElementById('userID').value = counter;
name.value='';
occupation.value ='';
let outputSection = document.getElementById('output');
let outputData = data[data.length - 1];
let newP = document.createElement('p');
newP.textContent = outputData['id'] + " " + outputData['name'] + " "+outputData['occupation'];
outputSection.appendChild(newP);
}
function sortByNameOrOccupation(attribute){
data.sort(function(a, b) {
var nameA = a[attribute].toUpperCase(); // ignore upper and lowercase
var nameB = b[attribute].toUpperCase(); // ignore upper and lowercase
if (nameA < nameB) {
return -1;
}
if (nameA > nameB) {
return 1;
}
// names must be equal
return 0;
});
}
function displayAfterSort(){
let outputSection = document.getElementById('output');
outputSection.innerHTML = '';
let fragment = document.createDocumentFragment();
data.forEach(function(d) {
let p = document.createElement('p');
p.textContent = d['id'] + " " + d['name'] + " "+d['occupation'];
fragment.appendChild(p);
});
outputSection.appendChild(fragment);
}
window.addEventListener('load', AddDetails, false);
To set the value of the textbox. Do:
$('#//ID of the textbox').val(CreateuserID)
This is assuming that 'CreateuserID' is a string or int
EDIT: Your CreateuserID function will need to return a value.
Related
This question already has answers here:
Why does jQuery or a DOM method such as getElementById not find the element?
(6 answers)
Closed 1 year ago.
So no matter what I change if I input anything in the textarea it is not reading anything from the form.
I needed it to be able to have input and not just change the default message of the textarea. If there is any other error in my code please help me by correcting me. And this is only purely html and javascript.
function manage(txt) {
var input = document.getElementById('replace');
if (txt.value != '') {
input.disabled = false;
}
else {
input.disabled = true;
}
}
function findReplace() {
var str = document.getElementById("message").innerHTML;
var find = document.getElementById("find").value;
var replace = document.getElementById("replace").value;
var res = str.replaceAll(find, replace);
document.getElementById("message").innerHTML = res;
}
function Counter(str) {
var str = document.getElementById("message").innerHTML;
var msg = str.split(" ");
var element = document.getElementById("replace").value;
var count = 0;
for ( var i = 0; i < msg.length; i++)
{
if (element == msg[i])
{
count++;
i++;
} else
{
i++;
}
document.getElementById("demo").innerHTML = "Number of replacement: " + count;
}
}
<!-- Message -->
<label for="message">Message: </label><br>
<textarea required type = "text" id="message" name = "message" rows="3" cols="20" method = "post">Hello testing</textarea><br>
<!-- Finding box -->
<label for="find">Find: </label><br>
<input type="text" id="find" name="find" onkeyup = "manage(this)"><br>
<!-- Replace box -->
<label for="replace">Replace with: </label><br>
<input disabled type="text" id="replace" name="replace">
<!--Submit button -->
<input type="button" value="find and replace" onclick ="findReplace(); Counter();">
Try value instead of innerHTML for textarea control.
function findReplace() {
var str = document.getElementById("message").value; //use value here
console.log(str)
var find = document.getElementById("find").value;
var replace = document.getElementById("replace").value;
var res = str.replaceAll(find, replace);
document.getElementById("message").value = res; //use value here
}
Note: There is no element with id demo in the HTML which is used in your JS.
Demo:
function manage(txt) {
var input = document.getElementById('replace');
if (txt.value != '') {
input.disabled = false;
}
else {
input.disabled = true;
}
}
function findReplace() {
var str = document.getElementById("message").value;
console.log(str)
var find = document.getElementById("find").value;
var replace = document.getElementById("replace").value;
var res = str.replaceAll(find, replace);
document.getElementById("message").value = res;
}
function Counter(str) {
var str = document.getElementById("message").innerHTML;
var msg = str.split(" ");
var element = document.getElementById("replace").value;
var count = 0;
for ( var i = 0; i < msg.length; i++)
{
if (element == msg[i])
{
count++;
i++;
} else
{
i++;
}
//document.getElementById("demo").innerHTML = "Number of replacement: " + count;
}
}
<!-- Message -->
<label for="message">Message: </label><br>
<textarea required type = "text" id="message" name = "message" rows="3" cols="20" method = "post">Hello testing</textarea><br>
<!-- Finding box -->
<label for="find">Find: </label><br>
<input type="text" id="find" name="find" onkeyup = "manage(this)"><br>
<!-- Replace box -->
<label for="replace">Replace with: </label><br>
<input disabled type="text" id="replace" name="replace">
<!--Submit button -->
<input type="button" value="find and replace" onclick ="findReplace(); Counter();">
I'm trying to code a small application that lets you dynamically add text strings in an unordered list, but the problem is the strings I pass as input do not show up after clicking the "Invia/Send" button. I have tried with a few solutions from other questions, but none of them worked. Any ideas?
<html>
<head>
<title>Promemoria esercizi</title>
</head>
<body>
<ul id="paragraphList">
</ul>
<form id="paragraphForm">
<br></br>
<textarea id="insertParagraph" rows="5" cols="100"></textarea>
<label>Inserisci il paragrafo:
<input type="radio" id="insertType" name="InsertType" value="last">In fondo
<input type="radio" id="insertType" name="InsertType" value="before">Dietro il paragrafo
<select id="beforeParagraph"></select><br></br>
</label>
<button id="add" onclick="addParagraph(paragraphArray)">Inserisci</button><br></br>
</form>
<script>
var paragraphArray = [];
document.getElementById("paragraphList").innerHTML = paragraphArray;
function addParagraph(paragraphArray){
var text = document.getElementById("insertParagraph").value;
var radio = document.getElementById("insertType");
var selectedInsertType = "";
var ul = document.getElementById("paragraphList");
var sel = document.getElementById("beforeParagraph");
var selectedBeforeParagraph = sel.options[sel.selectedIndex].value;
for(i = 0; i < radio.length; i++){
if(radio[i].checked){
selectedInsertType = radio[i].value;
}
}
if(selectedInsertType = "last"){
paragraphArray.push(text);
}else if(selectedInsertType = "before"){
paragraphArray.splice((selectedBeforeParagraph-1), 0, text);
}
var newChoice = document.createElement("option");
newChoice.value = paragraphArray.length.toString();
newChoice.text = paragraphArray.length.toString();
for(i = 0; i < paragraphArray.length; i++){
var li = document.createElement("li");
li.innerHTML = paragraphArray[i];
}
document.getElementById("paragraphList").innerHTML = paragraphArray;
}
</script>
</body>
</html>
There were a few issues:
A common problem people run into with the button tag is by default, it has a type of 'submit' which will submit the form. There are a few ways to disable this, my preferred method is to set the type as button.
Another issue is you don't have any content in the select box, which was causing an error trying to get the value of a select box with no options that can be selected.
I updated your radios, to use querySelectorAll and look for :checked that way you don't need to create an if statement.
I also removed the paragraphArray from addParagraph() since it is a global variable.
<html>
<head>
<title>Promemoria esercizi</title>
</head>
<body>
<ul id="paragraphList">
</ul>
<form id="paragraphForm">
<br></br>
<textarea id="insertParagraph" rows="5" cols="100"></textarea>
<label>Inserisci il paragrafo:
<input type="radio" id="insertType" name="InsertType" value="last">In fondo
<input type="radio" id="insertType" name="InsertType" value="before">Dietro il paragrafo
<select id="beforeParagraph"></select><br></br>
</label>
<button type="button" id="add" onclick="addParagraph()">Inserisci</button><br></br>
</form>
<script>
var paragraphArray = [];
document.getElementById("paragraphList").innerHTML = paragraphArray;
function addParagraph(){
var text = document.getElementById("insertParagraph").value;
var radio = document.querySelectorAll("#insertType:checked");
var selectedInsertType = "";
var ul = document.getElementById("paragraphList");
var sel = document.querySelector("#beforeParagraph");
var selectedBeforeParagraph = (sel.selectedIndex > -1) ? sel.options[sel.selectedIndex].value : "";
for(i = 0; i < radio.length; i++){
selectedInsertType = radio[i].value;
}
if(selectedInsertType = "last"){
paragraphArray.push(text);
}else if(selectedInsertType = "before"){
paragraphArray.splice((selectedBeforeParagraph-1), 0, text);
}
var newChoice = document.createElement("option");
newChoice.value = paragraphArray.length.toString();
newChoice.text = paragraphArray.length.toString();
for(i = 0; i < paragraphArray.length; i++){
var li = document.createElement("li");
li.innerHTML = paragraphArray[i];
}
document.getElementById("paragraphList").innerHTML = paragraphArray;
}
</script>
</body>
</html>
I am learning jquery. I have an HTML & jquery code. I want to show the button only if my answer is true on input value otherwise it should stay hidden. Also, I want to show the questions on my screen. See, if anyone can help. thanks
var random = Math.random();
var range = random * 2;
var incrment = range + 1;
var floor = Math.floor(incrment);
var ques1 = "what comes after 4?";
var ans = 5;
$(document).ready(function() {
$("#bot").keyup(function() {
if (ans == floor) {
$("#pete").css("display", "block");
} else {
$("#pete").css("display", "none");
}
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<p>Name: <input type="text" id="bot" required="required"></p>
<input type="submit" id="pete" style="display:none;">
use show() and hide() functions and i dont know when your floor and ans will be equal.
var random = Math.random();
var range = random * 2 ;
var incrment = range + 1;
var floor = Math.floor(incrment);
var ans = 5;
floor=6; //for testing i gave
$("#bot").keyup(function() {
if (ans == $('#bot').val())
$("#pete").show();
else
$("#pete").hide();
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<label>What number comes after 4?</label>
<input type="number" id="bot" required="required"/>
<input type="submit" id="pete" style="display:none;" >
Here is the complete code for your requirement .
Use innerHTML to priint the question in the screen and .value to obtain the value entered by user ..
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="X-UA-Compatible" content="IE=edge;chrome=1" />
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
</head>
<body>
<p id="question"></p>
<p>Name: <input type="text" id="bot" required="required"></p>
<input type="submit" id="pete" style="display:none;" >
</body>
</html>
<script type="text/javascript">
var random = Math.random();
var range = random * 2 ;
var incrment = range + 1;
var floor = Math.floor(incrment);
var ques1 = "what comes after 4?";
document.getElementById('question').innerHTML = ques1;
var ans = 5;
$("#bot").keyup(function() {
var ansFromInput = document.getElementById('bot').value;
console.log("ans , floor" , ans , ansFromInput);
if (ans == ansFromInput) {
$("#pete").css("display", "block");
}
else {
$("#pete").css("display", "none");
}
});
</script>
You can do something like that ,
Here using class to hide the button, we can add and remove class to achieve that.
var random = Math.random();
var range = random * 2;
var incrment = range + 1;
var floor = Math.floor(incrment);
var ques1 = "what comes after 4?";
var floor = 5;
$('#ques').text(ques1);
$(document).ready(function() {
$('#bot').on('input',function(e){
if ($('#bot').val() == floor) {
$("#pete").removeClass('hide');
} else {
$("#pete").addClass('hide');
}
});
});
.hide{
display:none;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<label> <p id="ques"> </p> </label>
<p><input type="text" id="bot" required="required"></p>
<input type="submit" id="pete" class="hide">
window.onload = Soldier;
function Soldier(allegiance,armor,weapon){
this.allegiance = allegiance;
this.armor = armor;
this.weapon = weapon;
}
document.getElementById("soldier").innerHTML =
var soldier1 = new Soldier("Theosis", true, "Sword");
alert(soldier1.allegiance);
<DOCTYPE HTML>
<html>
<head>
<script src = "objscript.js"> </script>
</head>
<body>
Allegiance: <input type ="text" id = "allegiance"><br/><br/>
Armor: <input type ="text" id = "armor"><br/><br/>
Weapon(s): <input type ="text" id = "weapon"><br/><br/>
<input type = "button" id="button" value = "Submit"><br/>
<p id = "soldier"> </p>
</body>
</html>
i know how to make objects but i dont know how to make the user input the data of the object and print onto the screen.
window.onload = submit;
function Soldier(allegiance,armor,weapon){
this.allegiance = "allegiance";
this.armor = armor;
this.weapon = weapon;
var soldier1 = document.getElementById("atext").value;
document.getElementById("soldier").innerHTML = " allegiance: " + soldier.allegiance + " <br/> " + " armor: " + soldier.armor + "</br>" + "Weapon(s): "+ soldier.weapon;
}
function submit(){
var submitButton = document.getElementById("button");
submitButton.onclick = Soldier;
}
<DOCTYPE HTML>
<html>
<head>
<script src = "objscript.js"> </script>
</head>
<body>
Allegiance: <input type ="text" id = "atext"><br/><br/>
Armor: <input type ="text" id = "armor"><br/><br/>
Weapon(s): <input type ="text" id = "weapon"><br/><br/>
<input type = "button" id="button" value = "Submit"><br/>
<p id = "soldier"> </p>
</body>
</html>
I dont think im allowed to use push. im just suppose to make new soldiers by the user typing it in. i made the code a little better. now just need it to actually print
The solution:
HTML
Allegiance: <input type ="text" id = "allegiance"><br/><br/>
Armor: <input type ="text" id = "armor"><br/><br/>
Weapon(s): <input type ="text" id = "weapon"><br/><br/>
<input type = "button" id="button" onclick="hire()" value = "Submit"><br/>
<p id="output"></p>
JS
var soldiers = [];
function Soldier(allegiance, armor, weapon){
this.allegiance = allegiance;
this.armor = armor;
this.weapon = weapon;
this.doReport = function () {
return this.armor + ' and ' + this.weapon;
}
}
function doReport() {
output = "";
for(var i = 0; i < soldiers.length; i++) {
output += (i + 1) + ") " + soldiers[i].doReport() + "; ";
}
document.getElementById("output").innerHTML = output;
}
function hire() {
var soldier = new Soldier(
document.getElementById("allegiance").value,
document.getElementById("armor").value,
document.getElementById("weapon").value
);
soldiers.push(soldier);
doReport();
}
I added function hire() and bound it with submit button. A new soldier object is being pushed into the list of soldiers. Also I added doReport() method to Soldier and common doReport() function which makes a general report of all soldiers in the list. Right now, I call doReport() in the end of each hire(), but you can do it by clicking on some another button for example.
Basically I'm trying to create a function in which it takes parameters, the times table required, and the values at which it should start and end. The function is to return a formatted string that can be displayed in the output area.
The rest of the code will get the three values from the textboxes and call the multiplication table function.
The return value will be displayed in a text area.
An example of what it should look like:
My JS currently looks like this:
function btnDisplay_onclick()
{
// get textboxes and assign to variables
var tableTextbox = document.getElementById("txtTable");
var startTextbox = document.getElementById("txtStart");
var finishTextbox = document.getElementById("txtFinish");
var outputTextbox = document.getElementById("txtOutput");
var table = tableTextbox.value;
var start = startTextbox.value;
var finish = finishTextbox.value;
var output = multiply(table, start, finish);
outputTextbox.value = output;
}
function multiply(table, start, finish)
{
for
}
the HTML:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<!-- saved from url=(0014)about:internet -->
<title>Multiplication Table</title>
<script src="Lab6-MultTable.js"></script>
</head>
<body>
<form action=#>
<p><h1>Multiplication Table</h1></p>
<p>
Table Number:<input type="text" id="txtTable"><br>
Start Number:<input type="text" id="txtStart"><br>
Finish Number:<input type="text" id="txtFinish"><br>
</p>
<p>
<textarea id="txtOutput" rows="8" cols="20" readonly="readonly"></textarea>
</p>
<p>
<input type="button" value="Display Numbers" id="btnDisplay" onclick="btnDisplay_onclick()">
<input type="reset">
</p>
</form>
<noscript>This website requires JavaScript to be enabled.</noscript>
</body>
</html>
So basically I'm having trouble learning how to use Loops properly if someone would be willing to explain it to me as reading up on it I'm not able to fully understand it for whatever reason.
You could change the processing of the value a bit, like
var table = +tableTextbox.value || 0;
That converts the value to number and checks for a truthy value. If falsy, take zero as value.
For multiplication take the start and end value for the for loop and a variable for the result.
Calculate the value and add the line to the result, return the result.
function multiply(table, start, finish) {
var i, result = '';
for (i = start; i <= finish; i++) {
result += table + ' * ' + i + ' = ' + table * i + '\n';
}
return result;
}
function btnDisplay_onclick() {
// get textboxes and assign to variables
var tableTextbox = document.getElementById("txtTable");
var startTextbox = document.getElementById("txtStart");
var finishTextbox = document.getElementById("txtFinish");
var outputTextbox = document.getElementById("txtOutput");
var table = +tableTextbox.value || 0; // convert to number and
var start = +startTextbox.value || 0; // testfor truthynes or take
var finish = +finishTextbox.value || 0; // the default value of 0
var output = multiply(table, start, finish);
outputTextbox.value = output;
}
function multiply(table, start, finish) {
var i, result = '';
for (i = start; i <= finish; i++) {
result += table + ' * ' + i + ' = ' + table * i + '\n';
}
return result;
}
<form action="">
<p><h1>Multiplication Table</h1></p>
<p>
Table Number:<input type="text" id="txtTable"><br>
Start Number:<input type="text" id="txtStart"><br>
Finish Number:<input type="text" id="txtFinish"><br>
</p>
<p>
<textarea id="txtOutput" rows="8" cols="20" readonly="readonly"></textarea>
</p>
<p>
<input type="button" value="Display Numbers" id="btnDisplay" onclick="btnDisplay_onclick()">
<input type="reset">
</p>
</form>
Another way is write the result inside the loop at textarea.
$("#display").on("click", function(){
multiply();
});
function multiply(){
var table = document.getElementById("table").value
, start = document.getElementById("start").value
, finish = document.getElementById("finish").value
, text = document.getElementById("result");
text.value = '';
for ( var i = start ; i <= finish ; i++ ){
text.value += table + " * " + i + " = " + (table * i) + "\n";
}
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<form>
<div id="parameters">
Table number: <input id="table" type="number" />
<br/>
Start number: <input id="start" type"number" />
<br/>
Finish number: <input id="finish" type"number" />
<div>
<textarea id="result" rows="8" cols="20" readonly="readonly"></textarea>
</text>
<br/><br/>
<button id="display" /> Display numbers
<button type="reset" /> Reset
</form>