Storing multiple values with different id in array - php,javascript - javascript

Multiple values are inputted using below code:
$c_num is the count of inputs. There are n number of inputs
$stud['stud_c'] is student codes, S01,S02,S05,S08,S19 .........
On a javascript function calculate(), a portion of id is passed.
code:
<input type="number" required id="c_m_<?php echo $c_num; ?>_<?php echo $stud['stud_c'];?>" name="c_m_<?php echo $c_num; ?>[<?php echo $stud['stud_c'];?>]" onkeypress="calculate('<?php echo $c_num; ?>_<?php echo $stud['stud_c'];?>','<?php echo $stud['stud_c'];?>')" class="num<?php echo $c_num; ?> " >
When I alert class1, i am getting corresponding output. But how to store multiple values with different id in array? How to store those inputted values in array num[] ? I also want to alert the total of these inputs.
Corresponding script for finding sum of n number of inputs:
function calculate(class1,class2){
var n = parseFloat(document.getElementById('count').value);
var num[] = parseFloat(document.getElementById('c_m_'+class1).value);
var total=0;
for (var i = 0; i <n; i++) {
total = total + parseFloat(num[i]) ;
}
if (!isNaN(total)) {
document.getElementById('total_mark_'+class2).value = Math.round(total);
}
}

Try like this..
<script>
arr =[];
function calculate(class1)
{
//var n = parseFloat(document.getElementById('count').value);
var num = parseFloat(document.getElementById('c_m_'+class1).value);
arr.push(num);
var total=0;
var n =arr.length;
for (var i = 0; i <n; i++) {
total = total +arr[i];
}
alert(total);
}
</script>

Try this . array.push().And array declaration was wrong.use num=[] instead of num[] .
I don't know why use n on forloop length. if you originaly need the array length use with n=num.length
var num=[];
function calculate(class1)
{
var n = parseFloat(document.getElementById('count').value);
num.push(parseFloat(document.getElementById('c_m_'+class1).value));
var total=0;
//n=num.length if you need num array length use this
for (var i = 0; i <n; i++) {
total = total + parseFloat(num[i]) ;
}
alert(total);
}

Assign a common attribute for the inputs and fetch them by this attribute. There are many ways to fetch nodes by attribute. To name a few:
parentNode.getElementsByClassName('className') fetches all the child nodes having specific class attribute;
parentNode.querySelectorAll('input[attribute="value"]') fetches a node list of all input tags having specific attribute value
using jQuery selector like 'input[attribute="value"]'
Example
(function() {
var inputs, i, total = 0;
inputs = document.forms.c.querySelectorAll("input[name='c_m[]']");
for (i = 0; i < inputs.length; i++) {
total += Number(inputs[i].value);
}
console.log(total);
})();
<html>
<head>
<meta http-equiv="content-type" content="text/html; charset=utf-8">
<title>XXX</title>
</head>
<body>
<form name="c">
<input type="text" name="c_m[]" value="1" size="3" />
<input type="text" name="c_m[]" value="2" size="3" />
<input type="text" name="c_m[]" value="3" size="3" />
</form>
</body>
</html>
Note, you don't need to collect the input values into num array, if you only want to compute the sum of the values. Simply literate the nodes and collect their values. If for some reason you still want to collect the values into an array, use Array.prototype.push method:
var num = [];
for (i = 0; i < inputs.length; i++) {
num.push(inputs[i].value);
}

<script type="text/javascript">
var RECALCULATE = function(a,b) {
var rowtotal = 0;
n = new Array();
var count = document.getElementById('criteria_count').value;
for (i = 1; i <=count; i++) {
if (parseInt(document.getElementById('criteria_mark_'+i+'_'+b).value) > 0) {
n[i] = parseInt(document.getElementById('criteria_mark_'+i+'_'+b).value);
rowtotal += n[i];
}
}
document.getElementById('total_mark_'+b).value = rowtotal;
};
</script>

Related

Check two arrays and its respective index as pair and find if a similar pair exist

I have a simple html code as below
<input type="text" id="key" name="key">
<input type="text" id="value" name="value">
<button id="check">Check</button>
and I have related jQuery code as well
var keyArray = [];
var valueArray = [];
$("#check").click(function() {
var keyVal = $("#key").val();
var valueVal = $("#value").val();
keyArray.push(keyVal);
valueArray.push(valueVal);
console.log(keyArray);
console.log(valueArray);
for ($i = 0; $i < keyVal.length; $i++) {
//Need to add some code here to check
}
});
What I want is, whenever if someone click the Check button, it has to check if there is a similar item added before into the respective index of keyArray and valueArray. Eg: First I add 1 into the id key and 2 into the id value. If I add 1 and 2 into key and value fields a second time, it should prompt me such a pair already added.
How can I achieve this with JavaScript or jQuery?
var keyArray = [];
var valueArray = [];
$("#check").click(function() {
var keyVal = $("#key").val();
var valueVal = $("#value").val();
var exist=false;
if(keyArray.length>0){
for (i = 0; i < keyArray.length; i++) {
if(keyArray[i]==keyVal && valueArray[i]==valueVal)
{
console.log("pair exist");
exist=true;
break;
}
}
}
if(!exist)
{
keyArray.push(keyVal);
valueArray.push(valueVal);
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type="text" id="key" name="key">
<input type="text" id="value" name="value">
<button id="check">Check</button>
If you want, you can introduce a third array and store data in it, and compare it with your value.
var keyArray = [];
var valueArray = [];
var newArray = [];
$("#check").click(function() {
var keyVal = $("#key").val();
var valueVal = $("#value").val();
var isExist = false;
for (i = 0; i < newArray.length; i++) {
if(newArray[i].key == keyVal && newArray[i].value == valueVal ){
isExist = true;
break;
}
else{
isExist = false;
}
}
if (isExist){
alert("such a pair already added");
}
else{
keyArray.push(keyVal);
valueArray.push(valueVal);
newArray.push({ key : keyVal, value : valueVal });
}
console.log(keyVal);
console.log(valueVal);
console.log(newArray);
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type="text" id="key" name="key">
<input type="text" id="value" name="value">
<button id="check">Check</button>

javascript - how to use a text box input in a for loop

I am trying to write a solution for a javascript application that takes a number input & depending on that number is how many times it runs a specific function. I am using a text box for input field & a button to process the number of times the user wants the function to run. It is for a game of dice game. User enters how many games he wants to play and clicks button to run the roll_dice function that many times. I'm not sure if I am going the right way with using a for loop to take users numeric input and loop through its value until it ends for example
function games() {
var num = document.getElementById("inp").vale;
var i;
for (i = 0; i < num; i++) {
roll_dice();
}
}
You have a typo. It's .value.
You can convert a string to a number by using * 1.
Something like this:
function games() {
var num = document.getElementById("inp").value * 1; // Convert the string value a number.
var i;
for (i = 0; i < num; i++) {
roll_dice();
}
}
function roll_dice() {
console.log("Test.");
}
var btnRun = document.getElementById("btnRun");
btnRun.onclick = function() {
games();
};
<input id="inp" type="text" />
<button id="btnRun" type="button">Run</button>
The value you get from input box is string you need to convert it into int . If you are using int in loop .
var num = parseInt(document.getElementById("inp").value);
function games() {
var num = document.getElementById("inp").value;
var i;
for (i = 0; i < Number(num); i++) {
roll_dice();
}
}
**<label>Game:</label><input type="text" id="input" value="0" />
<button id="btn">Submit</button>
<script>
document.getElementById("btn").addEventListener("click",function(){
var inputVal=document.getElementById("input").value*1;
rollDice(inputVal);
});
function rollDice(dice){
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width">
<title>JS Bin</title>
</head>
<body>
<label>Game:</label><input type="text" id="input" value="0" />
<button id="btn">Submit</button>
<script>
document.getElementById("btn").addEventListener("click",function(){
var inputVal=document.getElementById("input").value*1;
rollDice(inputVal);
});
function rollDice(dice){
for(var i =0;i<dice;i++){
var x = Math.random()*100;
console.log(x);}
}
</script>
</body>
</html>
for(var i =0;i<dice;i++){
var x = Math.random()*100;
console.log(x);}
}
</script>**

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

Unchecking a checkbox and modifying value of sum

I am trying to design a menu. If you check a box, then sum get added up and if you uncheck it, the sum is reduced. I face trouble in reducing the sum while unchecking the box and also the value of sum is not globally changed. Please help me out.
<head>
<script>
var sum=0;
function a(sum,num) {
sum=sum+num;
document.getElementById("demo").innerHTML=sum;
}
</script>
</head>
<body>
<input type="checkbox" name="Dal" id="dal" onclick=a(sum,10)>Dal<br>
<input type="checkbox" name="Rice" id="rice" onclick=a(sum,20)>Rice<br>
<h1> Total Price is : </h1>
<p id="demo"> 0 </p>
</body>
Change the markup, add a value and a class, and remove the inline JS
<input type="checkbox" name="Dal" id="dal" value="10" class="myClass">Dal
<input type="checkbox" name="Rice" id="rice" value="20" class="myClass">Rice
<h1> Total Price is : </h1><p id="demo">0</p>
Then do
<script type="text/javascript">
var inputs = document.getElementsByClassName('myClass'),
total = document.getElementById('demo');
for (var i=0; i < inputs.length; i++) {
inputs[i].onchange = function() {
var add = this.value * (this.checked ? 1 : -1);
total.innerHTML = parseFloat(total.innerHTML) + add
}
}
</script>
FIDDLE
You can do something like this:
function a (elem, num) {
var k = (elem.checked) ? 1 : -1;
sum = sum + k * num;
document.getElementById("demo").innerHTML = sum;
}
And in the HTML:
<input type="checkbox" name="Dal" id="dal" onclick="a(this, 10);">Dal<br>
<input type="checkbox" name="Rice" id="rice" onclick="a(this, 20);">Rice<br>
Try something like this:
var sum = 0;
function a(id, num) {
if(id.checked == true){
sum += num;
id.onclick = function() { a(id, num)};
}
else {
sum -= num;
id.onclick = function() { a(id, num)};
}
document.getElementById("demo").innerHTML=sum;
}
Fiddle: http://jsfiddle.net/95pvc/2/
My own take would involve removing the event-handling from the HTML (unobtrusive JavaScript) for easier maintenance in future, using data-* attributes to contain the price and using a class-name to identify the relevant ingredients, to give the following HTML:
<input class="ingredients" type="checkbox" name="Dal" data-price="10" id="dal" />Dal
<input class="ingredients" type="checkbox" name="Rice" data-price="20" id="rice" />Rice
<h1> Total Price is : </h1>
<p id="demo">0</p>
Which leads to the following JavaScript:
var ingredients = document.getElementsByClassName('ingredients');
function price() {
var result = document.getElementById('demo'),
curPrice = 0,
ingredients = document.getElementsByClassName('ingredients');
for (var i = 0, len = ingredients.length; i < len; i++) {
if (ingredients[i].checked) {
curPrice += parseFloat(ingredients[i].getAttribute('data-price'));
}
}
result.firstChild.nodeValue = curPrice;
}
for (var i = 0, len = ingredients.length; i < len; i++) {
ingredients[i].addEventListener('change', price);
}
JS Fiddle demo.
To avoid having to iterate through the relevant checkboxes, it might be better to wrap those input elements in a form, and then bind the event-handling to that form:
var ingredients = document.getElementsByClassName('ingredients');
function price() {
var result = document.getElementById('demo'),
curPrice = 0,
ingredients = document.getElementsByClassName('ingredients');
for (var i = 0, len = ingredients.length; i < len; i++) {
if (ingredients[i].checked) {
curPrice += parseFloat(ingredients[i].getAttribute('data-price'));
}
}
result.firstChild.nodeValue = curPrice;
}
document.getElementById('formID').addEventListener('change', price);
JS Fiddle demo.
References:
addEventListener().
element.getAttribute().
getElementsByClassName().
parseFloat().

Method to sum up all input values always returns 0

Why do I get only zero in my calculation?
Code:
<?php echo 'AU$ <input type="text" name="pay_total" class="amount_text_change" id="amount_textbox_'.$i.'" onChange="UpdateValue_'.$i.'()" onKeyUp="AddInputs()" value="1">'; ?>
<td>Total</td>
<td>AU$ <span id="Display"></span></td>
Javascript:
function AddInputs()
{
var total = 0;
//var coll = document.getElementsByTagName("input")
var coll = document.getElementsByTagName("pay_total")
for ( var i = 0; i<coll.length; i++)
{
var ele = coll[i];
total += parseInt(ele.value);
}
var Display = document.getElementById("Display");
Display.innerHTML = total;
}
This javascript will auto add everytime user enter a numeric value in the textbox, but it's strange, the result is zero, must be something missing, can you help me?
Thanks
This...
document.getElementsByTagName("pay_total")
should be...
document.getElementsByName("pay_total")

Categories

Resources