how to create an object with user input javascript - javascript

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.

Related

Generate user id using javascript and display it in textbox

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.

how to validate URL in dynamically added textbox

how to check URL is correct or not when i will enter into dynamically added textbox .
here t3 is given as id of input tag but that is works only for first dynamically added textbox not for others.
how to validate another URL present into next dynamically added textbox ?
<script type="text/javascript">
function GetDynamicTextBox(value){
return '<Label> Enter the URL : </label>' +
'<input name = "habits" type="text" id = "t3" value = "' + value + '" />' +
' <input type="button" value="Remove" onclick = "RemoveTextBox(this)" /><br><br>'
}
function AddTextBox() {
var div = document.createElement('DIV');
div.innerHTML = GetDynamicTextBox("");
document.getElementById("TextBoxContainer").appendChild(div);
}
function RemoveTextBox(div) {
document.getElementById("TextBoxContainer").removeChild(div.parentNode);
}
function RecreateDynamicTextboxes() {
var values = eval('<%=Values%>');
if (values != null) {
var html = "";
for (var i = 0; i < values.length; i++) {
html += "<div>" + GetDynamicTextBox(values[i]) + "</div>";
}
document.getElementById("TextBoxContainer").innerHTML = html;
}
}
window.onload = RecreateDynamicTextboxes;
</script>
<html>
<head>
<title>T-SUMM</title>
<script type="text/javascript">
function check()
{
if (document.getElementById('t1').value==""
|| document.getElementById('t1').value==undefined)
{
alert ("Please Enter a Query");
return false;
}
var regex = /(http|https):\/\/(\w+:{0,1}\w*)?(\S+)(:[0-9]+)?(\/|\/([\w#!:.?+=&%!\-\/]))?/;
if(!regex .test(document.getElementById('t2').value)||!regex .test(document.getElementById('t3').value))
{
alert("Please enter valid URL.");
return false;
}
return true;
}
</script>
</head>
<body>
<center>
<form method="Post" action="./result.jsp">
<table>
<br><br><Label> Enter a Query : </label>
<input name='habits' id='t1'> <br><br>
<Label> Enter the URL : </label>
<input name='habits' id='t2'>
<input id="btnAdd" type="button" value="add another URL" onclick="AddTextBox()" /><br><br>
<div id="TextBoxContainer">
<!--Textboxes will be added here -->
</div>
<input type="submit" name="submit" onclick="return check();">
</table>
</form>
</body>
</html>
HTML - index.html
<html>
<head>
<title>T-SUMM</title>
<script type="text/javascript" src="script.js"></script>
<script type="text/javascript">
function check()
{
if (document.getElementById('t1').value==""
|| document.getElementById('t1').value==undefined)
{
alert ("Please Enter a Query");
return false;
}
var regex = /(http|https):\/\/(\w+:{0,1}\w*)?(\S+)(:[0-9]+)?(\/|\/([\w#!:.?+=&%!\-\/]))?/;
var boxes = document.getElementsByTagName('input');
for(i = 0; i < boxes.length; i++) {
if(boxes[i].type == "text" && boxes[i].className==="urls" && !regex.test(boxes[i].value)) {
alert("Please enter valid URL. Error in Text Box "+boxes[i].value);
return false;
}
}
return true;
}
</script>
</head>
<body>
<center>
<form method="Post" action="./result.jsp">
<table>
<br><br><Label> Enter a Query : </label>
<input name='habits' id='t1'> <br><br>
<Label> Enter the URL : </label>
<input name='habits' class="urls" id='t2'>
<input id="btnAdd" type="button" value="add another URL" onclick="AddTextBox()" /><br><br>
<div id="TextBoxContainer">
<!--Textboxes will be added here -->
</div>
<input type="submit" name="submit" onclick="return check();">
</table>
</form>
</body>
</html>
JS - script.js
function GetDynamicTextBox(value){
return '<Label> Enter the URL : </label>' +
'<input name = "habits" type="text" class="urls" value = "' + value + '" />' +
' <input type="button" value="Remove" onclick = "RemoveTextBox(this)" /><br><br>'
}
function AddTextBox() {
var div = document.createElement('DIV');
div.innerHTML = GetDynamicTextBox("");
document.getElementById("TextBoxContainer").appendChild(div);
}
function RemoveTextBox(div) {
document.getElementById("TextBoxContainer").removeChild(div.parentNode);
}
function RecreateDynamicTextboxes() {
var values = eval('<%=Values%>');
if (values != null) {
var html = "";
for (var i = 0; i < values.length; i++) {
html += "<div>" + GetDynamicTextBox(values[i]) + "</div>";
}
document.getElementById("TextBoxContainer").innerHTML = html;
}
}
window.onload = RecreateDynamicTextboxes;
I think you can first try to add an "onchange" handler to the "TextBoxContainer" div and user event.target or event.srcElement to identify whether it is a textbox that triggered the "onchange" event. If the trigger dom is exactly the ones you want, then you can try to validate its value and if it is not, you don't need to do anything. If this is done, then the rest things will be simply add/remove textboxes to the container element. Below are some sample codes that may help:
<script type="text/javascript">
var _container = document.getElementById('TextBoxContainer');
function add(){
var _txt = document.createElement("INPUT");
_txt.type = "text";
_container.appendChild(_txt);
}
_container.onchange = function(event){
var _dom = event.target || event.srcElement;
if(_dom && _dom.tagName === "INPUT" && _dom.type === "text"){
//alert(_dom.value);
//You can validate the dom value here
}
};
document.getElementById('add').onclick=function(){
add();
};
</script>

Adding input fields to a HTML form

I want to dynamically add form input fields to a form using the javascript below by clicking on the add button:
var i = 0;
function increment() {
i += 1;
}
function addfieldFunction() {
var r = document.createElement('div');
var y = document.createElement("INPUT");
var z = document.createElement("INPUT");
y.setAttribute("class", "dash-input");
y.setAttribute("type", "text");
y.setAttribute("placeholder", "University");
z.setAttribute("class", "dash-input");
z.setAttribute("type", "text");
z.setAttribute("placeholder", "Course");
increment();
y.setAttribute("Name", "a_level[ + i ][0]");
r.appendChild(y);
z.setAttribute("Name", "a_level[ + i ][1]");
r.appendChild(z);
document.getElementById("form-div").appendChild(r);
}
<form class = "dash-form" method = "POST" action = "/" >
<div id = "form-div">
<input class = "dash-input" type = "text" name = "a_level[+i][0]" value = "" placeholder = "University"/>
<input class = "dash-input" type = "text" name = "a_level[+i][1]" value = "" placeholder = "Course"/>
</div>
<div class = "dash-submit">
<input class = "dash-submit-button" type = "submit" value = "Submit"/>
</div>
</form>
<div class = "dash-add">
<button class = "dash-add-button" onclick = "addfieldFunction()">ADD</button>
</div>
The function returns an i instead of incrementing and returning an integer as shown below:
<div id = "form-div">
<input class = "dash-input" type = "text" name = "a_level[0][0]" value = "" placeholder = "University"/>
<input class = "dash-input" type = "text" name = "a_level[0][1]" value = "" placeholder = "Course"/>
</div>
Concatenate variable i using +(concatenation operator) operator
The concatenation operator (+) concatenates two string values together, returning another string that is the union of the two operand strings.
var i = 0;
function increment() {
i += 1;
}
function addfieldFunction() {
var r = document.createElement('div');
var y = document.createElement("INPUT");
var z = document.createElement("INPUT");
y.setAttribute("class", "dash-input");
y.setAttribute("type", "text");
y.setAttribute("placeholder", "University");
z.setAttribute("class", "dash-input");
z.setAttribute("type", "text");
z.setAttribute("placeholder", "Course");
increment();
y.setAttribute("name", "a_level[ " + i + " ][0]"); //Keep attribute in lower case
r.appendChild(y);
z.setAttribute("name", "a_level[ " + i + "][1]");
r.appendChild(z);
document.getElementById("form-div").appendChild(r);
}
<form class="dash-form" method="POST" action="/">
<div id="form-div">
<input class="dash-input" type="text" name="a_level[+i][0]" value="" placeholder="University" />
<input class="dash-input" type="text" name="a_level[+i][1]" value="" placeholder="Course" />
</div>
<div class="dash-submit">
<input class="dash-submit-button" type="submit" value="Submit" />
</div>
</form>
<div class="dash-add">
<button class="dash-add-button" onclick="addfieldFunction()">ADD</button>
</div>
You need to concatenate it like this:
y.setAttribute("name", "a_level[" + i +"][0]");
As Rayon pointed out: keep attributes in lower case although the HTML5 standard does not require lower case attribute names (see here). W3C recommends it though and XHTML validation would fail using uppercase letters.

The code not working. I cannot identify the issue

I was writing some code and for some reason that I am unaware of, whenever I click on the button, the function that it is assigned does not run. Does anybody know why? Thanks in advance.
<html>
<head>
</head>
<body>
<script>
function prime(number) {
var text = document.getElementById("p").innerHTML;
var n = 0;
for(var i = 2; i<number; i++){
if(number%i==0){
text = "Your number, "+number+", is divisible by "+i+"! It's composite!";
n = 1;
}
}
if(n==0){
text = "Your number, "+number+", is prime!";
}
}
function funcito(){
console.log("Functions!");
var number = document.getElementById("input");
prime(number);
}
</script>
<p id="p"></p><br>
<form id="input">
Your Number: <input type="number" name="uInput"><br>
</form>
<p>Click "Got my number" to find out!.</p>
<button onclick="funcito()" value = "Got my number">Got my number</button>
</body>
</html>
Try this
<button onclick="funcito()" value = "Got my number">Got my number</button>
There are a couple of other issues with that code, so you won't get the result you are looking for. Try this code:
<html>
<head>
</head>
<body>
<script>
function prime(number) {
var text = document.getElementById("p");
var n = 0;
for(var i = 2; i<number; i++){
if(number%i==0){
text.innerHTML = "Your number, "+ number+", is divisible by "+i+"! It's composite!";
n = 1;
}
}
if(n==0){
text.innerHTML = "Your number" + number + " is prime!";
}
}
function funcito(){
console.log("Functions!");
var number = document.getElementById("input").value;
prime(number);
}
</script>
<p id="p"></p><br>
<form>
Your Number: <input id = "input" type="number" name="uInput"><br>
</form>
<p>Click "Got my number" to find out!.</p>
<button onclick="funcito()" value = "Got my number">Got my number</button>
</body>
</html>
Because you write onclick="funcito" which is wrong write onclick="funcito()". instead.

How to store inputs from a textbox in array in Javascript

<!DOCTYPE html>
<html>
<head>
<form id="form1">
Beets:<input id="number1" type="integer" size = "5">
Artichokes: <input id="number2" type="integer" size = "5">
Carrots: <input id="number3" type="integer" size = "5">
</form>
<button id = "submitButton" onclick="RunApp()" > Submit</button>
<button id = "displayButton" onclick="getAllValues()" > Display</button>
<script>
var str = "";
function getAllValues() {
var input1, inputs;
input1 = document.getElementById("form1");
inputs = input1.elements["number1"].value;
for (i = 0; i < inputs.length; i++) {
str += inputs[i].value + " ";
}
alert(str);
}
function RunApp()
{
var beets, artichokes, carrots, input1, input2, input3;
// getting inputs into variables
input1 = document.getElementById("form1");
beets = input1.elements["number1"].value;
input2 = document.getElementById("form1");
artichokes = input1.elements["number2"].value;
input3 = document.getElementById("form1");
carrots = input1.elements["number3"].value;
if (beets == "" || carrots == "" || artichokes == "" || isNaN(beets) || isNaN(carrots) || isNaN(artichokes))
{
document.getElementById("demo").innerHTML+= "not valid" + "<br>";
document.getElementById("demo").innerHTML+= "--------------------------" + "<br>";
}
else
{
document.getElementById("demo").innerHTML+= "Beets = " + beets + "<br>"; document.getElementById("demo").innerHTML+= "Artichokes = " + artichokes + "<br>";
document.getElementById("demo").innerHTML+= "Carrots = " + carrots + "<br>";
}
}
</script>
<p id="demo"></p>
</head>
<body>
</body>
</html>
First, this is my first time learning JS.
So, I have a text-box, a submit button, and a display button. When I enter a number in the text-box, and click submit, it shows the number. I enter my second number and clicking the submit button shows me the second number. Then I click on the display button, it will shows the number 1 and number 2 in order. If I have more inputs in the text-box, the display button will show the entire list of all the inputs from the array.
Thank you!
Well, since it's your first time and you're learning I won't just give you the answer, but I'll point you in the right direction.
You want to attach a click event on the submit button to add the value to an array, and then print the array on click of the display button.
i think first you must google for this. I write something and you can improve this. I only want to give an example.
HTML:
<input type="text" id="inputbox">
<br/>
<button type="button" id="submit">Submit</button>
<button type="button" id="display">Display</button>
<br/>
<div id="screen"></div>
JS:
var inputArray = [];
var input = document.getElementById('inputbox');
var screen = document.getElementById('screen');
document.getElementById('submit').onclick = function () {
inputArray.push(input.value);
screen.innerHTML = input.value;
};
document.getElementById('display').onclick = function () {
screen.innerHTML = inputArray
};
http://jsfiddle.net/y9wL27y0/

Categories

Resources