Hi guys I am new to javascript and php and I have a problem
I'd like to sum the looped text box but I am lack at logics
here is the code
<form name="rec" action="this.php" method="post" >
<?php
$x = 0;
while($x<=5){
$x++;
echo "<input type='text' name='n". $x."' id='n". $x."'>< input type='text' name='y". $x."' id='y". $x."'>
<input type='text' name='res". $x."' id='res". $x."'>";
}
?>
<input type="button" value="Compute" onclicked="compute()">
</form>
< script >
ctr = 0<
while(ctr<=5){
ctr++;
x = Number(document.getElementById("n"+ctr).value)
y = Number(document.getElementById("y"+ctr).value)
ans = x+y;
document.getElementById("res"+ctr).value = ans;
}
< /script>
I would like to get the out put of like this
Thank you I am not really specific :D
try this
<form name="rec" action="#" method="post">
<?php
$x = 0;
while($x<=5){
$x++;
echo "<input type='text' name='n". $x."' id='n". $x."'><input type='text' name='y". $x."' id='y". $x."'>
<input type='text' name='res". $x."' id='res". $x."'><br>";
}
?>
<input type="button" value="Compute" onclick="compute()">
</form>
<script>
function compute()
{
var ctr = 0;
while(ctr<=5){
ctr++;
var x = Number(document.getElementById("n"+ctr).value);
var y = Number(document.getElementById("y"+ctr).value);
var ans = x+y;
document.getElementById("res"+ctr).value = ans;
}
}
</script>
Where is your compute function? You should enclose the contents of the <script> tag with function compute().
Related
<div id="kutu">
<?php
echo "<table ' border='1' width='200px'>";
echo "<tr>";
echo "<th>#</th>";
echo "<th>Oyuncu Adi</th>";
echo "</tr>";
for ($x = 1; $x <= $playernum; $x++) {
echo "<tr>";
echo "<td>$x </td>";
echo "<td><input id='serdar' type='text' name='player$x' > </td>";
echo "</tr>";
}
echo "</table>";
?>
<p> <input type="submit" value="Kayit Et!"></p>
</div>
Im taking $playernum from other page. In this table I will take players name and I wanna put this names to my mysql db with javascript ajax method. But I couldnt find the way.
My table looks like:
I suggest you change your input-text to the same name like this, instead of player$x:
<form method="POST">
<input type="text" name="player" /><br />
<input type="text" name="player" /><br />
<input type="text" name="player" /><br />
<input type="text" name="player" />
<p id="result"></p>
<button id="btn">Get Player Names</button>
</form>
For the javascript:
<script>
$("form").submit(function(e) {
e.preventDefault();
players = document.getElementsByName("player");
var result = [];
for (var i = 0; i < players.length; i++) {
result[i] = players[i].value;
}
$.post(
'index.php', {
data: result
},
function(msg) {
document.getElementById("result").innerHTML = msg;
}
);
});
</script>
I just created an empty array and stored the values of each input into it. Then sent that array over to the PHP file.
For the index.php file:
$data = $_POST["data"];
echo "From PHP<br/>";
foreach ($data as $d){
echo $d . "<br/>";
}
So you can use the variable $d to access individual player names.
Result image
I'm trying to get a list of radio inputs from a form that are grouped by their names, and they all have different names. I'm trying to create an array with them, if they are checked then append a 1 to the array, otherwise append a 0. None of the alert boxes pop up, so I assume that the function processDataForFinalization doesn't get called.
I didn't know if something was wrong with how I'm appending to the array. Or if it's a bigger error than that.
Thanks in advance.
EDIT4 Here is the updateBallot.php code
TwoResults.txt looks like:
0 0 0 0 0 0 0 0
3 4 1
<?php
$name = $_POST['name'];
$points = $_POST['points']; //array of user vote
echo $points;
$txt_file = file_get_contents($name.'Results.txt');
$rows = explode("\n", $txt_file); // rows-array separated by new line
foreach($rows as $row => $data)
{
$row_datas = explode(' ',$data);
}
$goods = $row_datas[0];
$goodies = $row_datas[1];
$newArr = [];
for($j=0;$j<count($points);$j++) {
$newArr[$j] = $goods[$j] + $points[$j];
}
$newText = "";
foreach($newArr as $nArr => $nData) {
$newText .= $nData." ";
}
$newText .= "\n";
$secondNewArr = [];
$sizeOfBottom = count($goodies);
for($k=0;$k<$sizeOfBottom;$k++) {
$secondNewArr[$k] = $goodies[$k];
}
foreach($secondNewArr as $neArr => $neData) {
$newText .= $neData." ";
}
$myFile = fopen($txt_file,"w+");
fwrite($myFile, $newText);
fclose($myFile);
?>
EDIT3 Here is the output HTML from the page.
<form action="submitElection.php" method="post">
<input type="hidden" name="id" value="20">
<input type="hidden" name="numQs" id="numQs">
<input type="hidden" name="arr" value="Array">
<script>
var a = document.getElementById("numQs");
a.value = numQs;
</script>
<div id='ballotElement'><h4><u>q</u></h4>
<input type="radio" name="input0" value="1">
a <br>
<input type="radio" name="input0" value="1">
a <br>
<input type="radio" name="input0" value="1">
a <br>
</div>
<script>
var numQs = 1;
</script>
<div id='ballotElement'><h4><u>q</u></h4>
<input type="radio" name="input1" value="1">
a <br>
<input type="radio" name="input1" value="1">
a <br>
<input type="radio" name="input1" value="1">
a <br>
<input type="radio" name="input1" value="1">
a <br>
</div>
<script>
var numQs = 2;
</script>
<div id='ballotElement'><h4><u>q</u></h4>
<input type="radio" name="input2" value="1">
a <br>
</div>
<script>
var numQs = 3;
</script>
<br><br><br>
<div class="submit">
<input type="submit" value="Submit ballot" class="btn btn-primary btn-large" onclick="return confirmSubmit()">
</div>
</form>
EDIT2 Here is the HTML from the page.
<form action="submitElection.php" method="post">
<input type="hidden" name="id" value="<?php echo $id;?>">
<input type="hidden" name="numQs" id="numQs">
<input type="hidden" name="arr" value="<?php echo $arr;?>">
<script>
var a = document.getElementById("numQs");
a.value = numQs;
</script>
<?php
if (file_exists($name.'.txt')) {
if($type==1) {
$inputType = "checkbox";
} else {
$inputType = "radio";
}
$txt_file = file_get_contents($name.'.txt');
$rows = explode("\n", $txt_file);
array_shift($rows);
$vals = 0;
foreach($rows as $row => $data)
{
$arrCount = 0; // number of elements in array
echo "<div id='ballotElement'>";
$row_data = explode('^',$data);
$info[$row]['questions'] = $row_data[0];
$info[$row]['answers'] = $row_data[1];
echo "<h4><u>".$info[$row]['questions'] . "</u></h4>";
//echo $info[$row]['answers'] . "<br>";
$lines = explode("~",$info[$row]['answers']);
foreach($lines as $line => $lData) {
$answers[$row][$line] = $lData;
if($answers[$row][$line] !== "") {
$arrCount++;
?>
<input type="<?php echo $inputType; ?>" name="input<?php echo $row; ?>" value="1">
<?php echo $answers[$row][$line]; ?>
<br>
<?php }
$vals++;
}
if($writeIn == "y") {
$arrCount++; ?>
<input type="text" name="writeIn<?php echo $row; ?>" placeholder="Write in">
<?php
}
echo "</div>";
array_push($arr, $arrCount);
?>
<script>
var numQs = <?php echo count($arr); ?>;
</script>
<?php
}
} else {
header('Location: error.php');
}
echo "<br><br><br>";
<input type="submit" value="Submit ballot" class="btn btn-primary btn-large" onclick="return confirmSubmit()">
</form>
EDIT getActualData() is called from getData()
Here is getData(), this function works, so I'm not sure why the getActualData() doesn't work since they are basically the same thing.
function getData() {
var parts = 0;
for(var i=0; i<numQs; i++){
var checked = false;
var inp = document.getElementsByName('input'+i);
for(var j=0; j<inp.length && checked == false; j++){
if(inp[j].checked) {
checked = true;
parts++;
}
}
}
if(parts != numQs){
window.alert('Please vote for at least one candidate per race.');
return false;
} else {
window.alert('Okay');
getActualData();
//return true;
}
}
function processDataForFinalization() {
$.ajax({
url: 'updateBallot.php',
type: 'post',
data: {"points" : val, "name":name},
success: function(data) {
// Do something with data that came back.
window.alert(data);
//return true;
}
});
}
var val = [];
function getActualData() {
for(var k=0;k<numQs;k++) {
var inpu = document.getElementsByName('input'+k);
for(var jk=0;jk<inpu.length;jk++) {
window.alert('almost there');
if(inpu[jk].checked) {
window.alert('hello');
val.array_push(1);
window.alert(val.length);
} else {
val.array_push(0);
}
}
}
processDataForFinalization();
}
I am working on a very simple php page. The user picks how many numbers they would like to be added up, then enters the numbers on the new page, clicks a button, and then the sum is displayed.
I cannot figure out how to add up the numbers though since I can't just assign variables to each number because of the loop. I've tried this not using loops, assigning variables to each one, and simply making the button add those variables, but that required making the code for the inputs many many times, and I want this to work with a loop in case I wanted to integrate the choice to pick hundreds of numbers or something. If php isn't the best thing for this, please let me know what would be better, but anyways... how do I add up the numbers that the user inputs?
Index page:
<p>How many number would you like to add?</p>
2<br>
3<br>
4<br>
5<br>
Calculator page:
<?php
$inputs = $_GET['inputs'];
?>
<div>Enter the numbers<br>
<?php
for ($x=0; $x < $inputs; $x++) {
echo '<input type="number"><br>';
}
?>
</div>
<form action='' method='post'><input type='submit' value='Find value' name='findvalue'></form>
<?php
if (isset($_POST['findvalue'])) {
}
?>
for ($x=0; $x < $inputs; $x++) {
echo '<input type="number"><br>';
}
You cant use input without any name. You can use dynamic name, for example:
for ($x=0; $x < $inputs; $x++) {
echo '<input type="number" name="number_'.$x.'"><br>';
}
Or better way to use array names:
for ($x=0; $x < $inputs; $x++) {
echo '<input type="number" name="number[]"><br>';
}
After that, var_dump your $_POST variable.
But, best way to create dynamic fields is creating one and clone it with javascript, when user want to add next value. Example with jQuery:
<div class="myInputs"><input type="number" name="numbers[]"></div>
Add input
<script>
$('#Add').click(function(){
$('.myInputs input:first').clone().appendTo(".myInputs");
return false;
});
Try this:
<?php
$inputs = $_GET['inputs'];
?>
<form action='' method='post'>
<div>Enter the numbers<br>
<?php
for ($x=0; $x < $inputs; $x++) {
echo '<input name="numbers[]" type="number"><br>';
}
?>
</div>
<input type='submit' value='Find value' name='findvalue'>
</form>
<?php
if (isset($_POST['findvalue'])) {
print_r($_POST["numbers"]);
}
?>
There is currently no JavaScript on your page. To interact with the client, JavaScript would be the best choice since there is no need to go to the backend to create input fields unless you need to save the number before interacting with the user
window.onload = function() {
document.getElementById("nums").onchange = function() {
var fields = document.getElementById("fields"),
numberOfField = parseInt(this.value, 10),
inputs = [];
for (var i = 0; i < numberOfField; i++) {
inputs.push('<input type="text" class="calcField" name="number' + i + '" />');
}
fields.innerHTML = inputs.length > 0 ? inputs.join("<br/>") : "";
}
document.getElementById("calc").onsubmit = function() {
var total = 0,
fields = document.querySelectorAll(".calcField");
for (var i = 0; i < fields.length; i++) {
var val = parseInt(fields[i].value, 10);
total += isNaN(val) ? 0 : val;
}
document.getElementById("total").value=total;
return false; // stop submission - remove to submit the form
}
}
<p>How many numbers would you like to add?</p>
<form id="calc">
<select id="nums">
<option value="0">Please select</option>
<option value="2">Two numbers</option>
<option value="3">Three numbers</option>
<option value="4">Four numbers</option>
</select>
<div id="fields"></div><hr/>
<input type="submit" value="Find value" /> <input type="text" id="total" />
</form>
try adding a hidden field for the number of inputs then use it to loop
<?php
$inputs = $_GET['inputs'];
?>
<form action='' method='post'><input type='submit' value='Find value' name='findvalue'>
<div>Enter the numbers<br>
<input type="hidden" name="numberofinputs" value="<?php echo $inputs;?>"/>
<?php
for ($x=0; $x < $inputs; $x++) {
//Please note the $x
echo '<input type="number'.$x.'"><br>';
}
?>
</div>
</form>
<?php
if (isset($_POST['findvalue'])) {
$numberOfinputs = $_POST['numberofinputs'];
for($i=0; $i<numberOfinputs; $i++){
//You can access it here
echo $_POST['number'.$i];
}
}
?>
One example on how to use JavaScript to add remove fields in dynamically generated forms.
<h3>javascript add remove fields in dynamically generated forms</h3>
<br>
modification of http://www.quirksmode.org/dom/domform.html
<br>
<br><br>
<?
$action_url = {form action here};
?>
<script type="text/javascript">
var i = 1;
function addCost(cost_no){
cn = cost_no;
//max nubmer of fields, for all cases together
if (i <= 300){
i++;
ident = 'cost['+cn+']['+i+']';
var div = document.createElement('div');
//div.style.width = "300px";
//div.style.height = "50px";
//div.style.color = "white";
div.setAttribute('class', 'myclass');
div.innerHTML = '<input type="text" \n\
name="'+ident+'" \n\
id="'+ident+'" \n\
> \n\
<input type="button" \n\
value="-" \n\
onclick="removeKid('+cn+', this)"\n\
>';
document.getElementById('kids'+cn+'').appendChild(div);
}
}
function removeKid(cost_no, div) {
//alert(test);
cn = cost_no;
document.getElementById('kids'+cn+'').removeChild( div.parentNode );
i--;
}
</script>
<form action="<?= $action_url;?>" method="post" >
<?
for ($cost_id=0; $cost_id<=10; $cost_id++)
{
echo "The form id is : $cost_id <br>";
?>
<div id="kids<?= $cost_id; ?>">
<input type="button"
id="add_cost<?= $cost_id; ?>"
onClick="addCost(<?= $cost_id; ?>)"
value="Add field:<?= $cost_id; ?>"
/>
</div>
<br>
<?
}
?>
<br>
<input type="submit" name="submit" value="submit" />(limit 300)
</form>
Let us say I have the following script, calculating a sum.
Here is the code:
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<script language="javascript" type="text/javascript">
function updatesum() {
line1 = ((document.form.price_1.value -0) * (document.form.number_1.value -0));
line2 = ((document.form.price_2.value -0) * (document.form.number_2.value -0));
line3 = ((document.form.price_3.value -0) * (document.form.number_3.value -0));
line4 = ((document.form.price_4.value -0) * (document.form.number_4.value -0));
line5 = ((document.form.price_5.value -0) * (document.form.number_5.value -0));
document.form.sum.value = line1 + line2 + line3 + line4 + line5;
}
</script>
</head>
<body>
<?php
$tR = 1;
$maxlines = 5;
echo '<form name="form" method="post" action="action.php">';
echo '<table><tbody>';
while($tR <= $maxlines)
{
echo '<tr>';
echo '<td width="1"><input name="price_' . $tR . '" onChange="updatesum();" type="text"></td>';
echo '<td width="1"> x </td>';
echo '<td width="1"><input name="number_' . $tR . '" onChange="updatesum();" type="text" value="1"></td>';
echo '</tr>';
++$tR;
}
echo '</tbody></table>';
echo 'Total: <input name="sum" value="0" type="text" readonly="readonly">';
echo '<button type="submit" name="Submit" style="display: hidden;">Submit</button>';
echo '</form>';
?>
</body>
</html>
And that's fine... But now i change the variable $maxlines from 5 to 500...
How do I adjust the Javascript, without having to write something like:
function updatesum() {
line1 = ((document.form.price_1.value -0) * (document.form.number_1.value -0));
line2 = ((document.form.price_2.value -0) * (document.form.number_2.value -0));
line3 = ((document.form.price_3.value -0) * (document.form.number_3.value -0));
line4 = ((document.form.price_4.value -0) * (document.form.number_4.value -0));
line5 = ((document.form.price_5.value -0) * (document.form.number_5.value -0));
line6 = ((document.form.price_6.value -0) * (document.form.number_6.value -0));
.......................
line500 = ((document.form.price_500.value -0) * (document.form.number_500.value -0));
document.form.sum.value = line1 + line2 + line3 + line4 + line5 + line6 ........... + line500;
}
You can use a loop to go through all the fields:
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<script language="javascript" type="text/javascript">
function updatesum() {
var prices = document.getElementsByName('price');
var numbers = document.getElementsByName('number');
var sum = 0;
for (var i = 0; i < prices.length; i++) {
sum += prices[i].value * numbers[i].value;
}
document.form.sum.value = sum;
}
</script>
</head>
<body>
<?php
$tR = 1;
$maxlines = 50;
echo '<form name="form" method="post" action="action.php">';
echo '<table><tbody>';
while($tR <= $maxlines)
{
echo '<tr>';
echo '<td width="1"><input name="price" onChange="updatesum();" type="text"></td>';
echo '<td width="1"> x </td>';
echo '<td width="1"><input name="number" onChange="updatesum();" type="text" value="1"></td>';
echo '</tr>';
++$tR;
}
echo '</tbody></table>';
echo 'Total: <input name="sum" value="0" type="text" readonly="readonly">';
echo '<button type="submit" name="Submit" style="display: hidden;">Submit</button>';
echo '</form>';
?>
</body>
</html>
You can easily transfer php variables to javascript like this
<script>
var maxlines = <?php echo $maxLines?>;
</script>
You now have a javascript variable maxlines equal to your php variable
Also, remember if you are transferring a string to put it in quotations
<script>
var myString = '<?php echo $myString?>';
</script>
The short version would be to update the script and have a loop there that does all this.
BUT (and a huge but that is)
There are a few things you can improve in your script, other than the solution itself.
You can try a different approach to your issue:
You don't have to bind a function to each input change element separately, and using onchange attributes in HTML is a little outdated method.
You don't have to define each line. You can sum them all up using JavaScript, without knowing how many of them you have.
I would rename your input elements name attribute into something you could work with in PHP, without knowing its size beforehand. For example, if you change the name of the attributes to name="price[]" and name="number[]", your values will magically be sent to your PHP script as $_POST["price"] and $_POST["number"]. From there, you can play with it dynammicaly.
And now to some real code:
By building the HTML as I've explained, you will end up with something following this idea:
<form name="form">
<input type="text" name="price[]" value="1" /><input type="text" name="number[]" value="10" /><br />
<input type="text" name="price[]" value="2" /><input type="text" name="number[]" value="20" /><br />
<input type="text" name="price[]" value="3" /><input type="text" name="number[]" value="30" /><br />
<input type="text" name="price[]" value="4" /><input type="text" name="number[]" value="40" /><br />
<br /><input type="text" name="sum" value="0" id="sum" />
</form>
And then, following the event binding techniques I suggested, your JavaScript will be simplified to something like this:
function updateSum() {
var prices = document.getElementsByName("price[]");
var numbers = document.getElementsByName("number[]");
var sum = 0;
for (var i=0; i < prices.length; i++) {
sum += prices[i].value * numbers[i].value;
}
document.getElementById("sum").value = sum;
}
var prices = document.getElementsByName("price[]");
var numbers = document.getElementsByName("number[]");
for (var i=0; i < prices.length; i++) {
prices[i].addEventListener('change', updateSum, false);
numbers[i].addEventListener('change', updateSum, false);
}
I've created a jsFiddle (http://jsfiddle.net/nXqgW/2/) showing this code in action.
You can use the code like that:
<script>
function updatesum() {
<?php $lines = array() ?>
<?php for($i = 0; $i < $count; $i++) : ?>
line<?= $i ?> = ((document.form.price_<?= $i ?>.value -0) * (document.form.number_<?= $i ?>.value -0));
<?php $lines[] = 'line' . $i;
<?php endfor; ?>
document.form.sum.value = <?= implode(' + ', $lines);
}
</script>
You need to output the javascript lines with PHP, so in PHP where you have your maxlines variables you can do a loop like;
<script>
...
<?php for($i = 0; $i < $maxlines; $i++) {
//Output javascript line
?>
line<?php echo $i; ?> = ((document.form.price_<?php echo $i; ?>.value -0) * (document.form.number_<?php echo $i; ?>.value -0));
<?php
} ?>
document.form.sum.value = 0 <?php for($int i = 0; $i < $maxlines; $i++) {
echo '+ line' . $i;
} ?>
</script>
I haven't tested this code, but it should work.