Adding values of variable form fields - javascript

I have fields of type='number' in my form. These are dynamically generated by a database.
<input name="each[29]" id="form_29" placeholder="0.000" type="number" class="input" data-original-title="" title=""/>
<input name="each[30]" id="form_30" placeholder="0.000" type="number" class="input" data-original-title="" title=""/>
<input name="each[31]" id="form_31" placeholder="0.000" type="number" class="input" data-original-title="" title=""/>
The attribute name="each[xx]" is an ID of a category in the database. Here is the submit button:
<input type="submit" value="Enregistrer" onClick="return calculAuto('form_29,form_30,form_31')">
JavaScript
function calculAuto(v) {
var mystr = v;
var myarr = mystr.split(",");
var cat = '';
for (i = 0; i < myarr.length; i++) {
if ($('#' + myarr[i]).val() !== '') {
cat += $('#' + myarr[i]).val();
}
}
}
I want to calculate the sum of all the fields passed in the argument of the function.

you are doing:
var cat = ''; //string
so with cat += $('#' + myarr[i]).val();
its appending the values, do:
function calculAuto(v) {
var mystr = v;
var myarr = mystr.split(",");
var cat = 0;
for (i = 0; i < myarr.length; i++) {
if ($('#' + myarr[i]).val() !== '') {
cat += $('#' + myarr[i]).val();
}
}
console.log(cat);
return false;
}

Related

change attrib name with array

I have a form with this input:
<input id="cant_user" type="text" name="cant_user" value="1" onblur="addInputs()">
#userData is cloned when add a input value greater than 1 and I want to change input name from user_age to age[n]
<div id="userData">
<div class="panel-body" id="generated[0]">
<div class="form-group">
<label class="col-md-4 control-label">Age User [n]</label>
<div class="col-md-6">
<input type="number" class="form-control" name="user_age[]" value="0" required>
</div>
</div>
</div>
Javascript:
function addInputs() {
var cantUsers = document.getElementById("cant_user").value;
var countGenerated = $('[id^=generated]').length;
if (countGenerated > 0) {
$('[id^=generated]').not(':first').remove();
}
if (cantUsers != 1) {
if (cantUsers > 1 && cantUsers < 10) {
for (var i = 1; i < cantUsers; i++) {
jQuery("#userData").append(jQuery("#userData").children().first().clone());
jQuery("#userData").children().last().attr("id", "generated[" + i + "]");
for (var n = 0; n <= i; m++) {
var u = document.getElementsByName("user_age[]");
$(u).removeAttr("name").attr({
id: "generatedAge[" + n + "]",
name: "age[" + n + "]"
});
}
};
}
};
}
How can I make every label and input name shows a value from array like:
<label>Age User 1<label>
<input name="age[0]">
<label>Age User 2<label>
<input name="age[1]">
I changed some code, it maybe can help if i understand your idea correct
for ( var i = 1; i < cantUsers; i++) {
var userData = jQuery("#userData");
var childOfUserData = userData.children();
userData.append( childOfUserData.first().clone() );
childOfUserData = userData.children(); //because we just appen new data
childOfUserData.last().attr("id","generated[" + i + "]");
for ( var n = 0; n <= i; n++ ) {
var child = childOfUserData.get(i);
var userAge = $("input", $(child));//because you only have one input
userAge.attr("name","age[" + n + "]").attr("id","generatedAge[" + n + "]");
}
<input name="age[0]">
In the above code name attribute value acts as text not an array value.
To get an array value in the attribute, you need to change the JavaScript code
$("#userData").children().last().attr("id", generated[i]);
$(u).removeAttr("name").attr({
id: generatedAge[n],
name: age[n]
});
Now, if you check the attribute value, you will receive data into it.
Hope this will help you.

Taking the sum of user inputs and storing it as a variable

What is the best way to calculate sum of user inputs from an array and then store that value as a variable?
I have a function here that creates an array from user inputs(number4[]).
var counter = 1;
var limit = 3;
function addInput(divName){
if (counter == limit) {
alert("You have reached the limit of adding " + counter + " inputs");
}
else {
var newdiv = document.createElement('div');
newdiv.innerHTML = "Asset($) " + (counter + 1) + " <br><input type='text' name='number4[]'>";
document.getElementById(divName).appendChild(newdiv);
counter++;
}
<div class="container7">
<div id ="dynamicInput">
Assets 1($): <INPUT type="text" name="number4[]">
</div>
Liabilities 1(%): <INPUT type="text" name="number5">
Result($): <INPUT type="text" name="total1">
<INPUT type="button" style="background-color:#FF8800; border-color:BLACK;" value="Calculate"onclick="javascript:networth()">
<INPUT type="button" style="background-color:#FF8800; border-color:BLACK;" value="Add asset fields"onclick="addInput('dynamicInput');">
</div>
</FORM>
I have no code for total1 yet. so basically i have the array i just need help identifying the sum and then assigning it as a variable.
document.getElementsByName("number4[]") will return an array of the elements you need to total up
function networth(){
var totNo = document.getElementsByName("number4[]").length;
var sum = 0;
for(var i=0; i<totNo; i++){
sum += parseInt(document.getElementsByName("number4[]")[i].value);
console.log(sum);
}
}
Add an id to your input elements and use
var val1 = document.getElementById("the id of the input you want").value
//repete for val2... with a different id and add the val variables
You need to get all the input elements you want to sum. You can use the querySelectorAll to get all the elements with a same CSS selector common in all the inputs you want to sum.
https://www.w3schools.com/jsref/met_document_queryselectorall.asp
Finally you can get the input in the same way with querySelector, as is only one there is no need to use the All variation.
https://www.w3schools.com/jsref/met_document_queryselector.asp
var counter = 1;
var limit = 3;
function networth(){
var inputs = document.querySelectorAll("form #dynamicInput input");
var networth = 0;
for (var i = 0; i < inputs.length; i++) {
networth += parseFloat(inputs[i].value);
}
document.querySelector("input[name=total1]").value=networth;
}
function addInput(divName) {
if (counter == limit) {
alert("You have reached the limit of adding " + counter + " inputs");
} else {
var newdiv = document.createElement('div');
newdiv.innerHTML = "Asset($) " + (counter + 1) +
" <br><input type='text' name='number4[]'>";
document.getElementById(divName).appendChild(newdiv);
counter++;
}
}
<form>
<div class="container7">
<div id="dynamicInput">
Assets 1($):<br>
<INPUT type="text" name="number4[]">
</div>
Liabilities 1(%):
<INPUT type="text" name="number5"> Result($):
<INPUT type="text" name="total1">
<INPUT type="button" style="background-color:#FF8800; border-color:BLACK;" value="Calculate" onclick="javascript:networth()" />
<INPUT type="button" style="background-color:#FF8800; border-color:BLACK;" value="Add asset fields" onclick="addInput('dynamicInput');" />
</div>
</FORM>

Using for loop to generate text boxes

I want to be able to enter a number into a text box and then on a button click generate that number of text boxes in another div tag and automatically assign the id
Something like this but not sure how to generate the text boxes and assign automatically assign the id
function textBox(selections) {
for (i=0; i < selections +1; i++) {
document.getElementById('divSelections').innerHTML = ("<form><input type="text" id="1" name=""><br></form>");
}
}
Try this one:
function textBox(selections){
selections = selections*1; // Convert to int
if( selections !== selections ) throw 'Invalid argument'; // Check NaN
var container = document.getElementById('divSelections'); //Cache container.
for(var i = 0; i <= selections; i++){
var tb = document.createElement('input');
tb.type = 'text';
tb.id = 'textBox_' + i; // Set id based on "i" value
container.appendChild(tb);
}
}
A simple approach, which allows for a number to be passed or for an input element to be used:
function appendInputs(num){
var target = document.getElementById('divSelections'),
form = document.createElement('form'),
input = document.createElement('input'),
tmp;
num = typeof num == 'undefined' ? parseInt(document.getElementById('number').value, 10) : num;
for (var i = 0; i < num; i++){
tmp = input.cloneNode();
tmp.id = 'input_' + (i+1);
tmp.name = '';
tmp.type = 'text';
tmp.placeholder = tmp.id;
form.appendChild(tmp);
}
target.appendChild(form);
}
Called by:
document.getElementById('create').addEventListener('click', function(e){
e.preventDefault();
appendInputs(); // no number passed in
});
JS Fiddle demo.
Called by:
document.getElementById('create').addEventListener('click', function(e){
e.preventDefault();
appendInputs(12);
});
JS Fiddle demo.
The above JavaScript is based on the following HTML:
<label>How many inputs to create:
<input id="number" type="number" value="1" min="0" step="1" max="100" />
</label>
<button id="create">Create inputs</button>
<div id="divSelections"></div>
See below code sample :
<asp:TextBox runat="server" ID="textNumber"></asp:TextBox>
<input type="button" value="Generate" onclick="textBox();" />
<div id="divSelections">
</div>
<script type="text/javascript">
function textBox() {
var number = parseInt(document.getElementById('<%=textNumber.ClientID%>').value);
for (var i = 0; i < number; i++) {
var existingSelection = document.getElementById('divSelections').innerHTML;
document.getElementById('divSelections').innerHTML = existingSelection + '<input type="text" id="text' + i + '" name=""><br>';
}
}
</script>
Note: Above code will generate the N number of textboxes based on the number provided in textbox.
It's not recommended to user innerHTML in a loop :
Use instead :
function textBox(selections) {
var html = '';
for (i=0; i < selections +1; i++) {
html += '<form><input type="text" id="'+i+'" name=""><br></form>';
}
document.getElementById('divSelections').innerHTML = html;
}
And be carefull with single and double quotes when you use strings
You have to change some code snippets while generating texboxes, Learn use of + concatenate operator, Check code below
function textBox(selections) {
for (var i=1; i <= selections; i++) {
document.getElementById('divSelections').innerHTML += '<input type="text" id="MytxBox' + i + '" name=""><br/>';
}
}
textBox(4); //Call function
JS Fiddle
Some points to taken care of:
1) In for loop declare i with var i
2) your selection + 1 isn't good practice at all, you can always deal with <= and < according to loop's staring variable value
3) += is to append your new HTML to existing HTML.
ID should be generate manually.
var inputName = 'divSelections_' + 'text';
for (i=0; i < selections +1; i++) {
document.getElementById('divSelections').innerHTML = ("<input type='text' id= " + (inputName+i) + " name=><br>");
}
edit : code formated
Instead of using innerHTML, I would suggest you to have the below structure
HTML:
<input type="text" id="id1" />
<button id="but" onclick="addTextBox(this)">click</button>
<div id="divsection"></div>
JS:
function addTextBox(ops) {
var no = document.getElementById('id1').value;
for (var i = 0; i < Number(no); i++) {
var text = document.createElement('input'); //create input tag
text.type = "text"; //mention the type of input
text.id = "input" + i; //add id to that tag
document.getElementById('divsection').appendChild(text); //append it
}
}
JSFiddle

Javascript to alert a user that the same info has already been entered

First I should say I am a javascript newbie so forgive my ignorance.
I'm creating a form that has three functions and also uses array:
Add - To accept a name (if field left blank it should ask the user to enter a name in an alert box)
Find - To verify a name has not already been entered (in an alert box)
List - To list the names that have been entered (in an alert box)
I have the list function working (good). The alert to enter a name comes up after you enter a name as well as when you leave the field blank (not good)
and I can't get the find function to work at all.
My code is below and I've tried so many iterations and searched so many sites for help, also tried firebug; I'm hoping someone can point me in the right direction.
Untitled
<body>
<script type="text/javascript">
var a = new Array();
function list() {
var s = "";
for (i = 0; i < a.length; i++)
s = s + a[i] + "\n";
alert(s);
}
function add() {
// If the text box empty you ask the user to enter a name.
var myTextField = document.getElementById("myText");
a[a.length] = myTextField.value;
myTextField.value = "";
if (myTextField.value == "") {
alert("Please enter a name");
return false;
}
function find() {
//If the name already exists you should get a warning
var myTextField = document.getElementById("myText");
a[a.length] = myTextField.value;
myTextField.value = "";
for (var i = 0; i < a.length; i++)
if (a[i] == myTextField) {
alert("Sorry, the name " + a[i] + " already exists. Try again");
}
}
}
</script>
<input type="text" id="myText" /><br>
<input type="button" onclick="add()" value="Add a name" />
<input type="button" onclick="list()" value="List the names" />
<input type="button" onclick="find()" value="Find" />
</body>
</html>
You have done it almost, but some lil errors.. here you can check it jsfiddle
HTML:
<input type="text" id="myText" /><br>
<input type="button" value="Add a name" class="add_button"/>
<input type="button" value="List the names" class="list_button"/>
<input type="button" value="Find" class="find_button"/>
JS:
$(".add_button").live("click", function(){
add()
});
$(".list_button").live("click", function(){
list()
});
$(".find_button").live("click", function(){
find()
});
var a = new Array();
function list()
{
var s = "";
for(i = 0; i < a.length; i++)
s = s + a[i] + "\n";
alert(s);
}
function add()
{
// If the text box empty you ask the user to enter a name.
var myTextField = document.getElementById("myText");
a[a.length] = myTextField.value;
if (myTextField.value == "")
{
alert ("Please enter a name");
return false;
}
myTextField.value = "";
}
function find()
{
//If the name already exists you should get a warning
var status = true;
var myTextField = document.getElementById("myText");
for (var i = 0; i < a.length; i++)
{
if (a[i] == myTextField.value)
{
alert ("Sorry, the name " + a[i] + " already exists. Try again");
status = false;
break;
}
}
if(status==true)
{
a[a.length] = myTextField.value;
}
myTextField.value = "";
}
The code had a couple of errors, here's a working version: http://jsfiddle.net/sAq2m/2/
html:
<input type="text" id="myText" /><br>
<input type="button" onclick="add()" value="Add a name" />
<input type="button" onclick="listItems()" value="List the names" />
<input type="button" onclick="find()" value="Find" />
js:
var a = [];
function listItems()
{
var s = "";
for(var i = 0; i < a.length; i++)
s = s + a[i] + "\n";
alert(s);
return false;
}
function add()
{
// If the text box empty you ask the user to enter a name.
var myTextField = document.getElementById("myText");
var v = myTextField.value
if (!v){
v = prompt("You have not entered a name, please enter one.");
}
a.push(v);
console.log(a);
myTextField.value = "";
return false;
}
function find()
{
//If the name already exists you should get a warning
var myTextField = document.getElementById("myText");
for (var i = 0; i < a.length; i++)
if (a[i] == myTextField.value)
{
alert ("Sorry, the name " + a[i] + " already exists. Try again");
return;
}
}

get data from input to array

<h2>Add Another Input Box</h2>
<div id="p_scents">
<p>
<label for="p_scnts"><input type="text" id="p_scnt" size="20" name="p_scnt" value="" placeholder="Input Value" /> <input type="checkbox" id="c_scnt" name="c_scnt" class="show"> <input type="text" id="more" name="more" class="hide"> </label>
</p>
</div>
<span id="getall">Get all</span>
ALL CODE: http://jsfiddle.net/tZPg4/1420/
Is possible click on Get all and get all data from all inputs and next use them with loop each and get data: this.one (first input(text)), this.two (second input(checkbox)), this.three (third input - hidden )? for example:
$("#getall").click(function(){
//here get all data to array, but how?
array.each(function(i){
var html = $("<tr><td>this.one</td><td>this.two</td><td>this.three</td></tr>").appendTo("#myTable");
});
})
LIVE: http://jsfiddle.net/tZPg4/1420/
Something like this should work?
$("#getall").click(function(){
var myRow = document.createElement("tr");
var array = new Array()
$.each($("#p_scents").find("p"), function(ind, elem) {
var inputCol = new Array();
console.log("Adding row");
$.each($(elem).find("input"), function(ind2, inputElem) {
if ($(inputElem).attr("type") != "checkbox") {
inputCol [inputCol .length] = $(inputElem).val();
}
else {
inputCol [inputCol .length] = $(inputElem).is(":checked");
}
});
array[array.length] = inputCol;
});
console.log("Outputting results");
for (var i in array) {
console.log("Row: "+i);
for (var j in array[i]) {
console.log("Input: "+j + " == " + array[i][j]);
}
}
});
var arr = new Array();
$( 'input' ).each(function(index)
{
arr[arr.length] = $(this).val();
})

Categories

Resources