I would like to change the value of a textarea and an input field. The whole thing should happen with an onclick. Unfortunately, my approach seems to be wrong. I would be happy about tips.
<textarea class="input" name="adresse" readonly="readonly" id="street" value="test"></textarea>
<input style="width:130px;text-align: left" class="input" type="text" name="kundennr" id="kundennr" value="10000">
<?php
$sql = "SELECT * FROM `kunde` ORDER BY `kundennummer` ASC";
foreach ($dbh->query($sql) as $nav) {
$address = $nav['adresse'];
$name = $nav['kundennummer'];
echo "
<input type='text' name='textfield' id='textfield$name' value='$address'>
<a> | Kundennr: </a><a href='#' id='text' onclick='updateTxt(this);' >$name</a><br>
";
}
?>
</div>
</div>
<script>
function updateTxt(el)
{
var inhalt = el.text;
var field2 = document.getElementById('textfield'+inhalt).value;
document.getElementById('kundennr').value =inhalt;
document.getElementById('street').innerHTML = field2;
}
</script>
Update:
Thanks to all I found the solution
Sorry, But can't run PHP code here so added dummy data as your PHP code will render.
This should work:
function updateTxt(el) {
var inhalt = el.innerHTML;
var field2 = document.getElementById('textfield' + inhalt).value;
document.getElementById('kundennr').value = inhalt;
document.getElementById('street').innerHTML = field2;
}
<textarea class="input" name="adresse" cols=50 rows=10 readonly="readonly" id="street" value=""></textarea>
<input style="width:130px;text-align: left" class="input" type="text" name="kundennr" id="kundennr" value="">
<!-- <?php
$sql = "SELECT * FROM `kunde` ORDER BY `kundennummer` ASC";
foreach ($dbh->query($sql) as $nav) {
$address = $nav['adresse'];
$name = $nav['kundennummer'];
echo "
<input type='text' name='textfield' id='textfield$name' value='$address'>
<a> | Kundennr: </a><a href='#' id='text' onclick='updateTxt(this);' >$name</a><br>
";
}
?> -->
<input type="text" name="textfield" id="textfieldstreet1" value="Add1..">
<a> | Kundennr: </a>street1<br>
<input type="text" name="textfield" id="textfieldstreet2" value="Add2...">
<a> | Kundennr: </a>street2<br>
<input type="text" name="textfield" id="textfieldstreet3" value="Add3...">
<a> | Kundennr: </a>street3<br>
<input type="text" name="textfield" id="textfieldstreet4" value="Add4...">
<a> | Kundennr: </a>street4<br>
I think you are looking for how to update an textarea value with JS. It is not the same as input field and can be done like this;
document.getElementById('myTextarea').value = ''New value";
where textarea is:
<textarea id="myTextarea">Initial value, will be overwritten</textarea>
Related
I have an associative array $row[Description, Name, ID_Item]. When a user select "Name" by event onchange into function I want to pass 2 variables $row[Description] and $row[ID_Item].
So, I guess it should be something like:
<form action="/delete.php" method="post">
<select name="NameSelect" id="ID_Select" onchange = "ShowItemInfo('.$row['ID_Item'].', '.$row['Description'].' ,)">
<?php
while ($row = $res->fetch_assoc())
{
echo '<option value = " '.$row['Description'].''.'¶'.''.$row['ID_Item'].' " > '.$row['Name'].' </option>';
}
mysqli_free_result($res);
mysqli_close($conn);
?>
</select>
It doesn't work, so can anybody help? Because due to inability to pass these variables I have to pass them via DOM with separator "¶" but it is obviously a crutch:
<!DOCTYPE html>
<html lang="en">
<head>
<title>Delete your records</title>
</head>
<body>
<h2>
<?php
$conn = mysqli_connect("www.mywebsite.com", "username", "password", "Goods")
or die ('Cannot connect to db');
$query = "select ID_Item, Name,Description from Item";
$res = mysqli_query($conn, $query);
?>
<form action="/delete.php" method="post">
<select name="NameSelect" id="ID_Select" onchange = "ShowItemInfo()">
<?php
while ($row = $res->fetch_assoc())
{
echo '<option value = " '.$row['Description'].''.'¶'.''.$row['ID_Item'].' " > '.$row['Name'].' </option>';
}
mysqli_free_result($res);
mysqli_close($conn);
?>
</select>
<button type="submit"> Delete! </button>
<br> <br> <br> <br>
<textarea id="Desc" name="Desc" rows="4" cols="50" readonly>
Please, choose an item!
</textarea>
<br><br><br><br>
<label for="ID_Item">Identificator of an item:</label>
<input type="number" id="ID_Item" name="ID_Item" value="42" readonly >
</form>
</h2>
<script>
function ShowItemInfo() {
var str = document.getElementById("ID_Select").value;
var res = str.split("");
var Id = 0;
var Description = "";
var i = 1;
while (res[i] != "¶") {
Description = Description.concat(res[i]);
i++;
}
for (var j = i+1; j < res.length - 1; j++) {
Id = 10 * Id + parseInt(res[j],10);
}
document.getElementById("Desc").value = Description;
document.getElementById("ID_Item").value = Id;
}
</script>
</body>
</html>
Instead of adding values using separator you can use custom html attributes and set one value inside these attributes . So , your php code for options will look like below :
echo '<option desc=".$row['Description']." value = ".$row['ID_Item']." > '.$row['Name'].' </option>';
Demo Code :
function ShowItemInfo() {
//get selector
var selector = document.getElementById("ID_Select")
var Id = selector.value; //value
var Description = selector.options[selector.selectedIndex].getAttribute("desc"); //custom attribute desc
//set them
document.getElementById("Desc").value = Description;
document.getElementById("ID_Item").value = Id;
}
<select name="NameSelect" id="ID_Select" onchange="ShowItemInfo()">
<option desc="soemthing1" value="1"> sss</option>
<option desc="soemthing2" value="2"> sss2</option>
<option desc="soemthing3" value="3"> sss3</option>
</select>
<button type="submit"> Delete! </button>
<br> <br> <br> <br>
<textarea id="Desc" name="Desc" rows="4" cols="50" readonly>
Please, choose an item!
</textarea>
<br><br><br><br>
<label for="ID_Item">Identificator of an item:</label>
<input type="number" id="ID_Item" name="ID_Item" value="42" readonly>
Update 1 :
You can achieve same by passing value whenever onchange event is called .
Demo Code :
function ShowItemInfo(Id, Description) {
//set them
document.getElementById("Desc").value = Description;
document.getElementById("ID_Item").value = Id;
}
<!--pass values as parameter using `this`-->
<select name="NameSelect" id="ID_Select" onchange="ShowItemInfo(this.value,this.options[this.selectedIndex].getAttribute('desc'))">
<option desc="soemthing1" value="1"> sss</option>
<option desc="soemthing2" value="2"> sss2</option>
<option desc="soemthing3" value="3"> sss3</option>
</select>
<button type="submit"> Delete! </button>
<br> <br> <br> <br>
<textarea id="Desc" name="Desc" rows="4" cols="50" readonly>
Please, choose an item!
</textarea>
<br><br><br><br>
<label for="ID_Item">Identificator of an item:</label>
<input type="number" id="ID_Item" name="ID_Item" value="42" readonly>
I am working with dynamic text boxes.
I want to add the data that is entered in the text boxes to my database.
My markup:
<form name="reaction" id="reaction" method="post" action="./send.php">
<input type="text" name="number[]" id="number1" value="15" placeholder="Number 1" /> <br />
<input type="text" name="name[]" id="name1" value="aaaa" placeholder="Name 1" /> <br />
<input type="text" name="price[]" id="price1" value="10" placeholder="Price 1" /> <br />
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script>
$(document).on('click', '#add_row', function(){
count++;
$('#total_item').val(count);
var html_code = '';
html_code += '<input type="text" placeholder="Number '+count+'" name="number[]" id="number'+count+'" data-srno="'+count+'" /><br />';
html_code += '<input type="text" placeholder="Name '+count+'" name="name[]" id="name'+count+'" data-srno="'+count+'" /><br />';
html_code += '<input type="text" placeholder="Price '+count+'" name="price[]" id="price'+count+'" data-srno="'+count+'" /><br />';
html_code += '<button type="button" name="remove_row" id="'+count+'" class="btn btn-danger btn-xs remove_row">X</button><br />';
});
</script>
<button type="submit" class="btn btn-primary" name="send">Save</button>
</form>
Which results in the following document fragment:
<form name="reaction" id="reaction" method="post" action="./send.php">
<input type="text" name="number[]" id="number1" value="15" placeholder="Number 1" /> <br />
<input type="text" name="name[]" id="name1" value="aaaa" placeholder="Name 1" /> <br />
<input type="text" name="price[]" id="price1" value="10" placeholder="Price 1" /> <br />
<input type="text" name="number[]" id="number2" value="12" placeholder="Number 2" /> <br />
<input type="text" name="name[]" id="name2" value="bbbb" placeholder="Name 2" /> <br />
<input type="text" name="price[]" id="price2" value="15" placeholder="Price 2" /> <br />
<input type="text" name="number[]" id="number3" value="38" placeholder="Number 3" /> <br />
<input type="text" name="name[]" id="name3" value="cccc" placeholder="Name 3" /> <br />
<input type="text" name="price[]" id="price3" value="29" placeholder="Price 3" /> <br />
<button type="submit" class="btn btn-primary" name="send">Save</button>
</form>
When submitting the form I want to add the following data to the database:
| session_id | number | name | price |
|-------------|----------|----------|----------|
| 1 | 15 | aaaa | 10 |
| 1 | 12 | bbbb | 15 |
| 1 | 38 | cccc | 29 |
In my PHP code I am using the following to define the text boxes:
foreach($_POST['number'] as $i => $item) {
When I execute the script I only get the data of the first three textboxes. I get in my database:
| session_id | number | name | price |
|-------------|----------|----------|----------|
| 1 | 15 | aaaa | 10 |
After weeks of doing research I have discovered that there is something wrong with the JavaScript part of the code. When I send the data with the text boxes in the second example I get the result I want. When I use JavaScript to create the dynamic text boxes the PHP script will only post the first row (that is not created with JavaScript) to the database.
What is wrong with my script?
Here is the script I am using to add data to my database:
<?php
$correct = true;
$_SESSION['session_id'];
$number = $_POST['number'] ;
$name = $_POST['name'] ;
$price = $_POST['price'] ;
if($correct){
foreach($_POST['number'] as $i => $item) {
$db = new PDO('mysql:host=localhost;dbname=db', 'user', 'pass');
$query= "INSERT INTO products(session_id, number, name, price) VALUES (:session_id, :number, :name, :price)";
$stmt = $db->prepare($query);
$exec = $stmt->execute(array(
':session_id' => $_SESSION['session_id'],
':number' => $_POST["number"][$i],
':name' => $_POST["name"][$i],
':price' => $_POST["price"][$i]
));
}
}
else
{
header('Location: ../error.php');
}
?>
Result of var_dump on $_POST['number']:
array(1) { [0]=> string(2) "15" }
The main problem is that all your fields in the form have the same name, even though they are supposed to be arrays, you're not really allowing for multiple rows.
The easiest (not necessarily the optimal) way is to make some tweaks
Change your form element names to
variable[$i][number]
variable[$i][name]
variable[$i][price]
and make sure your form changes the value for $i on each row, so that your form becomes:
<form name="reaction" id="reaction" method="post" action="./send.php">
<input type="text" name="variable[0][number]" id="number1" value="15" placeholder="Number 1" /> <br />
<input type="text" name="variable[0][name]" id="name1" value="aaaa" placeholder="Name 1" /> <br />
<input type="text" name="variable[0][price]" id="price1" value="10" placeholder="Price 1" /> <br />
<input type="text" name="variable[1][number]" id="number1" value="15" placeholder="Number 1" /> <br />
<input type="text" name="variable[1][name]" id="name1" value="aaaa" placeholder="Name 1" /> <br />
<input type="text" name="variable[1][price]" id="price1" value="10" placeholder="Price 1" /> <br />
and so on...
Then, alter your form processing to iterate over $variable:
foreach($variable as $var)
{
$number = $var['number'];
$name = $var['name'];
$price = $var['price'];
// do whatever it is you do with the variables and then loop to the next row
}
that's it!
Like I said, this is not necessarily the best way to accomplish your goal, but it is by far the easiest
You can keep your form fields with the array names, but in order to post your data to the database, you will need to iterate through the array.
So your receiving page should collected all the form data in a $_POST variable, and then you can parse the posted values as $_POST['number'] and iterate through the array using a for-each loop.
foreach ($_POST['price'] as $key => $value) {
// do something with array value
echo "{$key} => {$value} ";
print_r($_POST['price']);
}
Dont inject pure html but play with DOM.
<form name="reaction" id="reaction" method="post" action="./send.php">
<button type="submit" class="btn btn-primary" name="send">Save</button><br />
</form>
<script>
function newInput(type, value, count){
var newInput = document.createElement('input');
newInput.type = 'text';
newInput.name = type+'[]';
newInput.id = type+count;
newInput.value = value;
newInput.placeholder = type+' '+count; // <--you probably want to camelize this
return newInput;
}
function addRow(number, name, price, count, target){
target.appendChild(newInput('number', number, count));
target.appendChild(newInput('name', name, count));
target.appendChild(newInput('price', price, count));
target.appendChild(document.createElement('br')); // <-- create any element
}
var myForm = document.getElementById('reaction');
var count = 0;
addRow(111, 'one', 1, ++count, myForm);
addRow(222, 'two', 2, ++count, myForm);
addRow(333, 'three', 3, ++count, myForm);
addRow(444, 'four', 4, ++count, myForm);
</script>
PHP part looks almost OK:
$post_number = $_POST['number'];
$post_name = $_POST['name'];
$post_price = $_POST['price'];
//check, if needed set session variables here, then
$ses_id = session_id();
$db = new PDO('mysql:host=localhost;dbname=test', 'root', '');
$query= "INSERT INTO products(session_id, number, name, price) VALUES (:session_id, :number, :name, :price)";
foreach($_POST['number'] as $i => $item) {
$stmt = $db->prepare($query);
$exec = $stmt->execute(array(
':session_id' => $ses_id,
':number' => $post_number[$i],
':name' => $post_name[$i],
':price' => $post_price[$i]
));
if($exec == false)
header('Location: ../error.php');
//or print out what happened
//$e = $stmt->errorInfo();
//print_r($e);
//die();
}
Right now I have code to dynamically add input fields to my form. I want to be able to submit the data and go to the next page but if someone decides to go back, the newly made input fields would still be there with the data. The way I have it set up now is to echo onto the input fields which works with the first two but not the third.
When I hit back, I get this:
Here is my code:
<h2>Enter Beneficiaries for Tangible Personal Property:</h2>
<form method="post" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>">
<div class="input_fields_container">
<tr>
<td>Name:<input type="text" name="ben[]" value="<?php echo $_SESSION['ben']['0'];?>" class="form-control name_list" /></td>
<td>Percentage of tangible personal property:<input type="number" min="0" max="100" value="<?php echo $_SESSION['percent']['0'];?>" style="width: 40px" name="percent[]" class="form-control name_list" /></td>
<td><input type="button" name="add" id="add" class="add_more_button" value= "Add Another" ></input></td>
</tr>
</table>
</div>
<p style="color:red;"></p>
<h3>Enter Contingent Beneficiary: </h3>
Name:<input type="text" name="conben" value="<?php echo $_SESSION['conben'];?>" >
<br><br>
<button type="button" name="back" value="back" onclick="location.href='county.php'">Back</button>
<input type="submit" name="submitform" value="Next"></input>
<button type="button" name="download" onclick="location.href='downloadAdd.php'">Download will</button>
</form>
<script>
//script to add/remove fields
$(document).ready(function () {
var getControl=getCookie("countControls1");
var max_fields_limit = 2; // Set limit for maximum input fields
var x = 0; // Initialize counter for text box
for(var i=1; i<=getControl; i++) {
console.log(i);
addControls();
}
$('.add_more_button').click(function (e) { // Click event to add more fields
addControls();
});
function addControls()
{
console.log(x);
if (x < max_fields_limit ) {
x++; // Increment counter
setCookie("countControls1",x,100);
$('.input_fields_container').append('<div><tr id="row'+x+'"><td> Name:<input type="text" name="ben[]" value="<?php echo $_SESSION['ben']['1'];?>" class="form-control name_list" /></td><td> Percentage of tangible personal property:<input type="number" min="0" max="100" style="width: 40px" name="percent[]" value="<?php echo $_SESSION['percent']['1'];?>" class="form-control name_list" /></td><td>Remove</td></tr>');; // Add input field
}
else if (x==2){
$("p").text("*Only 3 tangible beneficiaries are allowed.");
}
}
$('.input_fields_container').on("click", ".remove_field", function (e) { // User click on remove text links
$(this).parent('div').remove();
x--;
$("p").text("");
setCookie("countControls1",x,100);
});
function setCookie(cname,cvalue,exdays)
{
var d = new Date();
d.setTime(d.getTime() + (exdays*24*60*60*1000));
var expires = "expires=" + d.toGMTString();
document.cookie = cname + "=" + cvalue + ";" + expires + ";path=/";
$("#div1").html("Add cookie = ",getCookie(cname));
}
function getCookie(cname)
{
console.clear();
var name = cname + "=";
var decodedCookie = decodeURIComponent(document.cookie);
var ca = decodedCookie.split(';');
//console.log(cname);
//console.log(decodedCookie);
console.log(ca);
for(var i = 0; i < ca.length; i++) {
var c = ca[i];
while (c.charAt(0) == ' ') {
c = c.substring(1);
}
if (c.indexOf(name) == 0) {
console.log(c.substring(name.length, c.length));
return (c.substring(name.length, c.length));
}
}
return "";
}
});
</script>
Is there anyway to achieve this in this way or do I need to implement something else?
You can just write the fields back using a loop because presumably you have the two arrays in your session. You should also use empty() or isset() to check if the session arrays exist first otherwise you will end up with warnings about undefined keys and such:
<tr>
<td>Name:<input type="text" name="ben[]" value="<?php echo $_SESSION['ben']['0'];?>" class="form-control name_list" /></td>
<td>Percentage of tangible personal property:<input type="number" min="0" max="100" value="<?php echo $_SESSION['percent']['0'];?>" style="width: 40px" name="percent[]" class="form-control name_list" /></td>
<td><input type="button" name="add" id="add" class="add_more_button" value= "Add Another" /></td>
</tr>
<?php
# Remove the first keys since you already used them above
unset($_SESSION['percent'][0],$_SESSION['ben'][0]);
# Just do a normal loop to create any remaining values
foreach($_SESSION['percent'] as $key => $value): ?>
<tr>
<td>Name:<input type="text" name="ben[]" value="<?php echo $_SESSION['ben'][$key];?>" class="form-control name_list" /></td>
<td>Percentage of tangible personal property:<input type="number" min="0" max="100" value="<?php echo $value; ?>" style="width: 40px" name="percent[]" class="form-control name_list" /></td>
</tr>
<?php endforeach ?>
I have this form in the view:
<form method="POST" action="<?php echo Yii::$app->request->baseUrl;?>/telephone/addnow/" role="form" enctype="multipart/form-data">
<label>Upload your photo:</label><input type="file" name="image" ><br>
<input type="name" name="name" id="name" placeholder="Name" required><br><br>
<input type="text" name="address" placeholder="Address"><br><br>
<input type="text" name="telephone" placeholder="Telephone number" required>
<br><br>
<div id="dynamicInput">
<br><input type="text" name="myinputs[]" placeholder="Secondary Phone #1">
<span class="glyphicon glyphicon-plus" onClick="addInput('dynamicInput');"></span>
<br><br>
</div>
<input type="text" name="mobile" placeholder="Mobile number" > <br><br>
<input type="email" name="email" placeholder="Email">
<input type="email" name="altemail" placeholder="Alternative Email"><br><BR>
<input type="text" name="company_name" placeholder="Company Name"><br><BR>
<input type="text" name="company_address" placeholder="Company Address"><br><br>
<input type="text" name="company_phone_primary" placeholder="Company Telephone">
<input type="text" name="company_phone_secondary" placeholder="Telephone Secondary "><br><br>
<input type="text" name="company_email" placeholder="Company Email Address"><br><BR>
<button type="submit" class="btn btn-default">Submit</button><BR><BR>
</form>
allowing the user to insert any number of secondary phones i used this javascript code:
<script>
var counter = 1;
var limit = 10;
function addInput(divName) {
if (counter == limit) {
alert("You have reached the limit of adding " + counter + " inputs");
} else {
var newdiv = document.createElement('div');
newdiv.innerHTML = "Seconday Phone # " + (counter + 1) + " <br><input type='text' name='myinputs[]' placeholder='Secondary Phone '>";
document.getElementById(divName).appendChild(newdiv);
counter++;
}
}
</script>
And I have this controller code:
public function actionAddnow()
{
$request = Yii::$app->request;
$add=new telephone();
$add->Name=$request->post('name');
$add->Email=$request->post('email');
$add->Mobile=$request->post('mobile');
$add->Address=$request->post('address');
$add->Telephone=$request->post('telephone');
$add->altemail=$request->post('altemail');
$add->company_name=$request->post('company_name');
$add->company_address=$request->post('company_address');
$add->company_phone_primary=$request->post('company_phone_primary');
$add->company_phone_secondary=$request->post('company_phone_secondary');
$add->company_email=$request->post('company_email');
$add->save();
$getlast=Yii::$app->db->getLastInsertId();
$myinputs=$request->post('myinputs');
$totalinputs=sizeof('$myinputs');
for ($i=0; $i<=$totalinputs; $i++) {
$inputs=$myinputs[$i];
$phones=new phone();
$phones->secondary_phones=$inputs;
$phones->id=$getlast;
$phones->save();
}
return $this->redirect(Yii::$app->request->baseUrl.'/telephone/index');
}
but only the first two values of $myinputs are inserted in the database.
Putting variable $myinputs between single quotation marks ('$myinputs') you will convert your variable to string. sizeof is alias for count function, but as you give argument as string you allways get result as 1. After you will loop with condition ($i=0; $i<=$totalinputs; $i++) meaning that cycle will run 2 times when $i is 0 and when $i is 1.
Instead of:
$totalinputs=sizeof('$myinputs');
You should use
$totalinputs=sizeof($myinputs);
Another error is in your cycle condition.
for ($i=0; $i<=$totalinputs; $i++)
Should be
for ($i=0; $i<$totalinputs; $i++)
Or you could replace for cycle with foreach
foreach($myinputs as $inputs)
{
$phones=new phone();
$phones->secondary_phones=$inputs;
$phones->id=$getlast;
$phones->save();
}
On Yii side of improvements
1.For form you could use ActiveForm widget
$form = \yii\widgets\ActiveForm::begin([
'options' => [
"role" => "form",
"enctype"=> "multipart/form-data",
], ]);
echo $form->field($add, 'Name');
//etc
$form->end();
2.If you would use ActiveField for creating input fields in view or adding manually field names in format like ModelClassName[ModelFieldName], then you would be able to use Model load for assaign'ing values
Example:
$add=new telephone();
if ($add->load(Yii::$app->request->post()))
{
if ($add->save())
{//saved
}
else
{//error
}
}
else
{//no post data
}
3.For urls its probably not needed to add request baseUrl property. Example in redirect you can simply use
$this->redirect('/telephone/index');
4.Using method getLastInsertId() may lead to errors when there are some triggers in database that will create additional rows. So it may be wiser to use:
$getlast=$add->id;//assuming model autoincrement field name is "id"
I can't get this to work.
I got two forms, "mult" and "mult2" with a script making some simple calculations running through both. Both fields are dependent on data in another form called "recipe".
The thing is, i can actually get one of the forms to work doing it like i have done (see all my code under here) - the weird thing is that it's only mult2 that works and does all the calculations. Mult1 is not doing anything. The fields that needs to be updated in the end is "gravity" and "gravity2" - and only "gravity2" gets updated with the result of the calculation.
I know it's some long code bits here, but hope you can help me..
Here is the "recipe" form:
<form name="recipe">
<input type="text" size="1" maxlength="3" name="batchVal" value="30" onChange="calculate(malt1); calculate(malt2)"></td>
<input type="text" size="1" maxlength="3" name="efficiencyVal" value="75" onChange="calculate(malt1); calculate(malt2)"></td>
</form>
Here is the two forms, "mult" and "mult2" that both need the same datainputs from "recipe" form:
<form name="mult">
<select id="malt" name="malt" onChange="UpdateNextField(this,'ppg')">
<option>Choose fermentable..</option>
<?php
$query = $mysqli->prepare("SELECT id,maltname,maltebc,maltppg FROM malt WHERE mainid = ?");
$mainidcolumn = "1";
/* bind parameters */
$query->bind_param("i", $mainidcolumn);
$query->execute();
$menu_result = $query->get_result();
/* now you can fetch the results into an array */
while ($menu = $menu_result->fetch_assoc()) {
echo '<option value="'.$menu['maltppg'].'">' . $menu['maltname'] . ' ' . $menu['maltebc'] . ' EBC</option>';
}
echo '</select>';
?>
<input type="text" id="ebcfield" size="1" maxlength="3">
<input type="text" name="weightVal" size="1" maxlength="5" value="0" onChange="calculate(malt1)">
<input name="grainpercent" type="text" id="grainpercent" size="1" maxlength="2">
<input type="text" id="gravity" size="1" value="0" maxlength="4">
<input name="graincolor" type="text" id="graincolor" size="1" maxlength="3">
<input type="text" name="ppgVal" id="ppg" onMouseMove="calculate(malt1)">
</form>
<form name="mult2">
<select id="malt" name="malt" onChange="UpdateNextField(this,'ppg2')">
<option>Choose fermentable..</option>
<?php
$query = $mysqli->prepare("SELECT id,maltname,maltebc,maltppg FROM malt WHERE mainid = ?");
$mainidcolumn = "1";
/* bind parameters */
$query->bind_param("i", $mainidcolumn);
$query->execute();
$menu_result = $query->get_result();
/* now you can fetch the results into an array */
while ($menu = $menu_result->fetch_assoc()) {
echo '<option value="'.$menu['maltppg'].'">' . $menu['maltname'] . ' ' . $menu['maltebc'] . ' EBC</option>';
}
echo '</select>';
?>
<input type="text" id="ebcfield" size="1" maxlength="3">
<input type="text" name="weightVal2" size="1" maxlength="5" value="0" onChange="calculate(malt2)">
<input name="grainpercent" type="text" id="grainpercent" size="1" maxlength="2">
<input type="text" id="gravity2" size="1" value="0" maxlength="4">
<input name="graincolor" type="text" id="graincolor" size="1" maxlength="3">
<input type="text" name="ppgVal2" id="ppg2" onMouseMove="calculate(malt2)">
</form>
And finally the javascript that does the calculations based on data in the input fields. Calculate(malt1) and Calculate(malt2) does the same thing, it's just two instances of the same calculation.
<script type = "text/javascript">
function UpdateNextField(which,ppg) {
document.getElementById(ppg).value = which.value;
}
function UpdateNextField(which,ppg2) {
document.getElementById(ppg2).value = which.value;
}
</script>
<!-- calculations for malt 1-5 -->
<!-- form 1 - fermentable 1 -->
<script type="text/javascript">
function calculate(malt1){
var weightVal = document.mult.weightVal.value;
var ppgVal = document.mult.ppgVal.value;
var batchVal = document.recipe.batchVal.value;
var efficiencyVal = document.recipe.efficiencyVal.value;
var showValue = 0;
var showValue = ((weightVal * ppgVal * 0.000008345) * (efficiencyVal) * 10) / batchVal + (1000);
showValue = Math.round(showValue * 1) / 1;
if (!isNaN(showValue)) {
document.getElementById('gravity').value = showValue;
}
}
function calculate(malt2){
var weightVal2 = document.mult2.weightVal2.value;
var ppgVal2 = document.mult2.ppgVal2.value;
var batchVal = document.recipe.batchVal.value;
var efficiencyVal = document.recipe.efficiencyVal.value;
var showValue2 = 0;
var showValue2 = ((weightVal2 * ppgVal2 * 0.000008345) * (efficiencyVal) * 10) / batchVal + (1000);
showValue2 = Math.round(showValue2 * 1) / 1;
if (!isNaN(showValue2)) {
document.getElementById('gravity2').value = showValue2;
}
}
</script>
You have a few problems with your function names and duplicate IDs, as noted by Jay and LcLk. But, assuming you fix these, you can save a lot of time and grief by using jQuery. For example:
HTML
<input type="text" id="first" />
<input type="text" id="second" />
Javascript
$("#first").keypress(function(){
/* your custom code goes here */
console.log("A key was pressed.");
});
What this says is that anytime a key is pressed while the first input is selected, it will print out A key was pressed in the console. You can then either directly call your calculation functions from within that anonymous inner function, or pass them directly into keypress();.