Javascript OOP: Passing a value to property through input fails - javascript

I`m learning and training js oop right now but I have an issue. I want to pass a value to property from a constructor by input value.For example if the user want to make his own character , he has to input name , age ,etc etc... but my code fails.Here's my js and html code.I've searched for the answer in the stackoverflow but couldn't find any answers to my question.
JS
document.addEventListener("DOMContentLoaded", function() {
var button = document.getElementById('action');
var nameInput = document.getElementById('charName').value;
var ageInput = document.getElementById('age').value;
var par = document.getElementById('result');
function Person(name,age){
this.name = name;
this.age = age;
}
var first = new Person(nameInput,ageInput);
button.addEventListener('click',function(){
par.innerHTML = first.name + ' ' + first.age;
});
});
HTML:
<h1>Javascript Found</h1>
<button id="action">Action</button>
<div id="holder">
<p>
Give a name:<input type="text" id="charName" placeholder="Enter a name">
</p>
<p>
Enter age: <input type="text" id="age" placeholder="Enter a number(0-100)">
</p>
<p id="result"></p>
</div>

I would assume that the click listener is executed correctly, but the values of first.name and first.age are ''. You can verify that by putting a console.log(first) in the click listener.
So why is that? At the time your DOMContentLoaded listener triggers, both your inputs are empty (value == ''). Now, you copy these values into an instance of Person. Next, you wait for clicked events which are triggered at some point but the value of name and age in your instance were not updated so they are still "". So you set par.innerHTML = ' '.
What you need to do is, you have to read the values of your inputs again and update the variables in your instance before you set par.innerHTML.

You need to grab the value from the input on click not before that otherwise it will use the old value which would be an empty string.
I changed the code so nameInput and ageInput refer to the elements and the value is then fetch inside the Person class and first is created on click.
See JSFiddle to see it working.
var button = document.getElementById('action');
var nameInput = document.getElementById('charName');
var ageInput = document.getElementById('age');
var par = document.getElementById('result');
function Person(name,age){
this.name = name.value;
this.age = age.value;
}
button.addEventListener('click',function(){
var first = new Person(nameInput, ageInput);
console.log(first);
par.innerHTML = first.name + ' ' + first.age;
});

Related

JS - Calculate values depending on selected dropdowns

So I have this calculator for money that shows you the amount you enter but in a different money value. (Example dollar to euro)
Here is the HTML:
<b> Exchange money </b> <br> <br>
Enter amount for RSD: <input type="number" name="nbsAmount" id="nbsAmount" size="5"> <br>
<button class="dugme">Calculate</button> <br> <br>
Evro value is: <div class="konacnaEvroVrednost"></div>
Dolar value is: <div class="konacnaDolarVrednost"></div>
Swiss value is: <div class="konacnaSwissrednost"></div>
And here is the JS:
$('.dugme').click(function(){
var broj = document.getElementById('nbsAmount').value;
var evro = broj * 0.0085;
var dolar = broj * 0.0095;
var frank = broj * 0.0096;
$('.konacnaEvroVrednost').text(evro + ' €');
$('.konacnaDolarVrednost').text(dolar + ' $');
$('.konacnaSwissrednost').text(frank + ' Fr');
});
And this works fine. As you can see:
Here is the fiddle:
http://jsfiddle.net/5zvdwtpL/1/
But now I want to change this to work a bit more dynamically.
I want there to be two dropdowns that lets you select the value you want to change from to. Like this:
This is what I got so far: https://jsfiddle.net/7s8g9kLt/2/
The problem is that one input value should be copied to the other input value but with the added value of the currency.
So If I select RSD and set 1200, the other USD, then the other input should display 11.4.
So I am stuck a bit here as to how I can achieve this.
First of all, you have bound myFunction to button onClick Event but you have not defined function with this name. You can see following error in console after clicking button
Uncaught ReferenceError: myFunction is not defined
You will have to define this function:
window.myFunction = function() {...}
or event better, add event listener to button click:
document.getElementById('buttonId').addEventListener('click', function() {...})
To calculate dynamic rates, i would first convert input amount to single currency (for example RSD) and then multiply that value by correct rate.
I've modified your jsFiddle (https://jsfiddle.net/rhj4dgz7/3/) to reflect those changes.
You can create a dictionary with the pair of "id" of dropdown and the conversion rate, also you can give the same id to both drop downs. then you gonna just multiply the value by the rate and add the result to the second input.
var rsd = 1;
var evro = 0.0085;
var dolar = 0.0095;
var frank = 0.0096;
var dict = {
"4":rsd,
"1":evro,
"3":dolar,
"2":frank
}
function myFunction(){
var mvs = document.getElementById('mojaVrednostSelect').value;
var nvs = document.getElementById('novaVrednostSelect').value;
var mv = document.getElementById('mojaVrednost').value;
var nv = document.getElementById('novaVrednost').value;
novaVrednost.value = parseInt(mojaVrednost.value) * dict[nvs]
console.log("Yoooo"+ dict[nvs])
console.log("mvs je" + mvs);
console.log("nvs je" + nvs);
console.log("======");
console.log("mojaVrednost je" + mojaVrednost.value);
console.log("novaVrednost je" + novaVrednost.value);
}
document.getElementById('button').onclick = myFunction
check this fiddle
Hope this helps you

Change value of <input> to include a superscript, using Javascript

The following code works correctly for me, in HTML.
<input type = "text" name = "var_1" id = "i_var_1" value = "x&sup8">
The following, using Javascript, also works:
<p id = "p1"><input type = "text" name = "var_1" id = "i_var_1" value = "0"></p>
<script....>
q1 = document.getElementById("p1");
q1.innerHTML = '<INPUT TYPE = "text" name = "var_1a" id = "i_var_1a" value = "x&sup8">';
</script>
However I need to add in the superscript when a button is pressed. So I have something like:
<p id = "p1"><input type = "text" name = "var_1" id = "i_var_1" value = "0"></p>
<input type = "button" id = "i_button" value = "Add the superscript" onclick="Add_Superscript()";>
<script.....>
function Add_Superscript()
{
q1 = document.getElementById("p1");
b1 = document.getElementById("i_var_1");
c1 = b1.value.toString() + "&sup8";
q1.innerHTML = '<INPUT TYPE = "text" name = "var_1a" id = "i_var_1a" value = c1.value>';
}
</script>
The above code does not reproduce the superscript properly.
Anyone any ideas? Thanks in advance for comments.
Not sure this is what you want, but it adds &sup8 to whatever is in the input box.
function Add_Superscript() {
q1 = document.getElementById("p1");
b1 = document.getElementById("i_var_1");
c1 = b1.value.toString() + "&sup8";
q1.innerHTML = '<INPUT TYPE = "text" name = "var_1a" id = "i_var_1a" value = "' + c1 + '">';
}
<p id="p1">
<input type="text" name="var_1" id="i_var_1" value="0">
</p>
<input type="button" id="i_button" value="Add the superscript" onclick="Add_Superscript()" ;>
I don't know what you're trying to do but maybe it's because of the c1.value ! Try:
q1.innerHTML = '<INPUT TYPE = "text" name = "var_1a" id = "i_var_1a" value =' + c1 + '>';
You have several typos in your code and a lot of unnecessary code as well. You just need to set up a click event handler on the button that populates the value of the pre-existing input. No need to create a new input.
A few notes:
When you were trying to create the new input element (which it turns out you don't need to do in the first place), you had the entire thing as a string. You need to inject the dynamic value into that string, by terminating the string, concatenating the new value in and then concatenating the closing of the string, like this:
q1.innerHTML = '<input type="text" name="var_1a" id="i_var_1a" value=' + c1.value + '>';
Next, it's best to use good naming conventions for elements and variables. Prefix an id and name with something that describes the "type" of thing the element is. Use btn (button), txt (textbox), chk (checkbox), rad (radio button), etc. And don't use _ (that's a very old convention). Instead use "camelCase". Further, with form elements, you need to give them a name for form submission purposes, but it is also a good idea to give them and id for CSS and JavaScript purposes. Use the same id that you used for name so that you don't have two different names for the same thing.
Lastly, don't configure your HTML elements to event handlers via HTML attributes (onclick, onmouseover, etc.). Doing this creates global anonymous functions that alter the this binding in the callback function, it creates "spaghetti code" that is hard to scale and debug and it doesn't follow the W3C DOM Event specification. Instead, do all the work in JavaScript and use .addEventListener() to connect functions to events.
// Get references to the relevant DOM elements
var btn = document.getElementById("btnGo");
var input = document.getElementById("txtInput");
// Set up a click event handling function
btn.addEventListener("click", add_Superscript);
function add_Superscript(){
// Create a new value that is the old value plus a "superscript" value
var newVal = input.value + "&sup8";
// Update the input with the new value:
input.value = newVal;
}
<p>
<input type="text" name="txtInput" id="txtInput" value="0">
</p>
<input type = "button" id="btnGo" value="Add the superscript">

pass a variable name and evaluate it to that variable's value

I have a form with many buttons all of which print a value in the relevant textbox. the problem is the value is a fairly long text string and I would like to create a shorter variable eg. 'text' and make that variable equal to eg. 'some long sentence that I only want to type once'. any idea how I can edit this code to make this possible
function setInput(button, setValue) {
var buttonVal = button.value,
textbox = document.getElementById('input_' + buttonVal);
textbox.value = setValue;
<html>
<input type='submit' name='submit_a' value="a"
onclick="setInput(this,'make_me_a_variable'); return false;">
</html>
var textLookup = {
btnName1: "Long text",
btnName2: "Longer text"
};
// inside your function
var buttonText = ...,
inputText = textLookup[buttonText];
// do stuff with inputText;
Instead of defining the event handler in the HTML code, you could also create the event handler with javascript. You need to do that in another event handler for document.onload. When you do it earlier, the input HTML element might not have been parsed and created yet, so no event handler for it can be added.
<script>
// store your text in a variable
var inputText = 'make_me_a_variable';
// define some code which is executed when the page is loaded:
document.addEventListener("load",function(event){
// get the input by the id property I added to the HTML below.
var input = document.getElementById('submit_a');
// add an event handler for the click event (replaces the onclick HTML property)
input.addEventListener("click",function(event) {
setInput(this, inputText);
return false;
});
});
</script>
[...]
<input id="submit_a" type='submit' name='submit_a' value="a" >
You can create a variable and assign your long text to the variable and use it where ever you want.
Modified code
var longText = 'long text here'.
function setInput(button) {
var buttonVal = button.value,
textbox = document.getElementById('input_' + buttonVal);
textbox.value = longText ;
}
Html:
<input type='submit' name='submit_a' value="a"
onclick="setInput(this); return false;">

Dynamic values in object properties

want to make values of the oject's dynamic (from user input) but I get "undefined". The idea is to have 3 input fields and the user should input values in them which will fill up the alert message.
<script type="text/javascript">
function Family (fatherName, motherName, sisterName) {
this.fatherName = fatherName;
this.motherName = motherName;
this.sisterName = sisterName;
this.myFamily = function() {
alert("My father's name is " + this.fatherName +", my mother's name is "+ this.motherName +" and my sister's name is " + this.sisterName +".");
}
}
var Me = new Family(
Family["fatherName"] = father,
Family["motherName"] = mother,
Family["sisterName"] = siter);
var father = document.getElementById("fatherId").value;
var mother = document.getElementById("motherId").value;
var sister = document.getElementById("sisterId").value;
</script>
<input type="text" id="fatherId" />
<input type="text" id="motherId" />
<input type="text" id="fatherId" />
<input type="submit" value="Send" onclick="Me.myFamily();">
Also I'm looking for a way how user can add or remove properties (values in them, too).
There are a few things wrong with your code.
You've used your variables here
Family["fatherName"] = father,
Family["motherName"] = mother,
Family["sisterName"] = siter); // This should be sister by the way
before declaring them here
var father = document.getElementById("fatherId").value;
var mother = document.getElementById("motherId").value;
var sister = document.getElementById("sisterId").value; // Doesn't exist
Try switching the statements so you're declaring the variables first.
Also, there is no sisterId, you've used fatherId twice.
You're also calling javascript before the DOM is ready. If you're using jQuery, wrap your JS in
$(document).ready(function() { }
or if you want to stick with plain JS, try
window.onload = function() { }
You'll have to be more specific on what myFamily is supposed to do, since you haven't even mentioned that method.
Here is the working snippet of your example.
<input type="text" id="fatherId" />
<input type="text" id="motherId" />
<input type="text" id="sisterId" />
<input type="submit" value="Send" id="submit" />
<script>
function Family(fatherName, motherName, sisterName) {
this.fatherName = fatherName;
this.motherName = motherName;
this.sisterName = sisterName;
this.myFamily = function() {
alert("My father's name is " + this.fatherName +
", my mother's name is " + this.motherName +
" and my sister's name is " + this.sisterName + ".");
};
}
document.getElementById("submit").onclick = function() {
var father = document.getElementById("fatherId").value;
var mother = document.getElementById("motherId").value;
var sister = document.getElementById("sisterId").value;
Me = new Family(father, mother, sister);
Me.myFamily();
}
</script>
All the mistakes are summarized very well by Brandon.
*EDIT: (anser to your comment)
Your code has two execution related problems.
<script> tags are executed immediately and therefore if you insert script before the <input> part then there are no input elements available for you to retrieve.
You want to retrieve values of the inputs, but those inputs contain data when user clicks on the submit and therefore must be read using .value() at the onclick time. If you try to read them outside the onclick part then they are accessed immediately during page load when the input fields are empty.

Javascript array dynamic population

I am brand new in WebDevelopment and I came across the following issue.
I have an html file where a textbox is defined as well as a "View all Contents" button
The user can enter a value in the textbox and submit the data
Then repeat this action multiple times
Every time a new value is entered this value should be stored to a
Javascript array
The user will be able to view the contents of the Javascript array
when clicking on the button "View all Contents".
So my problem is how these values are stored dynamically in Javascript and printed when the user is finished.
Your answer is very much appreciated.
Best Regards
Olga
A very trivial example: http://jsfiddle.net/pimvdb/unEMp/.
<input type="text" id="textbox">
<br>
<input type="button" id="add" value="Add">
<br>
<input type="button" id="view" value="View all Contents">
with:
var arr = []; // the array
document.getElementById('add').onclick = function() {
arr.push(document.getElementById('textbox').value); // add textbox value to array
document.getElementById('textbox').value = ''; // clear textbox value
};
document.getElementById('view').onclick = function() {
alert(arr.join(', ')); // alert array contents as a string; elements are delimited by ', '
};
First you'll want to create your array in the global scope - this means outside of a method body, somewhere in the <script></script> body:
var myArray = new Array();
Next, you'll want to append the array with a new value each time the user clicks a button:
function myButtonClick(){
var myTb = document.getElementById("textBox1");
myArray.push(myTb.value);
myTb.value = ""; // reset the textbox
}
Next, you'll want another button handler for the click on "View All":
function myViewAllButtonClick(){
// will create a string of myArray's values, seperated by new line character
var msg = myArray.join("\n");
// will show the user all of the values in a modal alert
alert(msg);
}
Your HTML might look like:
<input type="text" id="textBox1" />
<input type="button" id="button1" value="Add Value" onclick="myButtonClick();"/>
<input type="button" id="button2" value="Show All" onclick="myViewAllButtonClick();"/>
When you get the hang of things, you can get rid of the "Add Value" button all together and use:
<input type="text" id="textBox1" onchange="onTextChanged(this)"/>
With a handler like:
function onTextChanged(e){
if(e.value == "") return;
myArray.push(e.value);
e.value = "";
}
The onTextChanged handler will fire when the user changes text in the textbox (it won't fire though until the textbox loses focus, which may make it bad for this example, but still a good JS skill to learn/understand).
Happy coding - good luck!
B
JavaScript array could be dynamicaly changed:
var array = [];
function foo() {
array.push('foo');
}
function boo() {
array.push('boo');
}
i put together a small example: http://jsbin.com/izumeb/3
<p><input type="text" id="txt"></input><button onclick="addToAll();">add to selection</button></p>
<p><button onclick="showAll();">show all</button></p>
<p id="all"></p>
and JS
<script>
var values = [];
function addToAll() {
var txt = document.getElementById("txt");
values.push(txt.value);
txt.value = "";
}
function showAll() {
var all = document.getElementById("all");
var str = "";
for (var i=0;i<values.length;++i) {
str += values[i] + "<br/>";
}
all.innerHTML = str;
}
</script>

Categories