Thanks in advance.
I want to change the value of input text "total" in a form depending the value of the select "opciones". I tried with onchange(), with document.getElementById("").value but it doesn't works.
I dont know what is failing, but I cannot change the input value.
<form name="formulario">
<select name="opciones" id="opciones">
<option>1</option>
<option>2</option>
<option>3</option>
</select>
<input type="text" name="suma" id="total">
</form>
Javascript:
function formtotal() {
if (document.formulario.opciones.value = "1") {
document.formulario.suma.value = "1000";
}
else if (document.formulario.opciones.value = "2") {
document.formulario.suma.value = "1250";
}
else if (document.formulario.opciones.value = "3") {
document.formulario.suma.value = "1500";
}
}
I think you should try to work with
let e = document.getElementById("opciones");
let total = document.getElementById("total");
switch(e.selectedIndex) {
case 0:
total.value = 1000;
break;
case 1:
total.value = 1250;
break;
case 2:
total.value = 1500;
break;
default:
total.value = 0;
}
I think instead of document.formulario.suma.value it should be document.formulario.total.value.
However, below code is working fine. Tested in jsfiddle (link below).
function formtotal() {
var x = document.getElementById("opciones").value;
if (x == "1") {
document.getElementById("total").value = "1000";
}
else if (x == "2") {
document.getElementById("total").value = "1250";
}
else if (x == "3") {
document.getElementById("total").value = "1500";
}
}
Add onchange to the select tag as per below snippet:
<select name="opciones" id="opciones" onchange="formtotal()">
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
</select>
https://jsfiddle.net/fghxhtmk/ - Working fine. Please check.
EDIT: Added "value" to each option tag.
One clear mistake I can see is your use of the equality operator
document.formulario.opciones.value = "1"
Should be
document.formulario.opciones.value == "1"
Due to this, your first if statement is always going to be evaluated as true.
Related
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>
In my html file I have 2select boxes and 4 input text boxes.
From the first select you can choose how many numbers (textboxes) would you like to use.
From the second select you can choose a mathematical operation (+,-,*,/)
According to users choice in first select, number of input boxes will appear.
Now you add numbers to these inputs and based on what you have selected and what you have in inputs, the result should appear in a particular div.
Then, when I change anything the result should be updated.
This is what I have so far:
First select:
<select id="quantity" name="qua" onchange="selectQuantity(this.value)">
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
<option value="4">4</option>
</select>
first select js:
function selectQuantity(selectedValue){
var e = document.getElementById("quantity");
var quantity = e.options[e.selectedIndex].value;
if ( quantity==='1') {
$('#nt').fadeIn();
} else if ( quantity==='2') {
$('#nt').fadeIn();
$('#nt1').fadeIn();
} else if ( quantity==='3') {
$('#nt').fadeIn();
$('#nt1').fadeIn();
$('#nt2').fadeIn();
} else {
$('#nt').fadeIn();
$('#nt1').fadeIn();
$('#nt2').fadeIn();
$('#nt3').fadeIn()
}
}
Second select html:
<select id="operation" name="ope" onchange="selectOperation(this.value)">
<option value="+">+</option>
<option value="-">-</option>
<option value="*">*</option>
<option value="/">/</option>
</select>
Second select js:
function selectOperation(selectedValue){
var e = document.getElementById("operation");
var operation = e.options[e.selectedIndex].value;
}
Input text example:
<input type="text" id="nt" onchange="checkField(this.value)">
js:
function checkField(val)
{
}
And the result div:
<div id="result"></div>
So, where and how should I put my calculations to achieve this dynamicly updated result? To a separate function?
All of my js functions are in separate js file.
Thank you.
-FIDDLE example
Here is a suggestion:
function calculator() {
var val1 = parseInt($('#quantity').val());
var op = $('#operation').val();
for (var i = 0; i < val1; i++) {
var incr = i ? i : '';
$('#nt' + incr).fadeIn();
}
var sum = 0;
function values2() {
var internalSum = 0;
$('[id^="nt"').each(function () {
internalSum += parseInt(this.value == '' ? 0 : this.value);
});
return internalSum;
}
switch (op) {
case '+':
sum = val1 + values2();
break;
case '-':
sum = val1 - values2();
break;
case '*':
sum = val1 * values2();
break;
case '/':
sum = val1 / values2();
break;
default:
console.log('Missing parameters');
}
$('#result').html(sum);
}
$('select, input').on('change', calculator);
Demo
So, I have an object named products that has 3 attributes:
var products = [
{"name":"product1","size":"large","color":"blue","gender":"male"},
{"name":"product2","size":"small","color":"pink","gender":"female"},
{"name":"product3","size":"large","color":"green","gender":"male"},
{"name":"product4","size":"large","color":"yellow","gender":"female"},
{"name":"product5","size":"medium","color":"blue","gender":"female"},
{"name":"product6","size":"large","color":"green","gender":"male"},
{"name":"product7","size":"small","color":"yellow","gender":"male"},
{"name":"product8","size":"medium","color":"red","gender":"female"},
{"name":"product9","size":"large","color":"blue","gender":"male"},
{"name":"product10","size":"small","color":"red","gender":"female"}
];
So, if I have 3 select boxes for size, color, and gender, how would I filter these 3 to get the product name?
I'm trying to use .filter in javascript. I know how to use it in non-associative arrays. But, what about associative arrays? how do you use them?
var color = document.getElementById("color").value;
var gender = document.getElementById("gender").value;
var size = document.getElementById("size").value;
var matched = products.filter(function(e) {
return (e.color == color && e.gender == gender && e.size == size);
}).map(function(e) { return e.name; });
I wrote a JSfiddle to go with this answer. Check it out here: http://jsfiddle.net/THEtheChad/XjGPt/
JQuery
$('input').change(function(){
var names = filter();
});
function filter(){
var selected = {
size: $('#size') .val(),
color: $('#color') .val(),
gender: $('#gender').val()
};
var matches = products.filter(function(product){
return product.size == selected.size &&
product.color == selected.color &&
product.gender == selected.gender;
});
return matches.map(function(product){ return product.name });
}
Vanilla JS
var d = document;
var inputs = d.getElementsByTagName('input');
// Convert to array
inputs = Array.prototype.slice.call(inputs);
inputs.forEach(function(input){
input.addEventListener('change', function(e){
var names = filter();
});
});
function filter(){
var selected = {
size: d.getElementById('size') .value,
color: d.getElementById('color') .value,
gender: d.getElementById('gender').value
};
var matches = products.filter(function(product){
return product.size == selected.size &&
product.color == selected.color &&
product.gender == selected.gender;
});
return matches.map(function(product){ return product.name });
}
Not as elegant as Barmar's code, I implemented 2 out of the 3 dropboxes and left a bit of work for you as well ;)
<html>
<head>
<script>
var products = [
{"name":"product1","size":"large","color":"blue","gender":"male"},
{"name":"product2","size":"small","color":"pink","gender":"female"},
{"name":"product3","size":"large","color":"green","gender":"male"},
{"name":"product4","size":"large","color":"yellow","gender":"female"},
{"name":"product5","size":"medium","color":"blue","gender":"female"},
{"name":"product6","size":"large","color":"green","gender":"male"},
{"name":"product7","size":"small","color":"yellow","gender":"male"},
{"name":"product8","size":"medium","color":"red","gender":"female"},
{"name":"product9","size":"large","color":"blue","gender":"male"},
{"name":"product10","size":"small","color":"red","gender":"female"}
];
function checkValidOption(){
var color_chosen = document.getElementById("color").value;
var size_chosen = document.getElementById("size").value;
var result = "";
//only if both options were chosen
if (color_chosen !== "empty" && size_chosen != "empty"){
for(var i=0; i<products.length; i++){
if(products[i].size == size_chosen && products[i].color == color_chosen){
result = products[i].name;
break;
}
}
document.getElementById('result').innerHTML = result;
}
}
</script>
</head>
<body>
<div id="wrapper">
<select id="size" name="size" onchange="checkValidOption();">
<option value="empty"/>
<option value="small">small</option>
<option value="medium">medium</option>
<option value="large">large</option>
</select>
<select id="color" name="color" onchange="checkValidOption();">
<option value="empty"/>
<option value="red">red</option>
<option value="yellow">yellow</option>
<option value="blue">blue</option>
<option value="green">green</option>
<option value="pink">pink</option>
</select>
</div><!--wrapper-->
<div id="result"></div>
</body>
</html>
I want be able to capture to name=formdesc an option value that is text and not numbers, but I need numbers to calculate price point below. Is there a way to change it, so that it calculates properly (below JS) and capture option values as text only instead numbers (HTML)?
Sample of what I need:
<select id="apparelType" name="formdesc">
<option selected="selected" value="na">Select</option>
<option value="tshirt">T-Shirt</option>
BUT Breakes my JS!
HTML: (what I have now)
<select id="apparelType" name="formdesc">
<option selected="selected" value="na">Select</option>
<option value="0">T-Shirt</option>
<option value="1">Shorts</option>
<option value="2">Hat</option>
<option value="3">Bag</option>
</select>
<input id="numb" type="number" name="formterm">
<id="tot"><Total: $0.00 >
JS:
<script type="text/javascript">// <![CDATA[
//
$(document).ready(function(){
$('#numb').keyup(function(){
var appVal = new Array();
appVal[0] = 15; <--[tshirt]
appVal[1] = 20;
appVal[2] = 25;
appVal[3] = 30;
var cost = 0;
var fmapVal = $('#apparelType').val();
if (fmapVal == 'na')
{ alert ('Please select an apparel type.');
}
else
{
cost = appVal[fmapVal];
};
//alert(cost);
var getNumb = $('#numb').val();
var baseTotal = cost * getNumb;
var getTax = baseTotal * .06;
var getTotal = baseTotal + getTax;
$('#tot').html('Total: $' + getTotal.toFixed(2));
$('#formbal').val(getTotal.toFixed(2));
});
});
// ]]></script>
<form>
<select id="apparelType" name="apparelType">
<option selected="selected" value="na">Select</option>
<option value="0">T-Shirt</option>
<option value="1">Shorts</option>
<option value="2">Hat</option>
<option value="3">Bag</option>
</select>
<label for="numb">Total: <span>$</span></label>
<input id="numb" type="number" name="formterm" value="0.00" >
<input id="pretaxTotal" type="hidden" value="0.00" >
<br>
<textarea id="formdesc" name="formdesc" rows="12" cols="20"></textarea>
</form>
<script type="text/javascript">
$('#apparelType').change(function(){
var apparelType = $('#apparelType');
var fmapVal = apparelType.val();
if (fmapVal == 'na') {
alert('Please select an apparel type.');
} else {
var appVal = [ 15, 20, 25, 30 ];
var description = apparelType.find('option:selected').text();
var cost = appVal[fmapVal];
var pretaxTotal = parseInt($('#pretaxTotal').val());
var subtotal = pretaxTotal + cost;
var updatedTotal = ( subtotal * 1.06 ).toFixed(2);
$('#pretaxTotal').val(subtotal);
$('#numb').val(updatedTotal);
$('#formdesc').append(description + '\n');
}
});
/* The following code is cosmetic. Makes dollar sign appear to be inside the input field */
$('label > span').css('position','relative').css('left','20px').css('font-size','80%');
$('input[type=number]').css('padding-left','15px');
</script>
If you need to take option name then val is not what you need. Instead try this:
var optionName = $('#apparelType').find('option:selected').text();
Hope I understood you correctly (although it's hard).
Could use a function with a case statement to get the cost from passed text strings:
function getVal(value) {
switch(value) {
case 'tshirt':
cost = 15;
break;
case 'shorts':
cost = 15;
break;
case 'hat':
cost = 15;
break;
case 'bag':
cost = 15;
break;
default:
cost = 'Please select an option...';
break;
}
return cost;
}
Then in your if statement use cost = getVal(fmapVal);.
How can I make it so Jquery checks that ESNStart and ESNEND in the HTML form are in the same range otherwise it throws an alert saying that both numbers need to be in the same range to the user after typing in the value for ESNEnd ??
I still don't understand how I could also make it so ESNList gets checked for all its multiple values entered in the text field to be in the same range otherwise it also throws an alert to the user to enter a number in the same range as shown by the if statements ? A fiddle demonstrating this would help me learn so much , thanks a bunch !
<html>
<head>
<script type="text/javascript" src="jquery/jquery-1.8.3.js"></script>
<script type="text/javascript">
$(function() {
$(":text").css("border", "2px solid red");
$(":text").keyup(function() {
var enteredData = $(this).val()
console.log(enteredData);
if (enteredData == "") {
$(this).css("border", "2px solid red");
} else {
$(this).css("border", "inherit");
}
if ($(this).attr("id") == "ESNList") {
esnList = parseInt(enteredData);
switch (true) {
case (esnList >= 986329 && esnList <= 999999):
$("#ddl_StxName").val("stx2");
$("#ddl_rtumodel").val("globalstar");
break;
case (esnList >= 660000 && esnList <= 699999):
$("#ddl_StxName").val("mmt");
$("#ddl_rtumodel").val("globalstar");
break;
case (esnList >= 200000 && esnList <= 299999):
$("#ddl_StxName").val("stm3");
$("#ddl_rtumodel").val("stmcomtech");
break;
case (esnList >= 1202114 && esnList <= 1299999):
$("#ddl_StxName").val("smartone");
$("#ddl_rtumodel").val("globalstar");
break;
}
}
});
});
</script>
</head>
<body>
<form id="provision">ESNList:
<input type="text" id="ESNList" name="ESNList" size="30" />
<br />ESN Start:
<input type="text" id="ESNStart" name="ESNStart" size="10" />
<br />ESN End:
<input type="text" id="ESNStart" name="ESNStart" size="10" />
<br />UnitName:
<input type="text" id="STxName" name="STxName" size="30" />
<br />Unit Model:
<select name="STxName" id="ddl_StxName">
<option value="stx2">STX2</option>
<option value="stm3" selected>STM3</option>
<option value="acutec">Acutec</option>
<option value="trackpack">Trackpack</option>
<option value="mmt">MMT</option>
<option value="smartone">Smartone</option>
<option value="smartoneb">SmartOneB</option>
</select>
<br />RTU Model Type:
<select name="rtumodel" id="ddl_rtumodel">
<option value="globalstar">GlobalStar</option>
<option value="both">Both</option>
<option value="comtech">Comtech</option>
<option value="stmcomtech">STMComtech</option>
</select>
<br />
<input type="submit" value="submit" />
</form>
</body>
</html>
I created some methods that seem to work, although I haven't created groups of numbers that are out of range.
I strongly suggest you don't allow user to enter comma separated lists as it will be hard to point to user the invalid entries. It would be a lot cleaner having each number in it's own input. You can easily add a button for "Add new number" and create a new input for it.
I used arrays to store ranges and the values for the valid range that get changed for other fields. This module is not trivial and suggest you create a testing sandbox with a wide variety of numbers you can test with.
$('#ESNList').keyup(function(){
var enteredData = $(this).val();
$(this).removeClass('valid');
if( enteredData == ''){
return;
}
if(hasMultipleValues(enteredData)){
var range=rangeCheckMultipleNumbers(enteredData)
if( range===false){
log('Numbers not in same range');
return;
} else{
setRangeValues(range);
$(this).addClass('valid');
}
}
var rangeIdx = getRangeIndex(enteredData);
if(rangeIdx===false){
log('Number not in range');
}else{
setRangeValues(rangeIdx);
$(this).addClass('valid');
}
});
function hasMultipleValues( str){
/* second test for a singel entry with comma at end*/
return str.indexOf(',') !=-1 && str.indexOf(',') != str.length-1;
}
var ranges = [
[986329, 999999],
[660000, 699999],
[200000, 299999],
[1202114, 1299999]
];
var rangeText = [
["stx2", "globalstar"],
["mmt", "globalstar"],
["stm3", "stmcomtech"],
["smartone", "globalstar"]
]
/* returns range index if all in same range, otherwise returns false*/
function rangeCheckMultipleNumbers(str) {
var nums = str.split(',');
var rangeMatch = true; /* clean array to remove empty values if extra commas*/
nums = $.grep(array, function(item, index) {
return parseInt(item);
});
var groupRange = getRangeIndex(nums[0]);
if(nums.length > 1) {
for(i = 1; i < nums.length; i++) {
if(!checkSameRange(nums[i - 1], nums[i])) {
rangeMatch = false;
}
}
}
return rangeMatch ? groupRange : false;
}
function setRangeValues(rangeIndex) {
$("#ddl_StxName").val(rangeText[rangeIndex][0]);
$("#ddl_rtumodel").val(rangeText[rangeIndex][1]);
}
function checkSameRange(num1, num2) {
return getRangeIndex(parseInt(num1, 10)) == getRangeIndex(parseInt(num2, 10));
}
/* returns false if out of range, otherwise returns range index*/
function getRangeIndex(num) {
var idx = false;
$.each(ranges, function(i, range) {
if(num >= range[0] && num <= range[1]) {
idx = i;
return false;
}
});
return idx;
}
DEMO: http://jsfiddle.net/hXsQ8/1/