Copying text to two inputs with the same ID - javascript

When I wrote something in the first input, second input showed it, but:
a) What if i want see text from input "2" showed in input "3"?
HTML:
<input id="1" type="text" oninput=al() /></br>
<input id="2" disabled="disabled" ></br>
<input id="3" disabled="disabled">
JS:
function al() {
var a = document.getElementById("1").value;
var result = a;
var ab = document.getElementById("2");
ab.value=a;
}
b) What if I want to see text from input "1" in two inputs named "2"?
HTML:
<input id="1" type="text" oninput=al() /></br>
<input id="2" disabled="disabled" ></br>
<input id="2" disabled="disabled">
JS:
function al() {
var a = document.getElementById("1").value;
var result = a;
var ab = document.getElementById("2");
ab.value=a;
}

Answer A: To show the same value in an input with ID 2 and an input with ID 3:
function al() {
var a1 = document.getElementById("1").value;
var a2 = document.getElementById("2");
var a3 = document.getElementById("3");
a2.value = a3.value = a1;
}
Answer B: Using elements with the same ID is wrong and will result in an invalid HTML document. To achieve your goal, you can set both elements with a certain class (classA at the example below), then you can use document.querySelectorAll which returns an array of elements, and then set their value with an index [0] and [1]:
<input id="1" type="text" oninput=al() /></br>
<input class='classA' disabled="disabled" ></br>
<input class='classA' disabled="disabled">
function al() {
var a = document.getElementById("1").value;
var result = a;
var ab = document.querySelectorAll("[class='classA']");
ab[0].value = ab[1].value = a;
}

First of all, you can't have two element with the same ID.
Second to copy from one to another, it's better use the keyDown, keyUp or onchange events.
E.g.
<input type="text" id="1" onchange="copypaste()"/>
<input type="text" id="2"/>
function copypaste() {
var first = document.getElementById("1")
var second = document.getElementById("2")
second.value = first.value
}

Related

applying onkeyup function simultaneously on multiple textboxes

Suppose I have a column of 1+7 text box. Name of the first box is mm1 and the other boxes are respectively dd1, dd2, ...., dd7. I want to write a javascript function so that all the values in the textboxes dd1, dd2,...,dd7 are multiplied by N if I put N in the first textbox namely mm1. I can write the javascript function , but how to make its effect in all boxes simultaneously? I have tried the following code. But it can effect only one box depending on the value of $i. If we can create a loop for $i taking values 1 to 7, then perhaps the problem will be solved. Any clue please.
<?php $i=3?>
<input type="text" size="1" id="mm1" name="mm1"
maxlength="2" onfocus="this.select()"
onkeyup="gft('dd<?php echo $i?>', 'mm1')"
>
Try this, use class to logically group elements...
$('.mult').each(function(i,v){
var tt = parseFloat($(this).val());
$(this).attr('data-val',$(this).val());
});
$('.myVal').on('keyup',function(e){
var t = $(this).val();
if(!t) t = 0;
$('.mult').each(function(i,v){
if(t>0){
var tt = parseFloat($(this).attr('data-val')) * t;
$(this).val(tt);
}
});
});
Find working fiddle here
function gft(x){
n = 5;
c = x * n;
textInputs[0].value = c;
textInputs[1].value = c;
textInputs[2].value = c;
}
var textInputs = document.querySelectorAll('input[type=text]');
//this eventlistener is made to listen for key movement on all text fields that are of type text
for(i=0;i<textInputs.length;i++){
textInputs[i].addEventListener('keyup',function(){
//gft will execute an equation whenever one of these fields change
//also, it will change all the values inside the textfield simultaneously
gft(this.value);
},false);
}
I made a JSFiddle using only JavaScript (no jQuery):
HTML
<input type="number" onkeyup="multiply(this)"/>
<input type="number" value="1" class="multiply-this"/>
<input type="number" value="2" class="multiply-this"/>
<input type="number" value="3" class="multiply-this"/>
<input type="number" value="4" class="multiply-this"/>
<input type="number" value="5" class="multiply-this"/>
<input type="number" value="6" class="multiply-this"/>
<input type="number" value="7" class="multiply-this"/>
JavaScript
function multiply(first){
var value = +first.value;
var textboxes = document.getElementsByClassName("multiply-this");
for(var i = 0; i < textboxes.length; i++){
var textbox = textboxes[i];
if(textbox.attributes.initialValue){
textbox.value = textbox.attributes.initialValue.value;
} else {
textbox.setAttribute("initialValue", textbox.value);
}
textbox.value = +textbox.value * value;
}
}
window.onload = function(){
var textboxes = document.getElementsByClassName("multiply-this");
for(var i = 0; i < textboxes.length; i++){
var textbox = textboxes[i];
textbox.onkeyup = function(){
this.setAttribute("initialValue", this.value);
}
}
}
I added functionality to remember what value the textboxes had at first. But you can still change it if you specifically change one of the 7 textboxes that gets multiplied.
EDIT
You can also add this if you want it to multiply after changing one of the values:
textbox.onblur = function(){
multiply(document.getElementById("multiplyer"));
}
JSFiddle

radio button .checked to perform a math expression using user input javascript

I have two textboxes where a user enters a number into each one and then clicks a radio button to select the mathematical operation to be performed upon the calculate button.This is for a homework assignment, so only javascript and html
are being used, no jquery. Currently when I click the button, nothing appears to happen and I am getting no console errors...
HTML
<div>
<p>Enter two numbers, select a math, then click the button.<br>
The answer will be shown below.</p>
<form>
1st number: <input type="text" name="number1">
2nd number: <input type="text" name="number2">
<br>
<input type="radio" name="add">Add <br>
<input type="radio" name="subtract">Subtract <br>
<input type="radio" name="multiply">Multiply <br>
<input type="radio" name="division">Division <br>
<input type="button" name="calc" onclick="calculate()" value="Calculate"> <br>
</form>
<p id="math_res"></p>
</div>
Javascript
function calculate(){
var num1 = parseInt("document.getElementsByName('number1').value;", 10);
var num2 = parseInt("document.getElementsByName('number2').value;", 10);
var add = document.getElementsByName("add");
var sub = document.getElementsByName("subtract");
var multi = document.getElementsByName("multiply");
var divis = document.getElementsByName("division");
var res = document.getElementById("math_res").innerHTML;
if (add.checked == true){
res = num1 + num2;
}
else if ( sub.checked == true){
res = num1 + num2;
}
else if (multi.checked == true){
res = num1 * num2;
}
else if (divis.checked == true){
res = num1 / num2;
}
}
I thought my function would take the input from the two text boxes and convert the user input to an integer and assign them to variable num1 and num2. Then assign each radio button to a variable to reduce typing of document.get...
that each if statement would check to see if that radio but was checked. If true perform calculation if false move to next if statement and display the results in a paragraph element.
where did I go wrong?
You have a couple of issues.
getElementsByName returns a collection of elements, not a single element so:
var add = document.getElementsByName("add");
will assign undefined to add. But you don't need to use it, just reference the controls as named properties of the form. Pass a reference to the button from the listener:
<input type="button" name="calc" onclick="calculate(this)" value="Calculate">
Then in the function get the form:
function calculate(element) {
var form = element.form;
Now just do:
var num1 = parseInt(form.number1.value, 10);
and so on, which also fixes the other issues you have with referencing the controls.
Also, radio buttons need to have the same name so that only one is selectable, so as Felix says, give them all the same name and differentiate on value (or class or some other attribute value). You'll need to loop over them to find out the operation to perform, so the HTML might be:
<input type="radio" name="operation" value="add">Add <br>
<input type="radio" name="operation" value="subtract">Subtract <br>
<input type="radio" name="operation" value="multiply">Multiply <br>
<input type="radio" name="operation" value="division">Division <br>
Then to get the operation:
var radios = form.operation;
var op;
for (var i=0; i<radios.length; i++) {
if (radios[i].checked) {
op = radios[i].value;
break;
}
}
Now check the value of op to work out whether to add, subtract, etc.
Here's a quick example, I don't recommend inline scripts like this but it's handy for playing.
<form>
<input type="radio" name="operation" value="add">Add <br>
<input type="radio" name="operation" value="subtract">Subtract <br>
<input type="radio" name="operation" value="multiply">Multiply <br>
<input type="radio" name="operation" value="division">Division <br>
<input type="button" onclick="
var form = this.form;
var radios = form.operation;
var op;
for (var i=0; i<radios.length; i++) {
if (radios[i].checked) {
op = radios[i].value;
break;
}
}
form.selectedOperation.value = op || 'No operation selected';
" value="Get selected operation">
<input type="text" readonly name="selectedOperation"><br>
<input type="reset">
</form>
There are a few issues I can notice.
1.
getElementsByName returns a NodeList, which is Array-like. You need to retrieve the first element in the NodeList before accessing its value. For example,
document.getElementsByName('number1')[0].value
2.
You are passing a literal code string to parseInt. You should write something like
parseInt(document.getElementsByName('number1')[0].value, 10);
3.
The code var res = document.getElementById('math_res').innerHTML stores a reference to the innerHTML of the element. When you assign res = num1 + num2 for example, you are simply overwriting the reference, instead of actually altering the innerHTML. To correct this,
var elem = document.getElementById('math_res');
// later...
elem.innerHTML = num1 + num2;
4. You are incorrectly defining multiple radio buttons with different names. In order for the browser to render them as a "radio button group" where only one can be selected, they must have the same name, but different "value" attributes. See RobG's answer or the Plunkr below for an example of how to define the radio button group and extract its value using JavaScript.
A working version of your code is here.
Edit Please note that these are minimal edits to make your code work. RobG's answer shows a more correct way of extracting the values of form fields.
Here is my version, hope it helps you.
<!DOCTYPE html>
<html>
<body>
<div>
<p>Enter two numbers, select a math, then click the button.<br>
The answer will be shown below.</p>
<form>
1st number: <input type="text" name="number1" id = 'number1'>
2nd number: <input type="text" name="number2" id = 'number2'>
<br>
<input type="radio" name="button" id = 'add' >Add <br>
<input type="radio" name="button" id = 'substract'>Subtract <br>
<input type="radio" name="button" id = 'multiply'>Multiply <br>
<input type="radio" name="button" id = 'division'>Division <br>
<input type="button" name="calc" onclick="calculate()" value="Calculate"> <br>
</form>
<p id="math_res"></p>
</div>
<script>
function calculate(){
//Obtaining the references to the text inputs
var number1 = parseInt(document.getElementById('number1').value);
var number2 = parseInt(document.getElementById('number2').value);
//Reference of the result Box
var resultBox = document.getElementById('math_res');
resultBox.innerHTML = '';
//Reference of the radio buttons
var buttonAdd = document.getElementById('add');
var buttonSubstract = document.getElementById('substract');
var buttonMultiply = document.getElementById('multiply');
var buttonDivision = document.getElementById('division');
//Make the magic
if(buttonAdd.checked == true){
resultBox.innerHTML = number1 + number2
}
else{
if(buttonSubstract.checked == true){
resultBox.innerHTML = number1 - number2
}
else{
if(buttonMultiply.checked == true){
resultBox.innerHTML = number1 * number2
}
else{
if(buttonDivision.checked == true){
resultBox.innerHTML = number1 / number2
}
}
}
}
}
</script>
</body>

Form in Javascript return me an "undefined" alert

I'm a begginner in Javascript and I made a little form as a test. But I can't get the value of the input tags. I always get the alert as "undefined".
var id1, id2, id3, id4, id5, id6, id7, notabx, op1, op2, mu1, mu2;
var doc = document;
var id1 = doc.getElementById("1").value;
var id2 = doc.getElementById("2").value;
var id3 = doc.getElementById("3").value;
var id4 = doc.getElementById("4").value;
var id5 = doc.getElementById("5").value;
var id6 = doc.getElementById("6").value;
var id7 = doc.getElementById("7").value;
var op1 = doc.getElementById("op").value;
var op2 = doc.getElementById("op2").value;
var bx = doc.getElementById("bx").value;
function init() {
var FG = ( id1 + id2 + id3 + id4 + id5 ) / 5 ;
var FE = ( id6 * op1 ) + ( id7 * op2 );
var result = (bx * (60/100)) + (FG * (40/100)) + FE;
}
function result() {
alert(result);
}
window.onload = init();
</head>
<body>
<form>
<label for="bx">1st Cours:</label><input type="text" id="bx" value=""><p>
<br>
<p>FASE GENERAL</p>
<label for="1">Subject #1 </label><input type="text" id="1" maxlength="5" value="">
<label for="2">Subject #2 </label><input type="text" id="2" maxlength="5" value="">
<label for="3">Subject #3 </label><input type="text" id="3" maxlength="5" value="">
<label for="4">Subject #4 </label><input type="text" id="4" maxlength="5" value="">
<label for="5">Subject #5 </label><input type="text" id="5" maxlength="5" value="">
<p>FASE ESPECÍFICA</p>
<label for="6">Subject #6 </label><input type="text" id="6" maxlength="5" value=""><p>
<select name="" id="op">
<option value="0.1">0.1</option>
<option value="0.2">0.2</option>
</select>
<label for="7">Subject #7 </label><input type="text" id="7" maxlength="5" value="">
<select name="" id="op2">
<option value="0.1">0.1</option>
<option value="0.2">0.2</option>
</select>
<button onclick="result();">Calculate</button>
</form>
</div>
I'm spanish so I tried to calculate the academic results by following a method used here, don't loot at it. I'm focusing in I can not caltulate the result.
Lines like this
var id1 = doc.getElementById("1").value;
only work if the element can be found in the document. This means that either the script needs to be loaded at the bottom of the page, or you have to move this code inside the init function that you call on window.onload.
Also, the variable result is local to the init() function, which means you cannot read it outside of it. So the value that is alerted is not assigned either. You can declare result outside of the functions, so both functions can read or set it.
So in short, you script could look like this:
var result; // Make global, so both functions can reach it.
function init() {
// Var declaration is not needed if you add the `var` keyword later.
// var id1, id2, id3, id4, id5, id6, id7, notabx, op1, op2, mu1, mu2;
var doc = document;
var id1 = doc.getElementById("1").value;
var id2 = doc.getElementById("2").value;
var id3 = doc.getElementById("3").value;
var id4 = doc.getElementById("4").value;
var id5 = doc.getElementById("5").value;
var id6 = doc.getElementById("6").value;
var id7 = doc.getElementById("7").value;
var op1 = doc.getElementById("op").value;
var op2 = doc.getElementById("op2").value;
var bx = doc.getElementById("bx").value;
// Shouldn't mu1 and mu2 get a value too?
var FG = ( id1 + id2 + id3 + id4 + id5 ) / 5 ;
var FE = ( id6 * mu1) + ( id7 * mu2 );
// Remove the 'var' keyword below. You want to set the global, rather than
// declare a new local variable.
result = (bx * (60/100)) + (FG * (40/100)) + FE;
}
function showResult() {
// Alert the global result variable.
alert(result);
}
window.onload = init();
Alternatively, you could choose to do the calculation only when you click the button. Maybe that's even what you want. If you calculate it onload, the calculation will only be made with the values that are initially in the form. Any changes are not taken into account in the result.
As Anonymous mentioned in the comment, having a variable and a function both named result is asking for problems. So I renamed the function to showResult. You should change this in the HTML too, of course:
<button onclick="showResult();">Calculate</button>

Javascript finding indexOf select option

So this is what I managed to do, use a text box to add strings to my select.
How can I now use a second text box to write part of a string I created in the select with the first text box and find the indexOf the word I typed(indexOf need to appear underneath the second text box)?
Note: the simplest Javascript answer, please.
function addString(){
var addTwoSelect = document.getElementById("select");
var write = document.createElement("option");
write.text = document.getElementById("txt").value;
addTwoSelect.add(write);
}
<input type="text" id="txt"/>
<input type="button" value="add string" onclick="addString()"/>
<select id="select"><option value="0">Choose a string</option></select>
OK, so just a second input box and compute the indexOf:
function addString(){
var addTwoSelect = document.getElementById("select");
var write = document.createElement("option");
write.value = write.text = document.getElementById("txt").value;
addTwoSelect.add(write);
}
function outputIndex() {
var addTwoSelect = document.getElementById("select"),
secondBox = document.getElementById("string"),
out = document.getElementById("index");
out.innerText = addTwoSelect.value.indexOf(secondBox.value);
}
<input type="text" id="txt"/>
<input type="button" value="add string" onclick="addString()"/>
<select id="select" onchange="outputIndex()"><option value="0">Choose a string</option></select>
<input type="text" id="string" oninput="outputIndex()"/>
<output id="index"></output>
Use the value attributes of your <option>s!
var last = 0;
function addString(){
var addTwoSelect = document.getElementById("select");
var write = document.createElement("option");
write.text = document.getElementById("txt").value;
write.value = ++last;
addTwoSelect.add(write);
}
function outputIndex() {
var addTwoSelect = document.getElementById("select"),
out = document.getElementById("index");
out.innerText = addTwoSelect.value;
}
<input type="text" id="txt"/>
<input type="button" value="add string" onclick="addString()"/>
<select id="select" onchange="outputIndex()"><option value="0">Choose a string</option></select>
<output id="index"></output>

Is possible to get all the values of all the <input>s inside a div?

<div id="test">
<input type="text" value="10" size="3">
<input type="text" value="0" size="3">
<input type="text" value="25" size="3">
<input type="text" value="0" size="3">
</div>
I want a function to get all the values of the inputs. I was trying with this:
var inputs = $("test :input");
But I don't know how to go from there or even if it's correct.
Thank you
You can do this:
var inputs = new Array();
inputs = $('#test :text').map(function(){
return this.value;
}).get(0);
Or:
var inputs = new Array();
inputs = $('#test :text').each(function(){
inputs.push(this.value);
});
You can access each value like this:
alert(inputs[0]);
alert(inputs[1]);
alert(inputs[2]);
// and so on
The :text refers to inputs of type text.
$("#test :input").each(function(){
var value = $(this).attr("value"); //Save value in an array or something
});
Do you mean like this?
var values = [];
$('input').each(function(index, element){
values.push($(element).val());
});
Non-jQuery version:
var values = [];
var inputs = document.getElementById("test").getElementsByTagName("input");
for (var i = 0, len = inputs.length; i < len; ++i) {
values.push(inputs[i].value);
}

Categories

Resources