Dynamically print alternative string character from two different string - javascript

I'm trying to print alternative character form two different string dynamically. I did below code but it's give me "TrAaUuSt" this output. but I want "TrAaUuStIF". How can I solve this? Anyone can help me? Thank You in advance. I'm new in PHP. If you have better solution then please suggest me.
<?php
/*$str1 = "TAUSIF";
$str2 = "raut";
Output = TrAaUuSt*/
if(isset($_POST['submit']))
{
$str1 = $_POST['str1'];
$str2 = $_POST['str2'];
$strlen1 = strlen($str1);
$strlen2 = strlen($str2);
if($strlen1 > $strlen2)
{
for($i = 0; $i<$strlen2; $i++){
$new[] = $str1[$i];
$new[] = $str2[$i];
}
}
else
{
for($i = 0; $i<$strlen1; $i++){
$new[] = $str1[$i];
$new[] = $str2[$i];
}
}
foreach($new as $str){
echo $str;
}
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Print alternative character.</title>
</head>
<body>
<form action="" method="post">
<input type="text" name="str1" ><br><br>
<input type="text" name="str2" ><br><br>
<input type="submit" name="submit" value="Submit" >
</form>
</body>
</html>

You could try something like this:
if(isset($_POST['submit']))
{
//$str1 = "TAUSIF";
//$str2 = "raut";
$str1 = $_POST['str1'];
$str2 = $_POST['str2'];
// SPLIT STRINGS TO ARRAY
$a1 = str_split($str1);
$a2 = str_split($str2);
$out = ''; // THE OUTPUT STRING
// CHECK WHICH STRING IS LONGEST
$count = (count($a1) > count($a2)) ? count($a1) : count($a2);
// LOOP BASED ON THE NUMBER OF CHARACTERS IN LONGEST STRING
for ($x = 0; $x <= $count; $x++) {
$out .= (isset($a1[$x])) ? $a1[$x] : '';
$out .= (isset($a2[$x])) ? $a2[$x] : '';
}
echo $out; // TrAaUuStIF
}
NOTE:
If you need Unicode support, then you should consider making your own str_split function as described in the top voted comment here: http://php.net/str_split

<?php
/*$str1 = "TAUSIF";
$str2 = "raut";
Output = TrAaUuSt*/
if(isset($_POST['submit']))
{
$str1 = $_POST['str1'];
$str2 = $_POST['str2'];
$strlen1 = strlen($str1);
$strlen2 = strlen($str2);
if($strlen1 > $strlen2)
{
for($i = 0; $i<$strlen2+$strlen1; $i++){
$new[] = $str1[$i];
$new[] = $str2[$i];
}
}else
{
for($i = 0; $i<$strlen1+$strlen2; $i++){
$new[] = $str1[$i];
$new[] = $str2[$i];
}
}
foreach($new as $str){
echo $str;
}
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Print alternative character.</title>
</head>
<body>
<form action="" method="post">
<input type="text" name="str1" ><br><br>
<input type="text" name="str2" ><br><br>
<input type="submit" name="submit" value="Submit" >
</form>
</body>
</html>

Related

Im trying to move the same value from page to another in php

I want to move a value from page stepone php to page steptwo php
the value is generated automatically by js on stepone php,
and then I want to use the same value ( id for the submission ) on steptwo php
any ideas ?
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
</head>
<body>
<form action="action_pageone.php" method="POST">
<label for="FullName">Full Name</label><br>
<input type="text" id="FullName" name="FullName"><br>
<!-- this input -->
<input type="hidden" name="ID" id="ID" value="" maxlength="16" size="16">
<!-- this input -->
<input type="submit" value="Submit">
</form>
<script>
function randomNumber(len) {
var randomNumber;
var n = '';
for (var count = 0; count < len; count++) {
randomNumber = Math.floor(Math.random() * 10);
n += randomNumber.toString();
}
return n;
}
window.onload = function() {
document.getElementById("ID").value = randomNumber(9);
};
</script>
</body>
</html>
and the action_pageone here it is
so i need to copy this ID to the other page mentioned ( steptwo)
the exact ID
<?php
$ID = $_POST['ID'];
$FullName = $_POST['FullName'];
// Database Connection
$servername = "localhost";
$username = "";
$password = "";
$db = "";
$conn = new mysqli('localhost', 'username', 'password', 'db') or die($conn->connect_error);
$conn->set_charset("utf8");
if ($conn->connect_error){
die("Connection failed: ". $conn->connect_error);
}
$sql = "insert into Registration(ID,FullName) values('$ID','$FullName')";
if ($conn->query($sql) === TRUE) {
header('location: steptwo.php');
} else {
echo " Registration not Success ";
}
$conn->close();
?>
any suggestions guys ?
for me it doesnt matter if its js or php , i need it to work :(
You can use the Web Cache,like cookie or session,then use the php to read this ID value.
there is many ways to do it
use input type hidden and keep pushing it on submit buttons
pass it in URL like google.com?id=2&name=mike and fetch it using $_GET['id']
keep it in session/cookie/js webstorage
You can do this in 2 ways, use hidden form and submit it or use ajax to post it.
hidden form
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
</head>
<body>
<form action="action_pageone.php" method="POST" name="form1">
<label for="FullName">Full Name</label><br>
<input type="text" id="FullName" name="FullName"><br>
<!-- this input -->
<input type="hidden" name="ID" id="ID" value="" maxlength="16" size="16">
<!-- this input -->
<input type="button" onclick = "submit()" value="Submit">
</form>
<form action="action_pagetwo.php" method="POST" name="form2">
<!-- this input -->
<input type="hidden" name="ID" id="ID" value="" maxlength="16" size="16">
<!-- this input -->
</form>
<script>
function submit()
{
document.forms['form1'].submit();
document.forms['form2'].submit();
//wait what form to submit?.. confused...? yes me 2 lol
}
function randomNumber(len) {
var randomNumber;
var n = '';
for (var count = 0; count < len; count++) {
randomNumber = Math.floor(Math.random() * 10);
n += randomNumber.toString();
}
return n;
}
window.onload = function() {
document.getElementById("ID").value = randomNumber(9);
};
</script>
</body>
</html>
This might a way to achieve what you want but might be inappropriate as after the form gets submitted it actually redirects to the action page. But still you can sort out how you want your response by yourself.
Ajax (after receiving ID in your first php file you pass it to the second one)
<?php
$ID = $_POST['ID'];
$FullName = $_POST['FullName'];
if($ID != NULL)
echo '<script>
$.ajax({
url: "action_pagetwo.php",
type: "post",
data: {
id: '.$ID.'
},
success: function(result) {
console.log("done bro");
}
});
</script>';
// Database Connection
$servername = "localhost";
$username = "";
$password = "";
$db = "";
$conn = new mysqli('localhost', 'username', 'password', 'db') or die($conn->connect_error);
$conn->set_charset("utf8");
if ($conn->connect_error){
die("Connection failed: ". $conn->connect_error);
}
$sql = "insert into Registration(ID,FullName) values('$ID','$FullName')";
if ($conn->query($sql) === TRUE) {
header('location: steptwo.php');
} else {
echo " Registration not Success ";
}
$conn->close();
?>
You can pass the ID in your html page itself to both php files, but you should choose what you want, you want to pass it without redirecting or you wanna direct to page by submitting.

JQUERY change value of an variable input field

i want to change the value of my input field with jquery. The problem is, that the input field has a variable and i don't know how describe this in jquery.
Without the variable all the code works, but this doesn't help because i use the form different times on my page.
function doSth(click) {
var value = ($(click).val());
var name_ekt = $('[name="name[]"]').map(function() {
return $(this).val();
}).get();
var dat = $("#dat").val();
$.ajax({
type: "post",
url: "get_test.php",
data: {
name: name,
dat: dat,
value: value
},
cache: false,
success: function(value) {
$("#output").html(value);
}
});
event.preventDefault();
}
<!DOCTYPE html>
<html>
<head>
<link rel="stylesheet" type="text/css" href="../css/style.css">
<script src="../js/jquery-3.2.1.js"></script>
<script src="../js/jquery-ui.js"></script>
<title>Modul </title>
</head>
<body>
<br>
<input type="text" id="dat" value="2017-06-30">
<br>
<br>
<div>
<?php for ($i = 1; $i <= 6; $i++) { ?>
<form>
<?php for ($x=0; $x<2; $x++) { ?>
<input type='text' name='name[]' id="name[]"><br>
<?php } ?>
<button type='submit' id='save' value='<?php echo $i; ?>' onclick="doSth(this);">save</button>
<br><br>
</form>
<?php } ?>
</div>
<div id='output'></div>
</body>
</html>
<?php
if ($row = (($value*2)-1)) {
$sql = "INSERT INTO test (dat, name)
VALUES ('$dat', '$name[$row]')";
$conn->query($sql);
if(($conn->affected_rows)>0) {
echo "<script>
$(document).ready(function(){
$('#name[$row]').prop('disabled', true).css('background-color','#C1FFC1');
$('#dat').prop('disabled', true).css('background-color','#C1FFC1');
});
</script>";
echo $row;
}
}
?>
Edit your code to this,
function doSth(click) {
var value = ($(click).val());
var name_ekt = $("#name[]").map(function() {
return $(this).val();
}).get();
var dat = $("#dat").val();

PHP messages aren't being written to the log file - tutsplus.com tutorial

tutsplus, there you will find a tutorial which guides you through the steps on how to create a simple web chat. I tried to follow all that was said, yet I noticed a problem when testing. It seems that the usermsg is not being posted to the log.html file.
here is the index.php, which in this case is named chat.php:
<?php
function loginForm() {
echo '
<div id="loginform">
<form action="chat.php" method="post">
<p>Please enter your name to continue:</p>
<label for="name">Name:</label>
<input type="text" name="name" id="name">
<input type="submit" name="enter" id="enter" value="enter">
</form>
</div>
';
}
if(isset($_POST['enter'])) {
if($_POST['name'] != "") {
$_SESSION['name'] = stripslashes(htmlspecialchars($_POST['name']));
}else {
echo '<span class="error">Please type in a name</span>';
}
}
?>
<!DOCTYPE html>
<html>
<head>
<title>Basic Chat Service</title>
<meta charset="utf-8">
<link rel="stylesheet" href="style.css" title="style" type="text/css" media="screen" charset="utf-8">
</head>
<body>
<?php
if(!isset($_SESSION['name'])) {
loginForm();
}else{
?>
<div id="wrapper">
<div id="menu">
<div class="welcome">Welcome, <?php echo $_SESSION["name"]; ?></div>
<div class="logout">Exit Chat</div>
<div style="clear:both;"></div>
</div>
<div id="chatbox"><?php
if(file_exists("log.html") && filesize("log.html") > 0) {
$handle = fopen("log.html", "r");
$contents = fread($handle, filesize("log.html"));
fclose($handle);
echo $contents;
}
?></div>
<form name="message" action="">
<input type="text" name="usermsg" id="usermsg" size="63">
<input type="submit" name="submitmsg" id="submitmsg" value="Send">
</form>
</div>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.3/jquery.min.js" charset="utf-8"></script>
<script type="text/javascript">
//jQuery Document
$(document).ready(function() {
$("#exit").click(function() {
var exit = confirm("Are you sure you want to logout?");
if(exit == true) {
window.location = 'chat.php?logout=true';
}
});
$("#submitmsg").click(function() {
var clientmsg = $("#usermsg").val();
console.log(clientmsg);
$.post("post.php", {text: clientmsg});
$("#usermsg").attr("value", "");
return false;
});
function loadLog() {
var oldscrollHeight = $("#chatbox").attr("scrollHeight") - 20;
$.ajax({
url:"log.html",
cache: false,
success: function(html){
$("#chatbox").html(html);
var newscrollHeight = $("#chatbox").attr("scrollHeight") - 20;
if(newscrollHeight > oldscrollHeight) {
$("#chatbox").animate({scrollTop: newscrollHeight}, 'normal');
}
}
});
}
setInterval(loadLog, 2500);
});
</script>
<?php
}
if(isset($_GET['logout'])) {
$fp = fopen("log.html", 'a');
fwrite($fp, '<div class="msgln"><i>User '.$_SESSION['name'].' has left the chat session.</i><br></div>');
fclose($fp);
session_destroy();
header("Location: chat.php");
}
?>
</body>
</html>
Here is the post.php:
<?php
session_start();
if(isset($_SESSION['name'])) {
$text = $_POST['text'];
$fp = fopen("log.html", 'a');
fwrite($fp, "<div class='msgln'>(".date("g:i A").")<b>".$_SESSION['name']."</b>:".stripslashes(htmlspecialchars($text))."<br></div>");
fclose($fp);
}
?>
I am using MAMP, and the files are located in the htdocs folder, so that's not the problem.
Thanks in advance for any help you can give me, and let me know if you need more info.
You should call session_start() in index.php.
(from Marc B in the comments)

clear form and show new comment jquery php

I'm trying to do a comment form, that puts the comment in my mysql database, and puts the new comment on my page right after submitting (and clears the form). But somehow you have to always refresh to see the new comments and if you click on submit more than once it shows duplicated comments after refresh. How can I solve that problem? I'm kinda a noob, so my codes are mostly from tutorials that I don't fully understand yet...
my php-page:
<?php
// Error reporting:
error_reporting(E_ALL^E_NOTICE);
include "connect.php";
include "comment.class.php";
$comments = array();
$result = mysql_query("SELECT * FROM comments ORDER BY id ASC");
while($row = mysql_fetch_assoc($result))
{
$comments[] = new Comment($row);
}
?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
<title>Bausatz</title>
<meta name="" content="">
<link rel="stylesheet" href="css/normalize.css">
<link rel="stylesheet" href="css/main.css">
<script src="js/modernizr-2.7.1.min.js"></script>
<style type="text/css"></style>
<link href='http://fonts.googleapis.com/css?family=Montserrat:400' rel='stylesheet'
type='text/css'>
</head>
<body>
<header>
<div class="logo">
<span class="col">ON THE </span>W<span class="col">OODWAY</span>
</div>
<nav>
TRAVELS
BLOG
ME
</nav>
</header>
<div class="main">
<div class="contentwrapper">
<div class="entry">
</div>
<div class="comment">
<div id="each">
<?php
foreach($comments as $c){
echo $c->markup();
}
?>
</div>
<div id="addCommentContainer">
<p>Add a Comment</p>
<form id="addCommentForm" method="post" action="">
<div>
<label for="name">Your Name</label>
<input type="text" name="name" id="name" />
<label for="email">Your Email</label>
<input type="text" name="email" id="email" />
<label for="body">Comment Body</label>
<textarea name="body" id="body" cols="20" rows="5"></textarea>
<input type="submit" id="submit" value="Submit" >
</div>
</form>
</div>
</div>
</div>
</div>
<div class="unten">
<nav>
contact
copyright
</nav>
</div>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<script>window.jQuery || document.write('<script src="js/jquery-1.9.1.min.js">
<\/script>')</script>
<script type="text/javascript" src="js/comment.js"></script>
</body>
</html>
jQuery:
$(document).ready(function(){
var working = false;
$('#addCommentForm').submit(function(e){
e.preventDefault();
if(working) return false;
working = true;
$('#submit').val('Working..');
$('span.error').remove();
/* Sending the form fileds to submit.php: */
$.post('submit.php',$(this).serialize(),function(msg){
working = false;
$('#submit').val('Submit');
if(msg.status){
$(msg.html).hide().insertBefore('#addCommentContainer').slideDown();
$('#body').val('');
}
else {
$.each(msg.errors,function(k,v){
$('label[for='+k+']').append('<span class="error">'+v+'</span>');
});
}
},'json');
});
});
comment.class.php
<?php
class Comment
{
private $data = array();
public function __construct($row)
{
/*
/ The constructor
*/
$this->data = $row;
}
public function markup()
{
/*
/ This method outputs the XHTML markup of the comment
*/
// Setting up an alias, so we don't have to write $this->data every time:
$d = &$this->data;
$link_open = '';
$link_close = '';
// Converting the time to a UNIX timestamp:
$d['dt'] = strtotime($d['dt']);
return '
<div class="comment">
<div class="name">'.$link_open.$d['name'].$link_close.'</div>
<div class="date" title="Added at '.date('H:i \o\n d M
Y',$d['dt']).'">'.date('d M Y',$d['dt']).'</div>
<p>'.$d['body'].'</p>
</div>
';
}
public static function validate(&$arr)
{
/*
/ This method is used to validate the data sent via AJAX.
/
/ It return true/false depending on whether the data is valid, and populates
/ the $arr array passed as a paremter (notice the ampersand above) with
/ either the valid input data, or the error messages.
*/
$errors = array();
$data = array();
// Using the filter_input function introduced in PHP 5.2.0
if(!($data['email'] = filter_input(INPUT_POST,'email',FILTER_VALIDATE_EMAIL)))
{
$email = '';
}
// Using the filter with a custom callback function:
if(!($data['body'] =
filter_input(INPUT_POST,'body',FILTER_CALLBACK,array('options'=>'Comment::validate_text'))) )
{
$errors['body'] = 'Please enter a comment body.';
}
if(!($data['name'] = filter_input(INPUT_POST,'name',FILTER_CALLBACK,array('options'=>'Comment::validate_text'))))
{
$errors['name'] = 'Please enter a name.';
}
if(!empty($errors)){
// If there are errors, copy the $errors array to $arr:
$arr = $errors;
return false;
}
foreach($data as $k=>$v){
$arr[$k] = mysql_real_escape_string($v);
}
$arr['email'] = strtolower(trim($arr['email']));
return true;
}
private static function validate_text($str)
{
if(mb_strlen($str,'utf8')<1)
return false;
$str = nl2br(htmlspecialchars($str));
$str = str_replace(array(chr(10),chr(13)),'',$str);
return $str;
}
}
?>
submit.php
<?php
error_reporting(E_ALL^E_NOTICE);
include "connect.php";
include "comment.class.php";
$arr = array();
$validates = Comment::validate($arr);
if($validates)
{
mysql_query(" INSERT INTO comments(name,url,email,body)
VALUES (
'".$arr['name']."',
'".$arr['url']."',
'".$arr['email']."',
'".$arr['body']."'
)");
$arr['dt'] = date('r',time());
$arr['id'] = mysql_insert_id();
$arr = array_map('stripslashes',$arr);
$insertedComment = new Comment($arr);
echo json_encode(array('status'=>1,'html'=>$insertedComment->markup()));
}
else
{
echo '{"status":0,"errors":'.json_encode($arr).'}';
}
?>
connect.php
<?php
$db_host = '*****';
$db_user = '*****';
$db_pass = '*****';
$db_database = '*****';
$link = #mysql_connect($db_host,$db_user,$db_pass) or die('Unable to establish a DB connection');
mysql_query("SET NAMES 'utf8'");
mysql_select_db($db_database,$link);
?>
Why don't you try appending it to the rest of the comments?
Change this:
$(msg.html).hide().insertBefore('#addCommentContainer').slideDown();
To this:
$(msg.html).hide().appendTo('#each').slideDown();

Creating a loop in Javascript based on php variable

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.

Categories