javascript copy (duplicate) text from 1 field to another - javascript

i have 20 fields
10 with name= from 1 to 10
and 10 fields with same name from 1 to 10
<input name="1" type="text">
...
<input name="10" type="text">
and 10 fields like this
<input name="1" type="text">
...
<input name="10" type="text">
so what i want is: to write in first 10 fields , and other 10 to be filled automatically
i can change names to id or add prefix to id of second group.
or its better with names .

if u change names to id 1-10 then second group id a1-a10
function populateSecondTextBox() {
document.getElementById('1').value = document.getElementById('a1').value;
}
this is for 1 only,
someone can add answer for doing all with 1 code

you want to mirror the changes like this ?
for(let i=1; i<11 ; i++){
let input = document.getElementsByName(i.toString())[0];
let mirror = document.getElementsByName(i.toString())[1];
input.onkeyup=()=>{ mirror.value = input.value; }
}

Related

how to get a number from div then multiply

my result is the following
Showing 5 to 40 of 50 entries i need to get the total entries ignoring "Showing 5 to 40 of" and keeping the number "50" insert it into input total then multiply it by 10
<div class="info" id="info">Showing 30 to 40 of 50 entries</div>
<input type="text" id="total" name="total">
<input type="text" id="total" name="x10">
This answer is with the strong assumption that the text always shows "Showing 5 to 40 of 50 entries" or a similar text, you'd also need to change the id for one of the boxes, as all id should be unique to be useable in the js code
// use js to get the value
const info = document.getElementById("info").innerHTML
// get an array of text seperated by space
const texts = info.split(" ")
// get the 2nd last character
const number = parseInt(texts[texts.length - 2])
// put those values into the input boxes
document.getElementById("total").value = number
document.getElementById("totalTimes10").value = number*10
<div class="info" id="info">Showing 30 to 40 of 50 entries</div>
<input type="text" id="total" name="total">
<input type="text" id="totalTimes10" name="x10">
Using Node.textContent property of the node to get the text content of div and then use String.split() method to extract the total entries.
const text = document.querySelector("#info").textContent.split(" ");
const entries = text[text.length - 2];
document.querySelector("#total").value = entries;
document.querySelector("#totalTimes10").value = 10 * entries;
<div class="info" id="info">Showing 30 to 40 of 50 entries</div>
<input type="text" id="total" name="total">
<input type="text" id="totalTimes10" name="x10">

Computing input field values with getElementsByClassName

I have many input fields (3 on each row), that basically do the same thing:
Input1 * Input2 = DisabledInput=result
Input3 * Input4 = DisabledInput=result
...
What would be the best way to multiply input fields on each row with js?
Doing it with getElementsById works, but that means creating several dozen IDs, even though the logic on each row is the same.
<div class="row">
<input class="input first" id="id1" type="text" name="first" oninput="calculate()" value="" placeholder="Enter number">
<input class="input second" id="id2" type="text" name="second" oninput="calculate()" value="" placeholder="Enter number">
<input class="input result" id="idResult" type="text" name="result" oninput="calculate()" value="" placeholder="Enter number">
</div>
function calculate() {
var first = document.getElementById('id1').value;
var second = document.getElementById('id2').value;
var result = document.getElementById('idResult');
var finalResult = id1 * id2;
idResult.value = Math.round(finalResult * 100) / 100;
}
I tried using
var get = function(clsName) {
return document.getElementsByClassName(clsName)[0];
};
get('result').innerHTML = +get('first').innerHTML * +get('second').innerHTML;
But it's not working. I'm just wondering what would the best approach be to problems like this? Surely not entering 50 different Ids for doing the same thing?
Update
New Solution
Using .class Attribute
See Demo 2.
If [name] is too busy of an attribute and you are concerned with possible conflicts, .class can be just as effective with this particular solution. In Demo 2 all [name] attributes are now .class attributes. The .className property is used instead of .name property. If any of your targeted elements have more than one class then use .classList.contains() property and method.
Original Solution
Using [name] Attribute
See Demo 1.
As long as your layout pattern is the same consistently
<input...> <input...> <output...>
You can have an unlimited number of input/output combos that operate independently from one another by delegating an event. The demo provided has a form tag that manages all form controls nested within it when the input event is triggered. An input event occurs whenever a form control gets data from a user by typing or selecting. The terse syntax used to reference the form tag (see first comment in demo) is from the HTMLFormElement interface. Also, instead of another input for the result, use an output tag instead, and use type='number' on inputs which will facilitate correct input. Details are commented in demo.
Note: I intentionally left that expression out of the function intentionally (it looked excessive to me since context or an explanation wasn't provided about said expression). If you still want to use it just replace line F with the following:
let product = origin.valueAsNumber * B.valueAsNumber;
C.value = Math.round(product * 100) / 100;
Do the same for line X and replace B.valueAsNumber; with A.valueAsNumber;
Demo 1
/*
Register the first form on the page to the input event
When any input within the form gets user data call function multiply()
*/
document.forms[0].oninput = multiply;
/** multiply()
//A - Pass Event Object
//B - Find input getting the user data - e.target always points to
the input getting data or button getting clicked, etc.
//C - if origin's [name=factorA]...
//D - ...then B is the tag after origin...
//E - ...and C is the tag after B...
//F - ...Set the value of C as the product of A and B
All form control values are strings not numbers, so once a
value is extracted from a form control it must be converted
to a number -- input.valueAsNumber is one of several ways
to do so.
- The second control statement handles input event if origin is
[name=factorB]
*/
function multiply(e) { //A
const origin = e.target; //B
if (origin.name === 'factorA') { //C
let B = origin.nextElementSibling; //D
let C = B.nextElementSibling; //E
C.value = origin.valueAsNumber * B.valueAsNumber; //F
} else if (origin.name === 'factorB') {
let A = origin.previousElementSibling;
let C = origin.nextElementSibling;
C.value = origin.valueAsNumber * A.valueAsNumber; //X
} else {
return false;
}
}
:root {
font: 700 3vw/1.2 Consolas
}
input,
output,
label {
display: inline-block;
font: inherit;
text-align: right;
}
input {
width: 30vw
}
<form>
<fieldset>
<legend>Multiplication</legend>
<label>
<input name='factorA' type='number' value='0'> × <input name='factorB' type='number' value='0'> &equals; <output name='product'>0</output>
</label><br>
<label>
<input name='factorA' type='number' value='0'> × <input name='factorB' type='number' value='0'> &equals; <output name='product'>0</output>
</label><br>
<label>
<input name='factorA' type='number' value='0'> × <input name='factorB' type='number' value='0'> &equals; <output name='product'>0</output>
</label><br>
</fieldset>
</form>
Demo 2
/*
Register the first form on the page to the input event
When any input within the form gets user data call function multiply()
*/
document.forms[0].oninput = multiply;
/** multiply()
//A - Pass Event Object
//B - Find input getting the user data - e.target always points to
the input getting data or button getting clicked, etc.
//C - if origin's .factorA...
//D - ...then B is the tag after origin...
//E - ...and C is the tag after B...
//F - ...Set the value of C as the product of A and B
All form control values are strings not numbers, so once a
value is extracted from a form control it must be converted
to a number -- input.valueAsNumber is one of several ways
to do so.
- The second control statement handles input event if origin is
.factorB
*/
function multiply(e) { //A
const origin = e.target; //B
if (origin.className === 'factorA') { //C
let B = origin.nextElementSibling; //D
let C = B.nextElementSibling; //E
C.value = origin.valueAsNumber * B.valueAsNumber; //F
} else if (origin.className === 'factorB') {
let A = origin.previousElementSibling;
let C = origin.nextElementSibling;
C.value = origin.valueAsNumber * A.valueAsNumber; //X
} else {
return false;
}
}
:root {
font: 700 3vw/1.2 Consolas
}
input,
output,
label {
display: inline-block;
font: inherit;
text-align: right;
}
input {
width: 30vw
}
<form>
<fieldset>
<legend>Multiplication</legend>
<label>
<input class='factorA' type='number' value='0'> × <input class='factorB' type='number' value='0'> &equals; <output class='product'>0</output>
</label><br>
<label>
<input class='factorA' type='number' value='0'> × <input class='factorB' type='number' value='0'> &equals; <output class='product'>0</output>
</label><br>
<label>
<input class='factorA' type='number' value='0'> × <input class='factorB' type='number' value='0'> &equals; <output class='product'>0</output>
</label><br>
</fieldset>
</form>
With getElementsByClassName
total = 0
for (instance of document.getElementsByClassName(clsName)) {
total+=parseInt(instance.value)
}
console.log(total)
An example for your problem
total = 0
i = 1
for (instance of document.getElementsByClassName(clsName)) {
if (i%3!=0) {
total+=parseInt(instance.value)
i++
} else {
instance.value = total
total = 0
i = 1
}
}
With getElementById
ids = ['id1', 'id2', 'idResult']
for (let id of ids) {
console.log(document.getElementById(id).value)
}

Compare input text with person name belongs to only one input number id

Im trying to write a validation for 2 groups of fields. I have 6 inputs, 3 for text name and 3 more for id number... the validation should do this "if input name="RE_SignedByID" has an input type name="RE_SignedByName", then other inputs name="RE_SignedByID", should NOT contain the same name="RE_SignedByName" More easy explanation... one ID number should have only one Person Name (Id number is unique for one person name). What can I use for that? Should I map() all the inputs?
Those are my inputs:
<div id="signedBy" class="clearfix">
<label>Signer, person ID & name</label>
<span id="signedByID" class="ids half">
<input type="text" name="RE_SignedByID" placeholder="personID, person1" data-validate="" tabindex="101" required>
<input type="text" name="RE_SignedByID" placeholder="personID, person2" data-validate="" tabindex="103">
<input type="text" name="RE_SignedByID" placeholder="personID, person3" data-validate="" tabindex="105">
</span>
<span class="names half">
<input type="text" name="RE_SignedByName" placeholder="name, person1" tabindex="102" required>
<input type="text" name="RE_SignedByName" placeholder="name, person2" tabindex="104">
<input type="text" name="RE_SignedByName" placeholder="name, person3" tabindex="106">
</span>
</div>
I guess it should also be an "on change" function? or can I make the validation on click? Some ideas...? Im actually compleatley lost here...
Thanks in advance!!!
Maybe use different class names for all 3 of them to make them unique?
<input class="name1">
<input class="name2">
<input class="name3">
I'm not sure what you mean but if you want to make the input types unique and not call them all when you write class="names half", then you should give them all unique class names.
So from my understanding you don't want multiple fields to have the same value.
My approach would be this:
let inputTimeout = null; //set an empty timeout object
let vars = [null, null, null, null]; // create an array containing as many nulls as you have inputs
$('.nameInput').on('keyup', function(){
let self = $(this);
clearTimeout(inputTimeout); //clear the timeout
inputTimeout = setTimeout(function(){ //set a timeout to check whether there is a dupe after the user has stopped typing
if (vars.indexOf(self.val()) == -1){ //check if the vals array contains the newly entered string
vars[self.attr('data-inputnum')] = self.val(); //insert the value into the array
}else{
//handle duplicates here
}
}, 500); //500ms is a sensible value for end of user input, change it if users complain that your app is too fast/slow
});
You then just have to edit your HTML a bit so that all name inputs have a class in common (i used .nameInput) and have a data-inputnum attr.
This would look something like this:
<input type="text" name="RE_SignedByName" placeholder="name, person1" tabindex="102" class='nameInput' data-whichinput='0'/>
<input type="text" name="RE_SignedByName" placeholder="name, person2" tabindex="103" class='nameInput' data-whichinput='1'/>
<!--and so on-->
Of course, never rely on JavaScript verification alone, always also check inside your backend. However this would be out of scope for this answer.
Hi Thanks all for the help, made me realize a couple of things till I got the answer. This is my working code:
var valSignedID = $("[name=SignedByID]").map(function() {
return this.value.trim();
}).get();
var valOwnersID = $("[name=OwnersID]").map(function() {
return this.value.trim();
}).get();
valSignedID.sort();
valOwnersID.sort();
for (var i = 0; i < valSignedID.length - 1; i++) {
if (valSignedID[i] == valSignedID[i + 1] && valSignedID[i] != "") {
alert(" You can not have duplicated signers ID's");
return false;
// break;
}
}
for (var i = 0; i < valSingedName.length; i++) {
if (valSingedName[i] == valSingedName[i + 1] && valSingedName[i] != "") {
alert(valSingedName[i] + " should not have different ID");
//return false;
}
}

Add three numbers and display result in textbox with Javascript

i was just trying to write a code that will use 3 input fields and show their sum into result field. If a person put data in field 1, the result field should show the data in result field and when user put data in second field, result field should show the sum of field 1 and field 2 and when user put data into field 3, their sum should be show on result field. I write below code but not got any success. I am a new learner.
<body>
Field 1: <input type="text" id="num1" onkeyup="sum();" > </br>
Field 2: <input type="text" id="num2" onkeyup="sum();" > </br>
Field 3: <input type="text" id="num3" onkeyup="sum();"> </br>
Sum: <input type="text" id="final" />
<script type="text/javascript">
function sum()
{
var w = document.getElementById('num1').value;
var x = document.getElementById('num2').value;
var y = document.getElementById('num3').value;
var z=parseInt(w)+parseInt(x)+parseInt(y);
document.getElementByID('final').value=z;
}
</script>
</body>
Two issues:
(1) Small typo in your last line, you used getElementByID instead of getElementById
(2) You need to account for the case where there is no value, one way to do this is to or it with 0 (which evaluates to 0 if there is no value).
Here is a working example:
function sum()
{
var w = document.getElementById('num1').value || 0;
var x = document.getElementById('num2').value || 0;
var y = document.getElementById('num3').value || 0;
var z=parseInt(w)+parseInt(x)+parseInt(y);
document.getElementById('final').value=z;
};
https://jsfiddle.net/yq60qad0/
It's a typo. =>
document.getElementByID('final').value=z;
should be Id, not ID

After deleting middle input renumber data-id

Right now when you add inputs they are numbered 1 by 1 so let's say we add 5 champions they will be numbered like
1
2
3
4
5
And let's say we want to remove 3rd one it will look like
1
2
4
5
And I want i to be numbered after removing like
1
2
3
4
Here is a working http://jsfiddle.net/dyje773m/ and also http://89.69.172.125/cms2.0/
Most important part of the code:
$(document).ready(function(){
championNumberArray = 0;
championNumber = 1;
$('a#AddChampion').on('click',function(){
$('div#ChampionInput').append(
'<div class="Champion" data-id="'+championNumberArray+'">\
Remove\
<br>\
<input type="text" class="ChampionInput" list="champions" name="champion[]" placeholder="Champion '+championNumber+'">\
<datalist id="champions"></datalist>\
Add Spell\
Add General Change\
<div class="GeneralChanges">\
</div>\
<div class="SpellChanges">\
</div>\
<br>\
<div>');
for(var key in champions){
if(champions.hasOwnProperty(key)){
$('#champions').append('<option value="' + key + '">');
}
}
championNumberArray++;
championNumber++;
});
});
And index
<div id="wrap">
Add Champion
<form name="second_form" id="second_form" method="POST">
<div id="ChampionInput">
</div>
<br><br>
<input type="submit" name="submit">
</form>
</div>
you shouldn't use championNumberArray and championNumber to store inputs quantities, instead of that u should count all the divs with class 'Champion' to get current quantity.
$("div.Champion").length;
when a input is added, u should set "id" value using previous method above.
when a input is deleted, u should get ther "id" value before removing... after removed, u can do following (( supposing "3" was removed ))
var c=3-1, el;
while(el=$("div.Champion:eq("+c+")").get())
{ $(el).data("id",c+1); c++; }
You have to renumber the inputs when you remove one. Try something like below.
$('div#ChampionInput').on('click', 'a.Remove',function(){
var champion = $(this).closest('.Champion');
var id = champion.data("id");
var nextChampion = champion;
//
// Loop through each following champion
while((nextChampion = nextChampion.next()).length != 0){
// Update id
nextChampion.attr("data-id",id++)
// Update placeholder
// Placeholder is id + 1 because placholders start at 1 and ids start at 0
nextChampion.find(".ChampionInput").attr("placeholder","Champion " + (id + 1));
}
// Remove champion
champion.remove();
});
By the way, you don't need to have the tagname before the selector. Especially for ids, which should be unique per page. #ChampionInput is exactly like div#ChampionInput, except #ChampionInput is faster because the browser doesn't have to check if the tagName matches.

Categories

Resources