I am trying to make a dropdown choice populate multiple selections, but not as an input field.
Here is an example as input fields, but I am not sure how to alter this to make just text on a page via [strong] / [div] or something.
http://jsfiddle.net/zunrk/
var ids = new Array();
var use = new Array();
var ful = new Array();
ids[0] = "";
use[0] = "";
ful[0] = "";
ids[1] = 6;
use[1] = "bsmith";
ful[1] = "Buddy Smith";
ids[2] = 2;
use[2] = "lsmith";
ful[2] = "Libbie Smith";
ids[3] = 4;
use[3] = "asmith";
ful[3] = "Andy Smith";
function Choice() {
//x = document.getElementById("users");
y = document.getElementById("selectUsers");
//x.value = y.options[y.selectedIndex].text;
document.getElementById("ids").value = ids[y.selectedIndex];
document.getElementById("use").value = use[y.selectedIndex];
document.getElementById("ful").value = ful[y.selectedIndex];
}
<form name="form1" method="post" action="">
<select id="selectUsers" name="users" onChange='Choice();'><option> </option>
<option value="1">bsmith</option>
<option value="2">lsmith</option>
<option value="3">asmith</option>
</select>
<p>ids <input type="text" id="ids" name="id" ></p>
<p>use <input type="text" id="use" name="username" ></p>
<p>ful <input type="text" id="ful" name="full_name" ></p>
</form>
You can use any element instead of <input />, for example a <span />. The difference is you set its .innerHTML[1], not .value, so use
<p>ids <span id="ids"></span></p>
and
document.getElementById("ids").innerHTML = ids[y.selectedIndex];
to set the HTML of an element instead of value of an input.
http://jsfiddle.net/zunrk/171/
[1] innerText/textContent would be a better choice, but it could introduce unnecessary complexity
use innerHtml property of the dom element
document.getElementById("ids").innerHTML = ids[y.selectedIndex];
Details:
http://www.w3schools.com/jsref/prop_html_innerhtml.asp
If you want to initialize the array the way you have done then instead of setting each array item individually you can set it as below.
var ids = new Array();
var use = new Array();
var ful = new Array();
ids=["",6,2,4];
use=["","bsmith","lsmith", "asmith"];
ful=["","Buddy Smith","Libbie Smith", "Andy Smith"]
Other than this my answer is not much different than what pawel suggested, but its a bit of a cleaner solution... its not great code by any mean but it's a good piece considering that you are beginner and i wouldn't like to make it too complex. Enjoy coding :) => http://jsfiddle.net/zunrk/172/
Related
I am wondering on how to dynamically set JS values. To better understand what I am trying to accomplish, here's a php example:
$first;
$second;
$third;
$my_array = ('first' => 'val_1','second' => 'val_2','third' => 'val_3');
foreach ($my_array as $key => $value){
$$key = $value;
}
let's say you have a ton of input boxes with a unique ID in html form and you want to use the id as a global variable using jquery or js, that's when I am a bit confused how I can dynamically assign already defined global variables from an Each statement.
The type of html I want to identify through js.
<input id='first' value='val_1'>
<input id='second' value='val_2'>
<input id='third' value='val_3'>
The JS/jquery code
var first;
var second;
var third;
$('input').each(function(){
var item_id = $(this).attr('id');
var item_value = $(this).attr('value');
/* now what... */
});
in the php example the extra dollar sign make the dollar to say I want to populate a variable named like the variable stored in $key. I am wondering if the same can be accomplished with JS or jquery.
The purpose is to manage the amount of values only by adding inputs to the HTML form without the need for altering the JS code considerably.
This isn't good programming style in PHP or JavaScript. Just use an array instead:
var values = [];
$('input').each(function() {
var item_id = $(this).attr('id');
var item_value = $(this).attr('value');
values[item_id] = item_value;
});
console.log('first = ' + values['first'] + ', second = ' + values['second']);
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<label for="first">First: </label>
<input id="first" type="text" value="hello" />
<label for="second">Second: </label>
<input id="second" type="text" value="world!" />
<label for="third">Third: </label>
<input id="third" type="text" />
You can use eval function
var first;
var second;
var third;
$('input').each(function(){
var item_id = $(this).attr('id');
var item_value = $(this).attr('value');
eval(item_id+'='+item_value);
});
For example
var v1 = 'first';
var v2 = 'second';
var val1 = 10;
var val2 = 20;
var first;
var second;
eval(v1+'='+val1);
eval(v2+'='+val2);
console.log('first='+first,'second='+second);
I am a beginner programmer and I want to make this work but it doesn't. Could you Please help me and explain what's wrong? For example, if I enter under 20, I want it to tell me how long it will take me to walk to whatever planet I selected. Most of it is figuring out how to have the code store whatever option the user selects and then apply it to the age and use the data to calculate it. Thank you!
<legend>basic info</legend>
<p> What is your destination?
<select onchange = "selectDestination(this.value)">
<option value="mercury">Mercury</option>
<option value="venus">Venus</option>
<option value="mars">Mars</option>
<option value="jupiter">Jupiter</option>
<option value="saturn">Saturn</option>
<option value="uranus">Uranus</option>
<option value="neptune">Neptune</option>
<option value="pluto">Pluto</option>
</select>
<script type="text/javascript">
var planets = new Array();
planets['mercury'] = 48000000;
planets['venus']=25000000
planets['mars']=25000000
planets['jupiter']=33900000
planets['saturn']=365000000
planets['uranus']=1200000000
planets['neptune']=2600000000
planets['pluto']=2800000000
function selectDestination(selectedValue) {
window.alert(selectedValue + " distance=" + planets[selectedValue]);
}
</script>
</p>
<p>
<label>how old are you?</label>
<form id="form" onsubmit="return false;">
<input type="number" id="userInput">
<input type="submit" onclick="age()">
</form>
<script type="text/javascript">
function age()
{
var input = document.getElementById("userInput");
alert(input);
}
if(age<20);
{
alert("YOU ARE UNDER 20");
var runSpeed=6.3;
var walkSpeed=2.1
var water = 1.5;
var calories = 2500;
var runTime = planets[selectedValue]/runSpeed;
var runDays = runTime/24
document.write("it will take "+runTime+" hours and "+runDays+" days to make it to"+selectedValue);
}
if(21<age>45) {
alert("YOU ARE AT YOUR PHYSICAL PEAK");
var runSpeed=8.3;
var walkSpeed=3.1;
var water = 2;
var calories = 3000;
var runTime = planets[selectedValue]/runSpeed;
var runDays = runTime/24;
document.write("it will take "+runTime"hours and"+runDays+"days to make it to"+selectedValue);
}
if(age<45){
alert("YOU ARE PROBABLY TOO OLD TO TAKE THIS TRIP");
var runSpeed=5.3;
var walkSpeed=1.1;
var water=1.5;
var calories=3000;
var runTime = planets[selectedValue]/runSpeed;
var rundays = planets[selectedValue]/24;
document.write("it will take "+runTime"hours and"+runDays+"days to make it to"+selectedValue);
}
</script>
</p>
This code here doesn't work.
var planets = new Array();
planets['mercury'] = 48000000;
planets['venus']=25000000
planets['mars']=25000000
planets['jupiter']=33900000
planets['saturn']=365000000
planets['uranus']=1200000000
planets['neptune']=2600000000
planets['pluto']=2800000000
What you're declaring is an Array, and what you want to push into them is objects.
What you ideally want planets to look like is var planets = [ {planet: 'mercury', distance: 48000000}, {planet: 'venus', distance: 25000000 }, ... ]
Right now, nothing is happening because your syntax is looking for an object with a key of mercury or venus and not finding anything.
The next thing you should do is be able to console.log() whatever the user inputs as an age. Make sure your function age() accepts a parameter, so it might look more like age(val)
Once you're console.log() logs the age input by the user, you should be pretty close. All you have to do after that is grab the planet the user selected, and you can do that by looping through your planets array and matching what the user selected with what is in the array. Something like planets.filter(planet => planet.indexOf(planetUserSelected) !== -1) will give you back the object you're looking for, and you can console.log() that value and go from there.
the following values are to calculate the user entered values, these are calculated and passed to the text field,
if(computer && monitor && tv && laptop && cell)
{ // getting the text field the values and calculated
var valueCom = document.getElementById("computer").value ;
var valueMon = document.getElementById("monitor").value ;
var valueTv = document.getElementById("tv").value ;
var valueLap = document.getElementById("laptop").value ;
var valueCel = document.getElementById("cell").value;
var finalCom = valueCom * 0.1818937134 ;
var finalMon = valueMon * 0.056842 ;
var finalTv = valueTv * 0.056842 ;
var finalLap = valueLap * 0.090947 ;
var finalCel = valueCel * 0.045473 ;
var totalTonnes = finalCom + finalMon + finalTv + finalLap + finalCel;
var totalCarbon = totalTonnes * 1 ;
var totalTree = totalTonnes * 17.1969 ;
var totalPetrol = totalTonnes * 286.396 ;
var totalPlastic = totalTonnes * 646.421 ;
// pass this above four values to the textfield
}
<input type="text" name="carbon" >
<input type="text" name="tree" >
<input type="text" name="petrol" >
<input type="text" name="plastic" >
// field to pass values here
how to pass this values using java script to the text field. can anyone help me please
you want to add id to text field,
<input type="text" name="carbon" id="carbon">
<input type="text" name="tree" id="tree">
<input type="text" name="petrol" id="petrol">
<input type="text" name="plastic" id="plastic">
then after javascript,
document.getElementById("carbon").value=totalCarbon;
document.getElementById("tree").value=totalTree;
document.getElementById("petrol").value=totalPetrol;
document.getElementById("plastic").value=totalPlastic;
and also you can use to value set by name,
document.getElementsByName("plastic")[0].value = totalPlastic;
......
or,
document.getElementById("plastic").setAttribute('value',totalCarbon);
.....
Assign your resultant text field with id="result" or anything. Then, you can put your result as $(#result).val(yourCalcultedResult);
set the value property
document.getElementById("carbon").value = totalCarbon;
document.getElementById("tree").value = totalTree;
document.getElementById("petrol").value = totalPetrol;
document.getElementById("plastic").value = totalPlastic;
and set the ids to the respective elements
<input type="text" name="carbon" id="carbon" >
<input type="text" name="tree" id="tree" >
<input type="text" name="petrol" id="petrol" >
<input type="text" name="plastic" id="plastic" >
Or if you still want to use names only, then make it
document.getElementsByName("carbon")[0].value = totalCarbon;
document.getElementsByName("tree")[0].value = totalTree;
document.getElementsByName("petrol")[0].value = totalPetrol;
document.getElementsByName("plastic")[0].value = totalPlastic;
document.getElementsByName("carbon")[0].value = totalCarbon;
document.getElementsByName("tree")[0].value = totalTree;
document.getElementsByName("petrol")[0].value = totalPetrol;
document.getElementsByName("plastic")[0].value = totalPlastic;
If your controls are in a form, like:
<form>
<input type="text" name="carbon">
<input type="text" name="tree">
<input type="text" name="petrol">
<input type="text" name="plastic">
...
</form>
then you can get a reference to the form and access them as named properties of the form, e.g.
var form = document.forms[0];
form.carbon.value = totalCarbon;
form.tree.value = totalTree;
...
Just make sure you don't give form controls a name that is the same as a form property, like submit or name, as these will shadow the form's default properties of the same name (so you can't call form.submit() or access the form's name, if it has one).
//globally i declared carbon, tree, petrol, plastic
document.getElementById("carbon").value = carbon ;
document.getElementById("tree").value = tree ;
document.getElementById("petrol").value = petrol ;
document.getElementById("plastic").value = plastic ;
I created multiplied input fields:
<div class="form-text-field first-name field-group">
<input data-index="1" type="text" id="firstName1" class="signup-input firstName" name="first[1]" placeholder="">
</div>
<div class="form-text-field email field-group">
<input type="text" data-index="1" id="inputMail1" class="signup-input text-value ignore" name="email[1]" placeholder="${message(code:"signup.redesign.placeholder.eg.email")}"/>
<span class="common-sprite disNone sign-up-cross first clone"></span>
</div>
I have a code in the JS file which clone every input.
I have to create arrays from the values of the inputs (one for the email, and one for the first name).
Here is the function:
var arrEmail = []
var arrName = []
function add() {
var obj = {};
var partner = {}
$('.email input[type="text"]').each(function() {
obj[this.data-index] = this.value;
});
arrEmail.push(obj)
$('.first-name input[type="text"]').each(function() {
partner[this.data-index] = this.value;
});
arrName.push(partner)
console.log(arrEmail[0])
}
I didn't succeed to get the arrays in this code. How do I fix it?
You have some mistakes.
Wrong syntax in line $('.email input[type="text"]').each(function({. You forgot to close bracket.
I don't understand why you tried get value this strange manner. You included jQuery. Use it!
I fix your code.
var arrEmail = [];
var arrName = [];
function add() {
var obj = {};
var partner = {};
$('.email input[type="text"]').each(function(item) {
obj[$(this).data('index')] = $(this).val();
});
arrEmail.push(obj);
$('.first-name input[type="text"]').each(function() {
obj[$(this).data('index')] = $(this).val();
});
arrName.push(obj);
console.log(arrEmail);
console.log(arrName);
}
$('#test').on('click', add);
jsFiddle demo
Upd #1
Haven't shown all conditions. Fixed it.
Use $(this).data('index') instead of this.data-index
You can handle this with a single array:
var myUsers= [];//this might be object that you store the user information
$('.first-name input[type="text"]').each(function(item) {
//first create the user information
var myUser = new Object();
myUser.Username = $(this).val();
myUser.Email= $(this).next().val();
//then add the user information to the myUsers array
myUsers.push(myUser );
});
Hi I am NewBee in Javascript. This is my second week.
Below is the code that has a form with three input fields.
The relationship of the fields is:
the second field is twice the value of the first field
the third field is the square of the first field
I have managed to do the above but i am not able to do the below :
If a user enters a value in the second or third field, the script should calculate the appropriate value in the other fields. Currently the code works well ONLY if I enter the value in the first field.
I hope I explained well in other words : how do I enter say 144 in the last textbox and the other 2 textboxes show 12 and 24 respectively. Or If I enter 24 first and first and the third text boxes show 12 and 144.
Thanks
Vipul
<html>
<head>
<script>
window.onload = init;
function init() {
var button = document.getElementById("usrButton");
button.onclick = save;
onkeyup = doMath;
function doMath(){
var base = document.getElementById("base").value;
var baseNumber_timesTwo = document.getElementById("baseNumber_timesTwo").value = (base*2);
var baseNumber_square = document.getElementById("baseNumber_square").value = (base*base) ;
}
}
</script>
</head>
<body>
<form>
<input type="text" name="base" id="base" onkeyup= "doMath()">
<br><br>
<input type="text" name="baseNumber_timesTwo" id="baseNumber_timesTwo" onkeyup= doMath()>
<br><br>
<input type="text" name="baseNumber_square" id="baseNumber_square" onkeyup= doMath()> <br><br>
</form>
</body>
</html>
take a look at the code below:
<html>
<head>
<script>
window.onload = init;
var init = function(){
var button = document.getElementById("usrButton");
button.onclick = save;
onkeyup = doMath;
}
var doMathbase = function(){
console.log('here');
var base = document.getElementById("base").value;
var baseNumber_timesTwo = document.getElementById("baseNumber_timesTwo").value = (base*2);
var baseNumber_square = document.getElementById("baseNumber_square").value = (base*base) ;
}
var doMathBase2Time = function(){
var baseNumber_timesTwo = document.getElementById("baseNumber_timesTwo").value;
var base = document.getElementById("base").value = (baseNumber_timesTwo/2);
var baseNumber_square = document.getElementById("baseNumber_square").value = (base*base) ;
}
</script>
</head>
<body>
<form>
<input type="text" name="base" id="base" onkeyup= "doMathbase()">
<br><br>
<input type="text" name="baseNumber_timesTwo" id="baseNumber_timesTwo" onkeyup= "doMathBase2Time()">
<br><br>
<input type="text" name="baseNumber_square" id="baseNumber_square" onkeyup= "doMathBaseSquare()">
<br><br>
</form>
</body>
You need to bind another function to the second and third field. I did it to the second. Now if you entered a number in the second field it return the 'base' number and the square of the base.
Try do it for the third :)
This should fit your needs:
Fiddle
//declaring those earlier saves you to get those by ID every
//time you call "doMath()" or something else
var base = document.getElementById("base");
var baseNumber_timesTwo = document.getElementById("baseNumber_timesTwo");
var baseNumber_square = document.getElementById("baseNumber_square");
function clearUp() {
base.value = "";
baseNumber_timesTwo.value = "";
baseNumber_square.value = "";
}
function doMath() {
//check which of the fields was filled
if(baseNumber_timesTwo.value){
base.value = baseNumber_timesTwo.value / 2;
}
if(baseNumber_square.value){
base.value = Math.sqrt(baseNumber_square.value);
}
//fill other fields according to that
baseNumber_timesTwo.value = (base.value*2);
baseNumber_square.value = (base.value*base.value) ;
}
As you see: There is no need to write more than one arithmetic function if you make sure that only one value is given at the time of evaluation (this is achieved by the cleanUp()
method)
However there are still some flaws in this solution! Since you are a js beginner I would suggest you to read the code and think about possible solutions for those problems as a little exercise :-)
- You cannot enter a 2 (or more) digit number in any field, why not? What do you have to change in order to allow such numbers as input?
- Why is it better (in this case!) to set the values to " " instead of '0' in the cleanUp function? Why does the code break when you try using '0' instead of "" ?
- Why does doMath() only check for values in the last two field (baseNumber_timesTwo and baseNumber_square) while ignoring the 'base' field?
Greetings, Tim