Text Box Event Javascript [closed] - javascript

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 8 years ago.
Improve this question
I'm a noobie and I need some help with changing events in textbox.
Here's the code I am working with:
<body>
<form action="#">
<input type="text" id="begin" /> Apple
=
<input type="text" id="done" />
<select id="newValue" onchange = "function()">
<option value="a">Apple</option>
<option value="b">Blueberry</option>
<option value="c">Cheese</option>
</select>
<p id = "weight"></p>
</form>
<script>
var apple = document.getElementById('begin'),
choice = document.getElementById('done');
apple.onkeyup = function(){
var temp = document.getElementById("newValue").value;
choice.value = this.value * 1; //if apple
choice.value = this.value * 2; //if blueberry
choice.value = this.value * 3; //if cheese
}
</script>
</body>
I have two text boxes. The left text box ('begin') will accept the weight of apple. But the right box ('done') should change the number value depending on what the user chooses form the drop-down text list.
My
apple.onkeyup = function(){
is not doing the right thing. If I give the value of '2' to the left text box,no matter what I choose in the dropdown list, it will return 2 * 3 = 6, meaning it skips everything in the function and evaluates only the last statement.
choice.value = this.value * 3; /*if cheese
How I want it to work is:
Left Box : 2 Right Box : 2 (if apple was chosen)
Left Box : 2 Right Box : 4 (if blueberry was chosen)
I'm sure I need a few 'if statements' to determine which output choice was chosen, something along the lines of
if(temp = Apple){
choice.value = this.value * 1;
}else if(temp = Blueberry){
choice.value = this.value * 2;
}
}
The value in Right Box should also change as the user chooses a different item from the list..
Although I'm not sure if that's the right approach/syntax.

I think this may be what you are looking for, here is a fiddle.
Remove the onchange from your newValue selection and set it in your JavaScript, just like you are doing with your onkeyup function for apple. In your code above, your are calling function() which will likely just cause errors. function() represents an anonymous function, you need to name your function with the syntax function name() if you'd like to call it in this way. However, since you are already setting onkeyup from your JavaScript, you might as well set onchange from the same place in this case.
Then change your JavaScript to this:
var apple = document.getElementById("begin"),
choice = document.getElementById("done"),
fruits = document.getElementById("newValue");
// This function properly sets the done field.
var setDone = function() {
var newVal = document.getElementById("newValue").value;
if (newVal == "a") {
choice.value = apple.value * 1; //if apple
} else if (newVal == "b") {
choice.value = apple.value * 2; //if blueberry
} else if (newVal == "c") {
choice.value = apple.value * 3; //if cheese
} else {
alert("I couldn't find that value!");
}
}
apple.onkeyup = setDone;
fruits.onchange = setDone;
I made your anonymous function into a named variable ,added if statements to check for the value of newValue and set the value of apple appropriately.
Then I set the onkeyup and onchange events for apple and the new variable I created for your selector, fruits.
If you have any questions about how any of this works, feel free to ask in the comments below.

Try this - I'm not sure if I got my apples and blueberries in the right order, but it looks to work OK:
var apple = document.getElementById('begin'),
choice = document.getElementById('done');
apple.onkeyup = function(){
var temp = document.getElementById("newValue").value;
if (temp == 'a') {
choice.value = this.value * 1;
}
if (temp == 'b') {
choice.value = this.value * 2;
}
if (temp == 'c') {
choice.value = this.value * 3;
}
}
FIDDLE

Your code :
var temp = document.getElementById("newValue").value;
choice.value = this.value * 1; //if apple
choice.value = this.value * 2; //if blueberry
choice.value = this.value * 3; /*if cheese
is equal to :
var temp = document.getElementById("newValue").value;
choice.value = this.value * 3;
you repeat assign value to choice.value, so the finally result is :
choice.value = this.value * 3;
you should change the code :
<select id="newValue" onchange = "function()">
<option value="1">Apple</option>
<option value="2">Blueberry</option>
<option value="3">Cheese</option>
</select>
to :
<select id="newValue" onchange = "function()">
<option value="a">Apple</option>
<option value="b">Blueberry</option>
<option value="c">Cheese</option>
</select>
and then change the code :
var temp = document.getElementById("newValue").value;
choice.value = this.value * 1; //if apple
choice.value = this.value * 2; //if blueberry
choice.value = this.value * 3; /*if cheese
to the code :
var temp = document.getElementById("newValue").value;
choice.value = this.value * temp;

So, I'm going to recreate some stuff here. From what I can tell, you want to select a food item and output its weight in the other text field.
/* begin and done are input and output. */
var input=document.getElementById("input");
var output=document.getElementById("output");
/* Handles a change in the input text field, like if the user types apple, blueberry, etc. */
/* You could make this a keyup listener as well, I suppose. */
input.addEventListener("change",function(event_){
switch(this.value){
case "apple":
output.value="weight of apple";
break;
case "blueberry":
output.value="weight of blueberry";
break;
/* Optional default value for when the user is messing around. */
default:
output.value="Please select an item from the drop down list."
break;
}
});
Be sure to use conditionals to evaluate your output. I used a switch statement, but if statements are great, too! What I mean is this:
var x=10;
x=15;
x=7;
alert(x);// Returns 7
var y=Math.random()*100;
if (y<50){
alert("y is less than 50");
} else {
alert("y is greater than 50");
}
Multiple assignments in a row will be overwritten by subsequent assignments.

try this, I tested which can be work.
<body>
<form action="#">
<input type="text" id="begin" /> Apple
=
<input type="text" id="done" />
<select id="newValue" onchange = "f();">
<option value="1">Apple</option>
<option value="2">Blueberry</option>
<option value="3">Cheese</option>
</select>
<p id = "weight"></p>
</form>
<script>
var weightTag = document.getElementById('begin');
var totalTag = document.getElementById('done');
function f(){
var priceTag = document.getElementById('newValue');
if (weightTag.value != "") {
var index = priceTag.selectedIndex;
var priceValue = priceTag.options[index].value;
totalTag.value = weightTag.value * priceValue;
}
}
weightTag.onkeyup = f;

I think this is what you need.
<html>
<head>
</head>
<body>
<form action="#">
<input type="text" id="begin" onkeyup="k(1);" />
<select id="Fruitbox1" onclick="k(1);">
<option value = "3">Apple</option>
<option value = "1.5">Blueberry</option>
<option value = "1">Cherry</option>
</select>
=
<input type="text" id="done" onkeyup="k(0);"/>
<select id="Fruitbox2" onclick="k(0);">
<option
value="3">Apple</option>
<option value="1.5">Blueberry</option>
<option value="1">Cherry</option>
</select>
<p id = "leftWeight"></p>
<p id = "rightWeight"></p>
</form>
<script>
function k(x){
var weightOfFruit1=document.getElementById("Fruitbox1")
var weightOfFruit2=document.getElementById("Fruitbox2")
var NumberofFruit1=document.getElementById("begin")
var NumberofFruit2=document.getElementById("done")
if(x==1)
{
TotalNumberofFruit2=(NumberofFruit1.value * weightOfFruit1.value)/weightOfFruit2.value
NumberofFruit2.value=parseInt(TotalNumberofFruit2)
}else
{
TotalNumberofFruit1=(NumberofFruit2.value * weightOfFruit2.value)/weightOfFruit1.value
NumberofFruit1.value=parseInt(TotalNumberofFruit1)
}
}
</script>
</body>
</html>

Related

Dropdown selection value doesn't become a real value and work in JavaScript

I have a language dropdown and I try to alert the user to have to choose one language before doing anything further like languageOption can become a string and go into array. But it's not working and I don't understand why. I tried:
alert("You didn't choose any language.");
console.alert("You didn't choose any language.");
console.log("You didn't choose any language.");
But they all don't work.
And I thought another way to solve this, which I make
<option value="1" selected>English (American)</option>
but then the value = "1" doesn't become the a value for variable 'languageOption'. So the arrays don't respond and don't know what to do when I see in console. I don't understand why the array is not responding.
Any help I would appreciate.
Below is my code:
<select id="languageSelection" style=display:none>
<option value="">Choose a language</option>
<option value="1">English (American)</option>
<option value="2">Chinese (Mandarin)</option>
<option value="3">Japanese</option>
</select>
var audioSrc = "sound/"
var audioType = ".wav";
// default number of random question, if user this used the dropdown
var default_numFollowUp = 4;
// default delai (seconds) between random questions, if user this used the dropdown
var default_secFollowUp = 10;
// Create the audio element
var audioElement = document.createElement('audio');
var endingArr = [];
var runThroughArr = [];
var randomArr = [];
var languageOption = parseInt($("#languageSelection").val() );
$("#languageSelection").on("change", function(){
languageOption = $(this).val(); // Make languageOption value be string
//if(languageOption.length==0){languageOption=1;}
console.log("langugeOption is " + languageOption);
console.log("Language changed to: "+ $(this).find("option").eq( $(this)[0].selectedIndex ).text() + " (Index: "+languageOption+")" );
console.log(typeof(languageOption)); // Outputs string
endingArr = [];
runThroughArr = [];
randomArr = [];
if(languageOption === ""){
alert("You didn't choose any language.");
console.alert("You didn't choose any language.");
console.log("You didn't choose any language.");
}
else if(languageOption === "1"){
console.log("English");
for(i = 0; i < intro_playList.length; i++){
if(intro_playList[i].stage === "ending"){ endingArr.push(i); }
if(intro_playList[i].runThrough){ runThroughArr.push(i); }
if(intro_playList[i].random){ randomArr.push(i); }
}
}
else if (languageOption === "2"){
console.log("Chinese");
for(i = 0; i < intro_playList_chi.length; i++){
if(intro_playList_chi[i].stage === "ending"){ endingArr.push(i); }
if(intro_playList_chi[i].runThrough){ runThroughArr.push(i); }
if(intro_playList_chi[i].random){ randomArr.push(i); }
}
}
});
You need to assign the onchange function after loading the document. With jQuery, you can do it like this
var languageOption;
$(document).on("ready", function() {
languageOption = $("#languageSelection").val();
$("#languageSelection").on("change", function() {
your code here ...
}
}

Javascript selection

I have a dropdown list of "Pounds", "grams", "Kilograms" and "Ounces". I want a situation that when I select gram to perform a function, when I input a value in the input field, also when i select pounds i want another function to perform when i input a value in the input field and so on. I have tried it but couldn't get it done.
Here's my code....
HTML
<div id="weight-dropdown">
<h4>Weight Converter</h4>
<select id="select-weight">
<option value="0">...</option>
<option value="1">Pounds</option>
<option value="2">Grams</option>
<option value="3">Kilograms</option>
<option value="4">Ounce</option>
</select>
<input id="input" type="number" placeholder="Enter value...">
</div> <!-- weight dropdown-->
<div id="output">
<div>
<h5>Pounds (lbs) :</h5>
<div id="poundsOutput"></div>
</div>
<div>
<h5>Grams (g) :</h5>
<div id="gramsOutput"></div>
</div>
<div>
<h5>Kilorams (kg) :</h5>
<div id="kgOutput"></div>
</div>
<div>
<h5>Ounce (oz) :</h5>
<div id="ozOutput"></div>
</div>
</div><!--output-->
Javascript
if (document.getElementById("select-weight").selectedIndex = "0"){
document.getElementById("input").addEventListener("input", function(e){
var pounds= e.target.value;
document.getElementById("poundsOutput").innerHTML = pounds
document.getElementById("gramsOutput").innerHTML = pounds/0.0022046;
document.getElementById("kgOutput").innerHTML = pounds/2.2046;
document.getElementById("ozOutput").innerHTML = pounds*16;
})
} else (document.getElementById("select-weight").selectedIndex = "2"){
document.getElementById("input").addEventListener("input", function(e){
var grams= e.target.value;
document.getElementById("poundsOutput").innerHTML = grams*0.0022046;
document.getElementById("gramsOutput").innerHTML = grams;
document.getElementById("kgOutput").innerHTML = grams/1000;
document.getElementById("ozOutput").innerHTML = grams/28.35;
})
}
You assign the input listener based on the input value once , but once assigned it gets always triggered, even if the select changes. May do it the other way round and use a switch:
document.getElementById("input")
.addEventListener("input", function(e){
var input = e.target.value;
switch(document.getElementById("select-weight").selectedIndex){
case 0:
return alert("Please select unit");
break;
case 1 :
var pounds = input;
var grams = input/0.0022046;
var kg = input/2.2046;
var oz = input * 16;
break;
case 2:
var pounds = input * 0.0022046;
var grams = input;
var kg = pounds/2.2046;
var oz = pounds * 16;
break;
case 3:
//...
break;
}
//update DOM with values
document.getElementById("poundsOutput").innerHTML = pounds;
document.getElementById("gramsOutput").innerHTML = grams;
document.getElementById("kgOutput").innerHTML = kg;
document.getElementById("ozOutput").innerHTML = oz;
});
While the upper code is good / understandable, you could use a more shorter approach. You could get the value of the next "row" by dividing through a certain number, and of the previous by multiplying with a certain number. So you could do:
var conversion = [
null,//an endpoint
1,// pounds / this = grams
2,//grams / this = kg
3, //kg/this = oz
null//an endpoint
];
//some pseudocode:
var index = selectWeight.selectedIndex;
var start = event.target.value;
var result = [];
//now multiple from right to left of selected index:
conversion.slice(0,index).reduceRight(function(value,multiplier,i){
result[i] = value;
return value * multiplier;
}, start);
//divide from right to left:
conversion.slice(index-1).reduce(function(value,divider,i){
result[index+i-1] = value;
return value / divider;
},start);
And now weve got our results:
var [pounds,grams,kg,oz] = result;
You're doing a left-hand assignment;
if (document.getElementById("select-weight").selectedIndex = "0"){
while it should be
if (document.getElementById("select-weight").selectedIndex == "0"){
Same applies to other statements.
Use the event onClick for each option and then use their ids to do a factory of weight functions.

Add array values without clearing previous value using javascript

I have a password generator which works fine. But need a little change. The below image shows
Once I click the "Generate Password" button it generates one password.
Required: When I click the button again, I need to have another password generated below without clearing the previous one. Tried a couple of variations in loop but did not work.
**passGen.js**
function passGen() {
var Generator = {};
Generator.generateMnemonic = function(length, num_length, mixcase) {
var ret = '';
var vowels = 'aeioe';
var consonants = 'bcdfghklmnpqrstvwxzy';
if (mixcase) {
vowels += vowels.toUpperCase();
consonants += consonants.toUpperCase();
}
vowels = vowels.split('');
consonants = consonants.split('');
for(var i = 0; i < length / 2; i++) {
ret += vowels.getRandom();
ret += consonants.getRandom();
}
if (!num_length) return ret;
var pos = $random(2, length - 2 - num_length);
return ret.substr(0, pos) + $random(Math.pow(10, num_length - 1), Math.pow(10, num_length) - 1) + ret.substr(pos + num_length);
};
var observe = new Observer('#generator-length, #generator-num_length, #generator-mixcase, #generator-amount', function(values) {
var length = values[0].toInt();
var num_length = values[1].toInt();
var mixcase = values[2].toInt();
var amount = values[3].toInt();
// Fill passwords in a loop
var words = [];
for (var i = 0; i < amount; i++) {
words.push(Generator.generateMnemonic(length, num_length, mixcase) );
}
// Get the output area
var output = $('generator-output');
// Output it and highlight it so users will notice the update
output.value = words.join("\n");
output.getParent().highlight('#ff8', '#fff');
}, {
// periodical: 1000 // interval in ms
});
// To fill in the first values
observe.fire();
}
**Part of Hmtl**
<script type="text/javascript" src="passGen.js"></script>
<span>How many passwords:</span>
<br>
<select name="amount" id="generator-amount">
<option value="1" selected>1</option>
<option value="5">5</option>
<option value="10">10</option>
<option value="50">50</option>
<option value="100">100</option>
</select>
</label>
<input type="button" name="button" value="Generate Password" onclick="passGen();">
<label>
<br>
<span>Your passwords:</span>
Do something along these lines: (small example to give the feel) with a static variable.
function passGen() {
if ( typeof passGen.words == 'undefined' ) { /* It has not been called do initialization*/
passGen.words = [];}//else previous passwords persist, and you push, onto them.
passGen.words.push("Hello");
alert(passGen.words);
}
passGen();
passGen();
In your case keep my initial if, remove your line
var words = [];
and prepend passGen. to your words.push and words.join
adapted from Static variables in JavaScript

if statement counter variable confusion javascript

As a novice in javascript, I am having trouble writing an If statement, with an event happening after the fourth turn. I want the alert to pop up after the user has clicked four options. I added the counter variable "turns" to the output so I can see if it has been counting correctly but it does not.
var question1 = new Array();
var turns = 0;
window.onload = function () {
var eSelect = document.getElementById('question1');
var optOtherReason = document.getElementById('displayresponse');
var options = document.getElementsByTagName("option");
eSelect.onchange = function () {
var li = document.createElement("li");
li.innerHTML = options[eSelect.selectedIndex].innerHTML;
var ol = document.getElementById("appendedtext");
ol.appendChild(li);
question1.push(li.innerHTML);
var x = document.getElementById("display");
x.innerHTML = question1 + turns;
turns + 1;
}
if (eSelect.selectedIndex == 3) {
optOtherReason.style.display = 'block';
turns - 1;
}
if (turns = 4) {
alert("hey your turn is over")
}
}
<select id="question1" name="question">
<option value="x">Reason1</option>
<option value="y">Reason2</option>
<option value="other">Otherreason</option>
<option value="none">None</option>
</select>
<br>
<div id="displayresponse" style="display:none;">If you did not see a choice here, you may search for other sites.</div>
<ol id="appendedtext"></ol>
<div id="display"></div>
To compare two expression you need to use == :
if ( turns == 4)
Also, turns is a variable, so to sum/substract one you should use:
turns += 1
turns -= 1
Or, as pointed out in comments, you could also use:
turns++;
turns--;

How can my Javascript shopping cart code be improved? Please forgive the raw code [closed]

Closed. This question is off-topic. It is not currently accepting answers.
Want to improve this question? Update the question so it's on-topic for Stack Overflow.
Closed 9 years ago.
Improve this question
In the last few days I have tried to get my head around Javascript. This is my first proper Javascript and I am wondering if anybody can see anyways that I can improve my code and ultimately my knowledge of Javascript. I appreciate my code thus far may seem a bit raw.
One thing I am stumped at how to finish my 'calcUnitPriceF' function so that I am not creating an array in each product case. These prices will come from a database soon.
The code below I hope is very clear in what it does.
<script type="text/javascript">
function update(){
var total = 0.00;
var calcUnitPrice, quantity;
var myForm = document["getElementById"]("totalform");
var justQuantity = myForm["quantity[]"];
var justPrice = myForm["productPrice[]"];
var unitPrice = myForm["unitPrice[]"];
var linePrice = myForm["linePrice[]"];
for(var i =0; i < justQuantity.length; i++)
{
justQuantity[i].value = Math.floor(justQuantity[i].value);
quantity = justQuantity[i].value;
calcUnitPrice = 0;
if(isNaN(quantity) || quantity < 0) {
justQuantity[i].value ="0";
}
else
{
calcUnitPrice = calcUnitPriceF(justPrice[i].value,quantity);
document.getElementById('unitPrice[' + i + ']').innerHTML = '£' + calcUnitPrice.toFixed(2);
document.getElementById('linePrice[' + i + ']').innerHTML = '£' + (calcUnitPrice * justQuantity[i].value).toFixed(2);
total = (total + (quantity* calcUnitPrice));
}
}
document.getElementById("delivery").innerHTML = "Your Order Delivery is: £2.50";
document.getElementById("Totprice2").innerHTML = "Your Order Total is: £" + total.toFixed(2);
}
function calcUnitPriceF(product,quantity)
{
switch(product)
{
case '0':
return 0;
case '1':
var values = [5, 4 , 15.30 , 10 , 12 ]; // Structure(Exceeding Quantity Price,Quantity Under, Price)
for(var i = 1; i< values.length; i=i+2)
if(quantity < values[i])
return values[i+1];
return values[0];
case '2':
return 75;
}
}
</script>
<body>
<form id="totalform">
<select id ="productPrice[]" onchange="update()">
<option value="0">Please Select One</option>
<option value="1">Product 1</option>
<option value="2">Product 2</option>
</select>
QUANTITY <input type = "text" id = "quantity[]" onChange="update()" >
UNIT PRICE <p id="unitPrice[0]" style="display:inline;">£0.00</p>
LINE PRICE <p id="linePrice[0]" style="display:inline;">£0.00</p><br />
<select id="productPrice[]" onchange="update()">
<option value="0">Please Select One</option>
<option value="1">Product 1</option>
<option value="2">Product 2</option>
</select>
QUANTITY <input type = "text" id = "quantity[]" onChange="update()" >
UNIT PRICE <p id="unitPrice[1]" style="display:inline;">£0.00</p>
LINE PRICE <p id="linePrice[1]" style="display:inline;">£0.00</p><br />
<span id ="delivery">Your Order Delivery is: £0.00</span><br />
<span id ="Totprice2">Your Order Total is: £0.00</span>
</form>
The number one thing I would do is change the JS approach.
var project = {};
project.ShoppingCart = function() {
this.total = 0;
this.justQuantity = ...;
this.currentQuantity = 0;
};
/**
* Updates the current quantity in the shopping cart.
* #param {!number} quantity The quantity to update with.
* #return {void} nothing.
*/
project.ShoppingCart.prototype.updateQuantity = function(quantity) {
// this is how to check for a number properly.
if (!isNaN(quantity) && parseFloat(quantity) && isFinite(quantity)) {
this.currentQuantity = quantity;
} else {
console.log("Invalid quantity");
};
};
Now in order to use the above.
var shoppingCart = new project.ShoppingCart();
Look at Object Oriented Javascript, how to properly use that, stop poluting the global namespace and randomly writing functions, comment your code and validate things properly.

Categories

Resources