replace String to number in loop - javascript

I want to create a fill in the blank quizz web site.
My problem is putting a different name="" value of all inputs.
So I create a function Who change a string giving into input.
But the problem is they have all the same name (inpName1).
What I want to do is giving them a diffrent names (inpName1,inpName2,inpName3...) so I can recuperate them later into DB
var i=0;
function MyFunction() {
var str = document.getElementById("myTextArea").value;
var res = str.replace(/#champ/g, "<input type='text' name='inpName"+ i++ +"'>");
document.getElementById("finalText").innerHTML = res;
}

Instead of inpName1, inpName2 etc use [] notation in name attribute:
<input type='text' name='inpName[]'>
<input type='text' name='inpName[]'>
<input type='text' name='inpName[]'>
<input type='text' name='inpName[]'>
In this case your values will be available on server via $_POST['inpName'] array.

Related

How can I access these form values?

I want to create a form where I will perform an operation with the values entered by the user, but when the function runs, I get NaN return. Thank you in advance for the help.
function test() {
var age = document.getElementsByName("person_age").value;
var weight = document.getElementsByName("person_weight").value;
var size = document.getElementsByName("person_size").value;
document.getElementById("result").innerHTML = weight + size + age;
}
<form>
<input type="text" name="person_age">
<input type="text" name="person_size">
<input type="text" name="person_weight">
<input type="button" value="calculate" onclick="test();">
</form>
<h3 id="result"></h3>`
Output:
NaN
When I get the values from the user and run the function, I get NaN feedback. how can i solve this problem.
There are multiple errors that you have to correct
1) When you use getElementsByName, It will return NodeList array like collection. So you have to get the element by using index as:
var age = document.getElementsByName( "person_age" )[0].value;
2) If you need sum of all three value then you have to convert it into Number type because document.getElementsByName( "person_age" )[0] give you value in String type. So you can do as:
+document.getElementsByName( "person_age" )[0].value
function test() {
var age = +document.getElementsByName("person_age")[0].value;
var size = +document.getElementsByName("person_size")[0].value;
var weight = +document.getElementsByName("person_weight")[0].value;
document.getElementById("result").innerHTML = weight + size + age;
}
<form>
<input type="text" name="person_age">
<input type="text" name="person_size">
<input type="text" name="person_weight">
<input type="button" value="calculate" onclick="test();">
</form>
<h3 id="result"></h3>
Just a Suggestion: You can use Document.getElementById if you want to directly access the value. Just add an ID property in your element. It will return a string value, convert that to int and you're good to go.
function test() {
var age = document.getElementById("person_age").value;
var weight = document.getElementById("person_weight").value;
var size = document.getElementById("person_size").value;
document.getElementById("result").innerHTML = parseInt(weight) + parseInt(size) + parseInt(age);
}
<form>
<input type="text" name="person_age" id="person_age">
<input type="text" name="person_size" id="person_size">
<input type="text" name="person_weight" id="person_weight">
<input type="button" value="calculate" onclick="test();">
</form>
<h3 id="result"></h3>
getElementsByName will always return an array-like nodelist so, if you were to use it you would need to access the first index [0]. Instead add a class to each input and use querySelector to target it.
The value of an input will always be a string (even if the input is type "number"), so you need to coerce it to a number, either by using Number or by prefixing the value with +.
So, in this example I've updated the HTML a little by adding classes to the inputs, and changing their type to "number", and removing the inline JS, and updated the JS so that the elements are cached outside of the function, an event listener is added to the button, and the values are correctly calculated.
// Cache all the elements using querySelector to target
// the classes, and add an event listener to the button
// that calls the function when it's clicked
const ageEl = document.querySelector('.age');
const weightEl = document.querySelector('.weight');
const sizeEl = document.querySelector('.size');
const result = document.querySelector('#result');
const button = document.querySelector('button');
button.addEventListener('click', test, false);
function test() {
// Coerce all the element values to numbers, and
// then display the result
const age = Number(ageEl.value);
const weight = Number(weightEl.value);
const size = Number(sizeEl.value);
// Use textContent rather than innerHTML
result.textContent = weight + size + age;
}
<form>
<input type="number" name="age" class="age" />
<input type="number" name="size" class="size" />
<input type="number" name="weight" class="weight" />
<button type="button">Calculate</button>
</form>
<h3 id="result"></h3>`

Display sum of other inputs into another element with javascript

Question
How can I have an element dynamically display the sum of various inputs?
Background
I have several text boxes (with the same class). I have 4 inputs, each with a number. Input 1 is "1", 2 is "2", etc.
I want the fifth box to contain the sum of "1, 2, 3, 4".
Issue
I am struggling with the javascript.
Ideally the fourth box with id final would update as any of the previous boxes are edited.
Can I do it using the classes? that is my intent as the amount of inputs can vary, it will not always be four.
HTML
<input type='text' id='txtFirst' class='copyText' /><br/>
<input type='text' id='txtSecond' class='copyText' /><br/>
<input type='text' id='txtThird' class='copyText' /><br/>
<input type='text' id='final' />
$('.copyText').on('keyup', function(){
var val = 0;
$('.copyText').each(function(){
val = val + (+$(this).val());
})
$('#final').val(val);
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js"></script>
<input type='text' id='txtFirst' class='copyText' /><br/>
<input type='text' id='txtSecond' class='copyText' /><br/>
<input type='text' id='txtThird' class='copyText' /><br/>
<input type='text' id='final' />
Try this which uses jQuery (demo using 2.1.0)
$('.copyText').on('keyup', function(){
var val = 0;
$('.copyText').each(function(){
val = val + (+$(this).val());
})
$('#final').val(val);
})
To see the the working demo click here. Or run the code snippet here.
window.onload = _ => {
//get the html elements
const texts = Array.from(document.getElementsByClassName("copyText"));
const out = document.getElementById("final");
//a function for getting all the text values and updating the ouput
function update(){
out.value = texts.map( text => text.value ).join(", ");
}
//await input, then update
texts.forEach( text => text.addEventListener("input", update) );
};
With jQuery get the fields values :
$('.copyText').map(function(){return $(this).val();})
Transform to string with :
.get().join(',')
And assign it to #final with :
$("#final").val();
Conclusion :
$("#final").val($('.copyText').map(function(){return $(this).val();}).get().join(','));

Adding two input boxes using Javascript

I am trying to add two already calculated and formatted input fields and not having much luck. My code is:
<input type='text' id='cage_linear_feet' value='83'>
<input type='text' id='cage_estimate' disabled>
<br>
<input type='text' id='cage_doors' value='3'>
<input type='text' id='doors_estimate' disabled>
<br>
<input type='text' id='cage_totals' disabled>
<script>
function format(n) {
return n.toFixed(2).replace(/(\d)(?=(\d{3})+\.)/g, "$1,");
}
//Linear Feet Calculation
$(document).ready(LinearFeet);
document.getElementById('cage_linear_feet').addEventListener("keyup", LinearFeet);
var inputBox1 = document.getElementById('cage_linear_feet');
function LinearFeet(){
document.getElementById('cage_estimate').value = format(inputBox1.value*225);
}
//Doors Calculation
$(document).ready(CageDoors);
document.getElementById('cage_doors').addEventListener("keyup", CageDoors);
var inputBox2 = document.getElementById('cage_doors');
function CageDoors(){
document.getElementById('doors_estimate').value = format(inputBox2.value*1800);
}
</script>
How do I add cage_estimate and doors_estimate together and display in cage_totals in real time?
Thanks,
John
This is what you are asking
how to convert comma separated currency into number in java script
parseFloat
This function calculate total. You have to call it in each key functions.
function setTotal(){
var x=document.getElementById('doors_estimate').value;
var y=document.getElementById('cage_estimate').value;
if(x ){
if(y){
var z=(parseFloat(x.replace(',',''))+parseFloat(y.replace(',','')));
document.getElementById('cage_totals').value=format(z);
}
}
}
calling codes
function LinearFeet(){
var inputBox1 = document.getElementById('cage_linear_feet');
document.getElementById('cage_estimate').value = format(inputBox1.value*225);
setTotal();
}
function CageDoors(){
var inputBox2 = document.getElementById('cage_doors');
document.getElementById('doors_estimate').value = format(inputBox2.value*1800);
setTotal();
}
Referances:
parseFloat
replace

Using join() to create a HTML id?

I have 6 Hidden fields which are to hold a latitude and longitude for 3 different postcodes:
<input type="hidden" id="geo_lat1" name="geo_lat1">
<input type="hidden" id="geo_lon1" name="geo_lon1">
<input type="hidden" id="geo_lat2" name="geo_lat2">
<input type="hidden" id="geo_lon2" name="geo_lon2">
<input type="hidden" id="geo_lat3" name="geo_lat3">
<input type="hidden" id="geo_lon3" name="geo_lon3">
I also have the three input fields for the postcodes:
<input type="text" name="search_postcode1" id="search_postcode1">
<input type="text" name="search_postcode2" id="search_postcode2">
<input type="text" name="search_postcode3" id="search_postcode3">
The geocoding function I have works fine, but only for the first set of lat/longs. If I want to produce the lat/longs for the other two postcodes, I would have to copy and paste the geocoding function for each postcode, just changing the number at the end of the input name in the following line:
var sAddress1 =document.getElementById("search_postcode1").value ;
Instead of copying/pasting I want to use the same code but in a loop, which means changing the reference from search_postcode1 to search_postcode2 and search_postcode3
I know I can use join() to join data in an array and assign it to another variable like so:
var a = new Array("search_postcode","1");
var pcname = a.join(""); // pcname would be assigned "search_postcode1"
My question is how do I assign it so that it would appear in the line of code above rather than a value in a variable?
EDIT
I also need to assign it to the hidden fields using:
geo_lat1.value = loc[0];
geo_lon1.value = loc[1];
How do I change the '1's in this to a '2' and a '3' in a loop? It must be a different way to the getElementById("search_postcode" + "1") way?
You could do something like this:
for (var i = 1; i <= 3; i++) {
var address = document.getElementById('search_postcode' + i);
// Do something with address. Each time through the loop, it will
// reference the "i" search_postcode input, 1-3. Maybe something like:
var loc = geoCodePostCode(address.value);
document.getElementById('geo_lat' + i).value = loc[0];
document.getElementById('geo_long' + i).value = loc[1];
}

Javascript function not returning a value

I have a javascript function that check for a value from a text box and the if the text box is not blank it outputs a statement. The text box take a numeric value, i want to include that numeric value that is output to html.
here is the html
<br><label id="cancelphoneLabel">1-800-555-1111</label>
<br><label id="mdamountLabel">Monthly Donation:
<td>
<input type="text" id="mdamountBox" style="width:50px;" name="md_amt" value="" placeholder="Monthly" onkeyup="monthlycheck()" autocomplete="off">
<br><label id="mnthlychkdiscoLabel"> </label>
and the Javascript
function monthlycheck() {
var mnthchk = document.getElementById("mdamountBox").innerHTML; <---i want to pass the value of this box
var cancelPhone = document.getElementById("cancelphoneLabel").innerHTML;
if (mnthchk.value != "") {
var newHTML = "<span style='color:#24D330'> Your Monthly pledge in the amount of $<label id='dollarLabel'> </label> is valid and will be deducted this time every month<br> untill you notify us of its cancellation by calling <label id='cancelphonelistLabel'> </label> </span>";
document.getElementById("mnthlychkdiscoLabel").innerHTML = newHTML;
document.getElementById("cancelphonelistLabel").innerHTML = cancelPhone;
document.getElementById("dollarLabel").innerHTML = mnthchk; <----passed to here
i cant get the value passed, it only shows blank, i can hardcode a value and will output fine, which is how the jsfiddle is currently http://jsfiddle.net/rn5HH/4/
thanks in advance
Input elements don't have child nodes, therefore innerHTML is blank. If you want to read their value, use the value property.
Your line:
var mnthchk = document.getElementById("mdamountBox").innerHTML;
Should be:
var mnthchk = document.getElementById("mdamountBox");
Then you can get the value of the text input like this:
var newmnthchk = mnthchk.value;
Working JS Fiddle here: http://jsfiddle.net/rn5HH/10/
use document.getElementById("mdamountBox").value
The problem here is you are trying to get the innerHtml, where you want the value. From your fiddle, just change this line:
var mnthchk = document.getElementById("mdamountBox").innerHTML;
...to this:
var mnthchk = document.getElementById("mdamountBox").value;
check below code :
HTML Code
<br><label id="cancelphoneLabel">1-800-555-1111</label>
<br><label id="mdamountLabel">Monthly Donation:
<td>
<input type="text" id="mdamountBox" style="width:50px;" name="md_amt" value="" placeholder="Monthly" onkeyup="monthlycheck()" autocomplete="off">
<br><label id="mnthlychkdiscoLabel"> </label>
Javascript Code
function monthlycheck() {
var mnthchk = document.getElementById("mdamountBox").value;
var cancelPhone = document.getElementById("cancelphoneLabel").innerHTML;
if (mnthchk.value != "") {
var newmnthchk = '5';
newmnthchk = mnthchk;
var newHTML = "<span style='color:#24D330'> Your Monthly pledge in the amount of $<label id='dollarLabel'> </label> is valid and will be deducted this time every month<br> untill you notify us of its cancellation by calling <label id='cancelphonelistLabel'> </label> </span>";
document.getElementById("mnthlychkdiscoLabel").innerHTML = newHTML;
document.getElementById("cancelphonelistLabel").innerHTML = cancelPhone;
document.getElementById("dollarLabel").innerHTML = newmnthchk;
}
}
This is working code perfectly checked on Fiddle
,you need to get DOM value using
var mnthchk = document.getElementById("mdamountBox").value;

Categories

Resources