I have the following markup in HTML:
<div class="rf-row count-container">
<input class="sum-monthly">
<div class="sub-rf-row">
<input class="add-monthly">
</div>
<div class="sub-rf-row">
<input class="add-monthly">
</div>
<div class="sub-rf-row template">
<input class="add-monthly">
</div>
</div>
And I want to add all inputs with class 'add-monthly' inside each sub-rf-row (excluding template sub-rf-rows) to the 'sum-monthly' inside rf-row (it's parent).
I want to calculate the sum values before user input (on document.ready). As well as dynamically update it on a 'keyup' event on one of the add-monthly inputs.
How can I best do this in jQuery?
You can do something like this...
$(document).ready(function()
{
updateValues()
$('.sub-rf-row').keyup(updateValues);
});
function updateValues()
{
var sum=0;
$('.sub-rf-row:not(.template) input').each(function(){
sum+=parseInt($(this).val()=='' ? 0 : $(this).val());
});
$('.sum-monthly').val(sum);
}
https://jsfiddle.net/rt42fz9q/13/
In order to acheive your goal, you need to reference the desired input fields, iterate through them and calculate their sum, finally place that sum in the .add-monthly field. But you nedd to watch out for the non-numeric values that may be present in some fields, so, in the sumUpdate function below I only add the input field's value to the sum only if that value is a valid number, also decimal numbers are allowed.
Here's a snippet to illustrate all what being said:
$(function(){
var sumInput = $('.rf-row input.sum-monthly'),
/* the 'sumInput' variable is the input field that will display the sum of the other inputs */
inputs = $('.sub-rf-row:not(.template) input.add-monthly');
/* the 'inputs' variable is an array containing the input fields with the class '.add-monthly' that are under '.sub-rf-row' element which doesn't have a '.template' class */
// Call the updateSum function to calculate the sum directly after the document has loaded.
updateSum();
// Adding KeyUp event listener to the inputs
inputs.on('keyup', updateSum);
// Implementation of the updateSum function that will calcule the sum of the input fields.
function updateSum() {
sum = 0;
inputs.each(function() {
var val = +$(this).val(); // Notice the plus sign in front of $(this).val() with we cast the input value to an integer, the val variable could contain of value of NaN if the input value can't be casted to an input(in other words if the input value contains non-numeric characters). With that we also allow decimal numbers.
sum += (val.toString() != 'NaN') ? val:0; // We only add valid numbers, otherwise we add 0 to the sum variable.
});
sumInput.val(sum.toFixed(2).replace('.00', '')); // Assign the sum variable's value to the sumInput, allowing precision to only 2 decimal digits, and also stripping '.00' from the sum variable if it contains a natural number(like 2.00 => 2, 10.00 => 10, but any decimal number will remain the same: 2.8 => 2.80, 12.97 => 12.97).
}
});
<!-- I added some values for the input fields with '.add-monthly' class just to show that the 'updateSum' function executes when the document is loaded -->
<div class="rf-row count-container">
<input class="sum-monthly">
<div class="sub-rf-row">
<input class="add-monthly" value="2.4">
</div>
<div class="sub-rf-row">
<input class="add-monthly" value="8.2">
</div>
<div class="sub-rf-row template">
<input class="add-monthly">
</div>
</div>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
Ps: I added some helpful comments to the code above, try to read them as they may help you.
Hope I pushed you further.
This may help yours
<!DOCTYPE html>
<html>
<head>
Demo
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
</head>
<body>
<div class="rf-row count-container">
<input class="sum-monthly">
<div class="sub-rf-row">
<input class="add-monthly" value="5">
</div>
<div class="sub-rf-row">
<input class="add-monthly" value="5">
</div>
<div class="sub-rf-row template">
<input class="add-monthly" value="5">
</div>
</div>
<script>
$(document).ready(function(){
var value = 0;
$('.count-container .sub-rf-row').each(function(){
value += parseInt($(this).find('.add-monthly').val()) ? parseInt($(this).find('.add-monthly').val()) : 0
})
$('.sum-monthly').val(value);
});
</script>
</body>
</html>
https://codepen.io/anon/pen/gdpZpR?editors=1010
Related
it does not returns prpoer answer it returnes NAN in Answer
<html>
<head>
<script type="text/javascript">
function pro(n,p)
{
var number=parseInt(n);
var powe=parseInt(p);
for(var i=1;i<powe;i++)
{
number*=number;
}
document.getElementById("answer").value=number;
}
</script>
</head>
<body>
<form name="F" >
Enter Number <input type="text" name="num" id="num"/>
Enter Power <select name="powe" id="powe">
<option value="2" >square</option>
<option value="3" >cube</option>
</select>
Answer<input type="text" name="Answer" id="answer" />
<input type="button" onClick="pro(num,powe)" value="Calculate" />
</form>
</body>
</html>
The issue is this: onClick="pro(num,powe)". Instead of the values for num and powe being gotten from the input elements and passed into the pro function, the actual element references (which are not numbers) are being passed.
To solve this problem, you'll need to get the values of the elements. But, before you just make a quick edit to your code, don't use inline HTML event attributes (onclick) in the first place. Instead, separate your JavaScript from your HTML and set up event handlers using modern standards with .addEventListener() as shown below.
Also (FYI):
Since you aren't actually submitting form data anywhere, you don't
need a <form> element.
It's not necessary to use parseInt with p.value because that
value is coming from your select and you've already set those at
whole numbers.
Don't bother with self-terminating tags (<input />) as you
gain nothing from using them.
If you are expecting only numeric input, it's better to use input
type=number which restricts the user input to numbers. Making this change also saves you from worrying about parseInt on the input number being misinterpreted as other bases than 10.
Since you don't want the user to be able to change the result of the
operation, it's better to display it in a non-editable element, like
a span.
It's a good idea to move your <script> element to just before the
closing body tag because, by the time the parser reaches that
point, all your HTML elements will have been parsed into memory.
<html>
<head>
</head>
<body>
<div>
Enter Number <input type="number" name="num" id="num">
</div>
<div>
Enter Power
<select name="powe" id="powe">
<option value="2">square</option>
<option value="3">cube</option>
</select>
</div>
<div>
Answer <span id="answer"></span>
</div>
<div>
<input type="button" value="Calculate">
</div>
<script>
// Get references to the inputs, the answer container and the button
let inputNum = document.getElementById("num");
let power = document.getElementById("powe");
let answer = document.getElementById("answer");
let btn = document.querySelector("input[type='button']");
// Set up the click event handler for the button
btn.addEventListener("click", function(){
// Now you need to get the input values and pass them
// to the function that will act with them
pro(inputNum.value, power.value);
});
function pro(n,p) {
var number = parseInt(n);
for(var i = 1; i < p; i++) {
number *= number;
}
answer.textContent = number;
}
</script>
</body>
</html>
Try
document.getElementById("answer").innerHTML = number
I'm extremely new to this so please excuse my spaghetti code - I'm trying to make a webpage that keeps track of basketball statistics live during a game, and then saves the total statistics using php afterwards. For now, I just need to pass the variable that is being live updated from my html page to php at the press of a button. I'm pretty sure I'm not even close, but am getting the 'undefined index' message when trying this. Here is my html page:
<head>
<meta charset="utf-8">
<title>Scoring</title>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/2.0.0/jquery.min.js"></script>
<script type="text/javascript">
var points = 0;
var assists = 0;
var rebounds = 0;
function add1point(){
points++;
document.getElementById('displaypoints').innerHTML = '<p>Points: ' + points;
}
function add2points(){
points = points + 2;
document.getElementById('displaypoints').innerHTML = '<p>Points: ' + points;
}
function add3points(){
points = points + 3;
document.getElementById('displaypoints').innerHTML = '<p>Points: ' + points;
}
function add1assist(){
assists++;
document.getElementById('displayassists').innerHTML = '<p>Assists: ' + assists;
}
function add1rebound(){
rebounds++;
document.getElementById('displayrebounds').innerHTML = '<p>Rebounds: ' + rebounds;
}
</script>
</head>
<body>
<center>
<br>
<button onclick="add1point()">+1 Point (Made Free-Throw)</button>
<br>
<br>
<button onclick="add2points()">+2 Points (Made Field-Goal)</button>
<br>
<br>
<button onclick="add3points()">+3 Points (Made Three-Pointer)</button>
<br>
<br>
<br>
<button onclick="add1assist()">+1 Assist</button>
<br>
<br>
<br>
<button onclick="add1rebound()">+1 (Offensive) Rebound</button>
<br>
<br>
<button onclick="add1rebound()">+1 (Defensive) Rebound</button>
<br>
<br>
<br>
<br>
<form method="post" attribute="post" action="scoring.php">
<div id="displaypoints"><script type="text/javascript">document.write('<p>Points: ' + points);</script></div>
<div id="displayassists"><script type="text/javascript">document.write('<p>Assists: ' + assists);</script></div>
<div id="displayrebounds"><script type="text/javascript">document.write('<p>Rebounds: ' + rebounds);</script></div>
<br>
<br>
<br>
<input type="submit" name="finish" id="finish" value="Finish Game">
</button>
</form>
</center>
</body>
</html>
And my php code:
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>Game Finished</title>
</head>
<body>
<?php
$points = $_POST['points'];
$assists= $_POST['assists'];
$rebounds = $_POST["rebounds"];
?>
</p>
</body>
Any help at all would be greatly appreciated :)
I rewrote some parts of your code. I hope you don't mind :).
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Scoring</title>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/2.0.0/jquery.min.js"></script>
</head>
<body>
<center>
<br>
<button onclick="addPoints(1)">+1 Point (Made Free-Throw)</button>
<br>
<br>
<button onclick="addPoints(2)">+2 Points (Made Field-Goal)</button>
<br>
<br>
<button onclick="addPoints(3)">+3 Points (Made Three-Pointer)</button>
<br>
<br>
<br>
<button onclick="addAssists(1)">+1 Assist</button>
<br>
<br>
<br>
<button onclick="addRebounds(1)">+1 (Offensive) Rebound</button>
<br>
<br>
<button onclick="addRebounds(1)">+1 (Defensive) Rebound</button>
<br>
<br>
<br>
<br>
<form method="post" attribute="post" action="scoring.php">
<p>Points: <span id="displaypoints"></span></p>
<p>Assists: <span id="displayassists"></span></p>
<p>Rebounds: <span id="displayrebounds"></span></p>
<!-- Any input element with "name" attribute will be sent to server (scoring.php script). -->
<input type="hidden" name="points" id="points" />
<!-- Any input element with "name" attribute will be sent to server (scoring.php script). -->
<input type="hidden" name="assists" id="assists" />
<!-- Any input element with "name" attribute will be sent to server (scoring.php script). -->
<input type="hidden" name="rebounds" id="rebounds" />
<br>
<br>
<br>
<input type="submit" name="finish" id="finish" value="Finish Game">
</form>
</center>
<script type="text/javascript">
// Initial values
var points = 0;
var assists = 0;
var rebounds = 0;
// Find "span" element with "displaypoints" id.
$displayPoints = $("#displaypoints");
// Set element text to initial points value.
$displayPoints.text(points);
// Find "span" element with "displayassists" id.
$displayAssists = $("#displayassists"),
// Set element text to initial assists value.
$displayAssists.text(assists);
// Find "span" element with "displayrebounds" id.
$displayRebounds = $("#displayrebounds");
// Set element text to initial rebounds value.
$displayRebounds.text(rebounds);
// Function that receives the amount of points.
// 1. Adds received amount of points to current amount of points.
// 2. Sets the corresponding element text to current amount of points.
// 3. Sets the element that's going to be sent to server value to current amount of points.
function addPoints(amount){
points += amount;
$displayPoints.text(points);
$("#points").val(points);
}
// Function that receives the amount of assists.
// 1. Adds received amount of assists to current amount of assists.
// 2. Sets the corresponding element text to current amount of assists.
// 3. Sets the element that's going to be sent to server value to current amount of assists.
function addAssists(amount){
assists += amount;
$displayAssists.text(assists);
$("#assists").val(assists);
}
// Function that receives the amount of rebounds.
// 1. Adds received amount of rebounds to current amount of rebounds.
// 2. Sets the corresponding element text to current amount of rebounds.
// 3. Sets the element that's going to be sent to server value to current amount of rebounds.
function addRebounds(amount){
rebounds += amount;
$displayRebounds.text(rebounds);
$("#rebounds").val(rebounds);
}
</script>
</body>
</html>
As James' comment said you could do it easily by inputs in your form. I guess you do not want that the user may change the value at the finish of the game, so you could use input hidden, something like this:
<form method="post" action="scoring.php">
<div id="displaypoints"><script type="text/javascript">document.write('<p>Points: ' + points+'</p><input type="hidden" name="points" value="'+points+'">');</script></div>
...
<input type="submit" name="finish" id="finish" value="Finish Game">
I have a form. On this form I when I add line items I save the input value then prepend it to the form. This part works. Keep in mind the form is not being submitted I am just adding to the dom dynamically
In the part of the form I save there is a price input. I am using jquerypriceformat plugin to format the price into price format. For example 111 becomes $1.11. If I do not use the plugin it works. The plugin does work as intended. I think my problem is that after I type the value is being changed and I need to retain that value somehow.
Here is a fiddle
https://jsfiddle.net/ks2z5mdo/7/
I think the fiddle will better show what the problem is. Basically when you type a description type a quantity and price, the price gets formatted then hit the add button all the data is saved except the price.
How can I solve this?
So first is the form
<div class="form-row">
<strong>Line Items:</strong>
<br>
<div class="line-items">
<div class="line-item">
<div class="line-item-box description">
<label>Description:</label>
<textarea name="description" id="description"></textarea>
</div><!--
--><div class="line-item-box quantity">
<label>Quantity:</label>
<input type="text" name="quantity" id="quantity">
</div><!--
--><div class="line-item-box price">
<label>Price:</label>
<input type="text" name="price" id="price">
</div>
<button class="btn add-item">Add Item</button>
</div>
</div>
</div>
Then is the jquery
$(document).ready(function() {
$('#price').priceFormat();
$('.add-item').click(function() {
if ($('description, #quantity, #price').filter(function() { return $(this).val(); }).length > 0) {
var description = $('#description').val();
var quantity = $('#quantity').val();
var price = $('#price').val();
$('.line-items').prepend('<div class="line-item"><div class="line-item-box description">' + description + '</div><div class="line-item-box quantity">' + quantity + '</div><div class="line-item-box price">' + price*quantity + '</div><button class="btn remove-btn">Remove</button></div>');
return false;
} else {
alert('Line item empty');
}
});
$(document).on('click', '.remove-btn', function() {
$('.line-item').remove();
});
});
Your var price = $('#price').val(); adds a $ and a space in front of the actual value that you are trying to get. Therefore, one solution is to get the substring of this value to remove the $:
var price = $('#price').val().substring(2);
This will leave the value as a number rather than the string it was originally made to be. Here is a fiddle that works.
I'm using a widget on a web page but learning to code
this is the code i insert into my page:
<script type="text/javascript" src="https://api.bistri.com/bistri.conference.widget.js"></script>
<div class="bistri-conference"
data-appid="hidenfromquestion"
data-appkey="hiddenfromquestion"
data-room="meetingroom1"
data-capacity="10"
data-media-controls="true"
data-audio-codec="ISAC/16000"
data-audio-birate="40"
data-video-birate="400"
data-device="320x240:12"
data-chat="True">
</div>
one of the variables "data-room" i wish to change the value by way of user input. what script/code do i need in order to ask the user for the input and then replace the default value "meetingroom1"
Thanks
Let us say you have an input
<input id="myInput" type="text"/>
Add JS like following
$("#myInput").blur(function(){
$(".bistri-conference").data("room", $(this).val());
});
One approach, using plain JavaScript in this case, is as follows; first showing the HTML:
<!-- wrapping the <inputs> used to update the data in a <form> -->
<form action="#" method="post">
<!-- using <label> elements to allow clicking the text to
focus the relevant <input> -->
<label>Change the meeting room venue:
<!-- using a custom data-* attribute to
clearly denote the data to be
updated by the <input> element's value -->
<input data-attribute="room" type="text" />
</label>
<label>Change the venue capacity:
<input data-attribute="capacity" type="text" />
</label>
<!-- a <button> to trigger the updates: -->
<button type="button" id="update">Update</button>
</form>
<!-- your own posted element, unchanged -->
<div class="bistri-conference" data-appid="hidenfromquestion" data-appkey="hiddenfromquestion" data-room="meetingroom1" data-capacity="10" data-media-controls="true" data-audio-codec="ISAC/16000" data-audio-birate="40" data-video-birate="400" data-device="320x240:12" data-chat="True"></div>
And the JavaScript:
function updateData() {
var inputArray = Array.prototype.slice.call(this.form.querySelectorAll('input'), 0),
toUpdate = document.querySelector('.bistri-conference');
inputArray.forEach(function (input) {
if (input.value !== input.defaultValue) {
toUpdate.dataset[input.dataset.attribute] = input.value;
}
});
}
document.getElementById('update').addEventListener('click', updateData);
// a named function:
function updateData() {
// Using Function.prototype.call() to use
// Array.prototype.slice() to convert the NodeList
// returned by 'querySelectorAll()' to be converted
// into an Array:
var inputArray = Array.prototype.slice.call(this.form.querySelectorAll('input'), 0),
// retrieving the element to be updated by this function:
toUpdate = document.querySelector('.bistri-conference');
// iterating over the array of <input> elements, using
// Array.prototype.forEach():
inputArray.forEach(function(input) {
// the 'input' is the current array-element
// from the array over which we're iterating.
// if the value of the <input> is not the
// default-value of the <input>:
if (input.value !== input.defaultValue) {
// we update the data-* attribute of the
// element equivalent to the value held in
// the <input> element's 'data-attribute',
// setting it to the value entered in the <input>:
toUpdate.dataset[input.dataset.attribute] = input.value;
}
});
}
// binding the 'click' event-handler function (note the lack of
// of parentheses after the function's name) of the button:
document.getElementById('update').addEventListener('click', updateData);
label {
display: block;
}
div[data-room]::before {
content: 'current value: ' attr(data-room);
display: block;
}
div[data-room]::after {
content: 'current value: ' attr(data-capacity);
display: block;
}
<form action="#" method="post">
<label>Change the meeting room venue:
<input data-attribute="room" type="text" />
</label>
<label>Change the venue capacity:
<input data-attribute="capacity" type="text" />
</label>
<button type="button" id="update">Update</button>
</form>
<div class="bistri-conference" data-appid="hidenfromquestion" data-appkey="hiddenfromquestion" data-room="meetingroom1" data-capacity="10" data-media-controls="true" data-audio-codec="ISAC/16000" data-audio-birate="40" data-video-birate="400" data-device="320x240:12"
data-chat="True"></div>
JS Fiddle demo.
References:
Array.prototpe.forEach().
Array.prototype.slice().
document.getElementById().
document.querySelector().
document.querySelectorAll().
Function.prototype.call().
HTMLElement.dataset.
HTMLInputElement.
if you are looking something like this ... then try this ;)
<head>
<script type="text/javascript" src="https://api.bistri.com/bistri.conference.widget.js"></script>
<script src="https://code.jquery.com/jquery-1.10.2.js"></script>
<script type="text/javascript">
function Onblur(event) {
var element=document.getElementById("something").value;
$(".bistri-conference").attr("data-room", element);
}
</script>
</head>
<body>
<div class="bistri-conference"
data-appid="hidenfromquestion"
data-appkey="hiddenfromquestion"
data-room="meetingroom1"
data-capacity="10"
data-media-controls="true"
data-audio-codec="ISAC/16000"
data-audio-birate="40"
data-video-birate="400"
data-device="320x240:12"
data-chat="True">
<input type="text" id="something" onblur="javascript:Onblur(event)" value="Text field" />
</div>
</body>
I'm attempting to make a form that asks the user for a number of units, then asks whether or not they would like those units to be provisioned, and depending on the answer, generates text fields corresponding with the number of units the typed in, along with a text field asking for an account number.
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.6.2/jquery.min.js">
</script>
<script type="text/javascript">
function Getunits(value) {
var units = document.getElementById('units');
for(count=0; count<=units; count++) {
$("<input type='text'>").appendTo("inpane");
}
document.getElementByTag('futureacc').InnerHTML='What is your account number? <input type="text" value="accountnum">';
}
</script>
</head>
<body>
<div id="container">
<form method="post" action="sendcontact.php">
<div id="unitammount" class="inpane">
Number of units ordered: <input type="text" name="units" id="units"/><br />
</div>
<div id="futureacc" class="inpane">
Are these units to be provisioned? <input type="radio" name="select" value="yes" onClick="Getunits('units.value')"/> Yes <input type="radio" name="select" value="no"/> No
</div>
Obviously I would like the new text fields to appear inside the futureacc div and inpane div respectively.
I don't know whether it's the loop that doesn't do anything or that I'm not appending correctly but as I currently have it this does nothing...
Any help would be greatly appreciated.
You had a number of errors with your code. It was confusing because you were mixing jQuery and pure Javascript. It's generally better to just use jQuery if you've decided to use it anyway. Your loop should have been iterating while it was smaller than units.val(), not while it was smaller than or equal to units. innerHTML is spelled with a lowercase "i," and your appendTo selector needed a period before the class name. I went ahead and cleaned up your code so it should work now!
HTML:
<div id="container">
<form method="post" action="sendcontact.php">
<div id="unitammount" class="inpane">
Number of units ordered: <input type="text" name="units" id="units"/>
</div><br>
<div id="futureacc" class="inpane">
Are these units to be provisioned? <input type="radio" name="select" value="yes" onClick="getUnits()"/> Yes <input type="radio" name="select" value="no"/> No <br>
</div>
</form>
</div>
Javascript:
function getUnits() {
var units = $("#units").val();
for (var count = 0; count < units; count++) {
$("<input type='text' /><br>").appendTo("#futureacc");
}
$("#futureacc").append('<br>What is your account number? <input type="text" placeholder="accountnum">');
}
WORKING DEMO
var units = document.getElementById('units');
needs to be
var units = document.getElementById('units').value;
you are passing value to onclick but it is a string will not give you exact value anyway you are not using it in you function so it doesnt have any side effect.
also you need to some error check to make sure that user has entered a number
with
for(count=0; count<=units; count++)
You are adding 1 more text box than user entered value. so if user has entered 4 you are creating 5 <= should be changed to <
This is wrong
onClick="Getunits('units.value')"
Instead use this:
onClick="Getunits(units.value)"
try this
$(document).ready(function(){
$('input[name=select]').click(function(){
if($(this).val() ==='yes'){
var numberOfTextboxes = $('#units').val();
for(var i =0; i<numberOfTextboxes; i++){
$('#unitammount').append('<input type="text" />');
}
}
});
});
See the fiddle