How to insert PHP 'generated' options (html select) dynamically using JavaScript? - javascript

I'm facing this trouble..
I have this JavaScript code:
echo "<script type=\"text/javascript\">
var counter = 1;
function addInput(divName){
var newdiv = document.createElement('div');
newdiv.innerHTML = \"Entry \" + (counter + 1) + \" <input type='text' name='myInputs[]'>\";
document.getElementById(divName).appendChild(newdiv);
counter++;
}
</script> ";
and this PHP code:
$produkty="SELECT * FROM goods ORDER BY name";
if (isset($_POST['order'])) {
$name = $_POST['myInputs'];
foreach( $name as $key => $n ) {
print $n." thank you\n <br />";
}
}
echo "
<fieldset><form method='post'>
<div id='dynamicInput'>
<select name='idp[]'>";
$vys = mysqli_query($db, $goods);
while ($arr = mysqli_fetch_assoc($vys)) {
echo "<option value='".$arr['id_good']."'>".$arr['name']."</option>";
}
echo "
</select> <br />
Entry 1 <input type='text' name='myInputs[]''><br />
</div>
<input type='button' value='Add another text input' onClick=\"addInput('dynamicInput');\"><br />
<input type='submit' name='order'>
</form></fieldset>
";
and I use it to "generate" new (html) input everytime submit is clicked.
But I need to generate not only those (html) inputs, but also that (html) select, which processes the values from the database and show it as options in that (html) select.
I searched a lot to find out the way to "insert" the part from <select .. to </select> to the newdiv.innerHTML variable, but it wasn't succesful. I find some hints that I should "parse" the PHP code in (html) select and then create variable $no1 = mysqli_query($db, $goods); $no2 = while ($arr = mysqli_fetch_assoc($no1)... ... and in the end just say JavaScript newdiv.innerHTML = <?php echo $no5; ?>; .. but there were many problems with the syntax and with the principles that discouraged me.
Can you help me please? ;)

Here is a rough sketch of what you can do for this, if I am understanding you correctly.
<?php
$options = "";
$vys = mysqli_query($db, $goods);
while ($arr = mysqli_fetch_assoc($vys)) {
$options .= "<option value='".$arr['id_good']."'>".$arr['name']."</option>";
}
echo <<< _html
<form method="post">
<div id="dynamicInput">
<div>
<select name=idp[]>
$options
</select> <br />
Entry 1 <input type="text" name=myInputs[]><br />
</div>
</div>
<input type="button" value="Add another text input" onClick="addInput('dynamicInput');"><br />
<input type="submit" name="order">
</form>
_html;
?>
<script type="text/javascript">
var counter = 1;
function addInput(divName){
var newdiv = document.createElement('div');
newdiv.innerHTML = "<select name=idp[]><?php echo $options; ?></select> Entry " + (counter + 1) + " <input type='text' name='myInputs[]'>";
document.getElementById(divName).appendChild(newdiv);
counter++;
}
</script>
Hope this helps...

Related

How to make sure form cannot be submitted if text field is empty when user selects False Hit radio button?

I am doing something to prevent user from submitting HTML Form without leaving their remarks for False Hits.
Conditions:
Only if False Hit radio button is selected
The remarks text field cannot be empty (Compulsory)
Currently, I have used JavaScript to check if the text field (Remarks) is empty.
function empty() {
var x;
x = document.getElementById("roll-input").value;
if (x == "") {
alert("Please enter remarks for false hits selected.");
return false;
};
I am also able to check which radio button is selected with JavaScript.
<input type="radio" name="select" id="truehit" value="true" />
<input type="radio" name="select" id="falsehit" value="false" />
if(document.getElementById('falsehit').checked) {
//False Hit radio button is checked
}
else if(document.getElementById('truehit').checked) {
//True Hit radio button is checked
}
However, I am quite stuck at linking both conditions together. Is there a simpler method to this? Any help is greatly appreciated. Thank you in advance.
This is how my Form looks like.
<body bgcolor="#FFFFFF">
<br />
<div align="center" class="h1">
<h1>Entity Search</h1><br />
</div>
</html>
<br />
<?php
include("db_connect.php"); //connect to database
#$loginid = strtoupper(base64_decode($_POST['LanID'])); //to capture
the user's LanID as the UserID
if($loginid == "")
{
$userID = $_SESSION['loginid'];
}
else
{
$_SESSION['loginid'] = $loginid;
$userID = $_SESSION['loginid'];
}
$userID = $_SESSION['loginid'];
//to insert date and time of the records
date_default_timezone_set('Asia/Singapore');
$Date = date('Y-m-d');
$Time = date ('h:i:s a');
$userID = $_SESSION['loginid'];
$loginid = "";
$entityfromform = $_GET["entity"];
?>
<br />
<?php
//connection to database
$connectionInfo = array( "Database"=>"test","UID"=>$test,"PWD"=>$test);
$db_connect=sqlsrv_connect($serverName, $connectionInfo);
//to retrieve the department name from the user database and insert
department name of the user into the records
$namesql = "SELECT Name, DeptName, Role FROM RPDB.dbo.Userdb WHERE
LanID='$userID';";
$name_query = sqlsrv_query($db_connect,$namesql);
while($row = sqlsrv_fetch_array($name_query, SQLSRV_FETCH_ASSOC))
{
$nameontop = iconv("gb2312","UTF-8",$row['Name']);
$admincheck = iconv("gb2312","UTF-8",$row["Role"]);
$deptnamecheck = iconv("gb2312","UTF-8",$row["DeptName"]);
}
$negative = "Negative Hit: No results found.<br />";
$result = "$entityfromform <br />Negative Hit: No results found.<br />";
//variable to insert into the table as result
//search for keyword from form in the Entity Table List where Name =
keyword
$entitysql = "SELECT * FROM RPDB.dbo.entitysearch_table WHERE Name LIKE
'%" . $entityfromform . "%' OR Name = '".$entityfromform."'";
$entity_query = sqlsrv_query($db_connect,$entitysql);
//variables
$i=0;
while($row = sqlsrv_fetch_array($entity_query, SQLSRV_FETCH_ASSOC))
{
$name[$i] = $row["Name"];
$brn[$i] = $row["Business_Registration_Number"];
$address[$i] = $row["Registered_Address"];
$group[$i] = $row["Applicable_Limb_of_Related_Party_Group"];
$selectradio[$i] = 'selectradio'.$i;
$text[$i] = 'text'.$i;
$i++;
}
if(#$name != NULL) //Positive Result
{
echo "<input type='button' name=uncheck' value='Uncheck All'
class='uncheck' onClick='window.location.reload()'>"; //uncheck all
function where it clears all changes
echo "<h2><div align='center'>Results found for:
$entityfromform</div></h2><br />";
//table to display the data
echo "<div align='center'>
<table>
<tr>
<th>Name</th>
<th>Business Registration Number</th>
<th>Registered Address</th>
<th>Applicable Limb of Related Party Group</th>
<th>True Hit</th>
<th>False Hit</th>
<th>Unable To Ascertain</th>
<th>Remarks, for false hit</th>
</tr>
</div>";
echo "<strong><div class='wording'>Positive Hit: </div></strong>";
echo "<br /><br />";
$x=0;
?>
<!--The form data is sent for processing to action_handler.php by HTTP POST method-->
<form method="post" id="form" action="action_handler.php" enctype="multipart/form-data">
<?php
//data displayed in tables along with checkboxes for true hit, false hit, unable to ascertain and text box for remarks where applicable
for($x=0;$x<$i;$x++)
{
echo "<tr>
<td>" . $name[$x] . "</td>
<td>". $brn[$x] . "</td>
<td>". $address[$x] . "</td>
<td>". $group[$x] . "</td>
<td>
<label class='container'>
<input type='radio' id='truehit' name='".$selectradio[$x]."' value='true hit' class='btn' required>
<span class='checkmark'></span>
</label>
</td>
<td>
<label class='container'>
<input type='radio' id='falsehit' name='".$selectradio[$x]."' value='false hit' class='btn'>
<span class='checkmark'></span>
</label>
</td>
<td>
<label class='container'>
<input type='radio' id='unabletoascertain' name='".$selectradio[$x]."' value='unabletoascertain' class='btn'>
<span class='checkmark'></span>
</label>
</td>
<td>
<label><input type='text' name='".$text[$x]."'>
</label>
</td>
</tr>" ;
}
echo "</table>"; //table closed
echo "<br /><br /><br />";
echo "<input type='button' value='Submit' class='submit' onClick='empty()'>"; //submit button to confirm
?>
</form>
<?php
//sessions to be used in others
$_SESSION['num'] = $x;
$_SESSION['entityfromform'] = $entityfromform;
}
else
{
echo "<div align='center'><h2>Results found for: $entityfromform</h2>
<br />";
echo "<div class='wording' align='center'>$negative</div><br><br>
<br>";
}
?>
</table>
</body>
your empty() function does not return anything if the textbox has a value and hence for that condition it is undefined; you can create a function for your requirement like:
function doSubmit()
{
if(document.getElementById('falsehit').checked)
{
if(document.getElementById("roll-input").value == '')
{
alert("Please enter remarks for false hits selected.");
return false;
}
}
return true;
}
and call this method to validate, so if falsehit is checked and remarks has a value it'll return true or else false.
Hope this helps; let me know if I'm missing to understand your problem here..
Happy coding...
You can use a set of if statements like below. This basically checks if the falsehit radio button is checked. If it is, then it checks if the text is empty. If the text is empty, it alerts what you wanted it to. If the text isn't empty, it submit's the form.
Also, if falsehit is not checked, it automatically submit's the form.
As per request in the comments: Now I get every radio button, and loop through them to check if they're selected. If they aren't, you get an alert message saying Please select all accordingly. Otherwise, it just works the same as before.
function empty() {
var text;
var groups = document.querySelectorAll("[id^=group]");
var selected = {};
var radioButtons;
var submitForm = true;
groups.forEach(e1 => {
radioButtons = e1.querySelectorAll("input[type=radio]");
radioButtons.forEach(e2 => {
if (e2.checked) {
selected[e1.id] = true;
}
});
if (selected[e1.id] == undefined) {
selected[e1.id] = false;
}
});
groups.forEach(e => {
text = e.children[0].value;
for (var i = 0; i < e.children.length; i++) {
if (e.children[i].id == "falsehit") {
if (e.children[i].checked) {
if (text.length == 0) {
alert("Please enter remarks for false hits selected.");
submitForm = false;
}
} else if (selected[e.id]) {
//Don't need to do anything. Just need to prevent the next else from accessing these values
} else {
alert("Please select all accordingly.");
submitForm = false;
}
}
}
});
if (submitForm) {
document.getElementById("form").submit();
}
}
<form id="form">
<fieldset id="group1">
<input type="text" id="roll-input" />
<input type="radio" name="group1" id="truehit" value="true" />
<input type="radio" name="group1" id="falsehit" value="false" />
</fieldset>
<fieldset id="group2">
<input type="text" id="roll-input" />
<input type="radio" name="group2" id="truehit" value="true" />
<input type="radio" name="group2" id="falsehit" value="false" />
</fieldset>
<input type="button" value="Submit" onclick="empty()" />
</form>

How to store dynamically added rows into database mysql php

I'm stuck on this for a couple of days. I hope any of you can help me out.
Usually when you ask user input through an HTML form you can access the data by calling the $_POST function.
The problem in this approach is that I don't have a static set of input fields. When the user clicks on the addition button another input field shows up and they can make as many input fields as feel neccesary.
I do know that I should loop through it, but I don't have alot of experience in doing this. See the code below which adds dynamic rows in Jquery/Javascript:
<script type="text/javascript">
$(document).ready(function(){
var counter = 2;
$("#addButton").click(function () {
if(counter>10){
alert("Only 10 textboxes allow");
return false;
}
var newTextBoxDiv = $(document.createElement('div'))
.attr("id", 'TextBoxDiv' + counter);
newTextBoxDiv.after().html('<label>Source Name #'+ counter + ' : </label>' +
'<input type="text" placeholder ="Source Name" name="source_name' +
counter +
'" id="textbox' + counter + '" value="" > <label>IP address from #'+
counter + ' : </label>' +
'<input type="text" placeholder="IP Address From"
name="source_ip_from' + counter +
'" id="textbox' + counter + '" value="" > <label>IP address till #'+
counter + ' : </label>' +
'<input type="text" placeholder="IP Address Till"
name="source_ip_till' + counter +
'" id="textbox' + counter + '" value="" >'
);
newTextBoxDiv.appendTo("#TextBoxesGroup");
counter++;
});
$("#removeButton").click(function () {
if(counter==2){
alert("No more textbox to remove");
return false;
}
counter--;
$("#TextBoxDiv" + counter).remove();
});
$("#getButtonValue").click(function () {
var msg = '';
for(i=1; i<counter; i++){
msg += "\n Textbox #" + i + " : " + $('#textbox' + i).val();
}
alert(msg);
});
});
</script>
The code below is where the form is created and posted in HTML/PHP
<form method="post" class="form-inline" action="addverkeersstroom.php">
<div id='TextBoxesGroup'>
<div id="TextBoxDiv1">
<label>Source Data : </label>
<input type="text" class="form-control mb-2 mr-sm-2 mb-sm-0"
placeholder="Source" name="source_name">
<input type="text" class="form-control mb-2 mr-sm-2 mb-sm-0"
placeholder="APP Nummer" name="source_app">
<?php
mysql_connect('localhost', '', '');
mysql_select_db('');
$sql = "SELECT * FROM zone";
$result = mysql_query($sql);
echo "<select name='zone_1' id='zone_1' class='form-control
ip_or_zone'>";
echo "<option value=''></option>";
while ($row = mysql_fetch_array($result)) {
echo "<option value='". $row['idzone'] . "'>" . $row['zone_naam'] . "
</option>";
}
echo "</select>";
?>
OR <input type="text" class="form-control ip_or_zone" placeholder="IP
Address from" name="source_ip_from">
<input type="text" class="form-control ip_or_zone" placeholder="IP
Address till" name="source_ip_till">
<input type="text" class="form-control mb-2 mr-sm-2 mb-sm-0"
placeholder="NAT IP" name="source_nat">
<input type="text" class="form-control mb-2 mr-sm-2 mb-sm-0"
placeholder="Netmask" name="source_netmask">
</div>
</div>
<input type='button' value='+' id='addButton'>
<input type='button' value='-' id='removeButton'>
And last but not least the code below that should insert it into the database.
<?php
session_start();
if(isset($_POST['submit'])) {
echo $source_name = $_POST['source_name'];
echo $source_app = $_POST['source_app'];
echo $source_zone = $_POST['zone_1'];
echo $source_ip_from = $_POST['source_ip_from'];
echo $source_ip_till = $_POST['source_ip_till'];
echo $source_nat = $_POST['source_nat'];
echo $source_netmask = $_POST['source_netmask'];
echo $destination = $_POST['destination'];
echo $dest_app = $_POST['destination_app'];
echo $dest_zone = $_POST['zone_2'];
echo $dest_ip_from = $_POST['dest_ip_from'];
echo $dest_ip_till = $_POST['dest_ip_till'];
echo $dest_nat = $_POST['destination_nat'];
echo $dest_netmask = $_POST['destination_netmask'];
mysql_connect('localhost', '', '');
mysql_select_db('');
//Maak een nieuwe verkeersstroom aan in de database
mysql_query("INSERT INTO verkeersstroom(changes_idchange, protocol, tcpudp,
port_nr)
VALUES('".$changeid."', '".$protocol."', '".$tcpudp."', '".$portnr."')");
$verkeerstroomid = mysql_insert_id();
//Maakt de eigenschappen van de verkeersstroom aan
mysql_query("INSERT INTO verkeersstroom_eigenschappen(changes_idchange,
verkeersstroom_idverkeersstroom, source_name, source_app, source_zone,
source_ip_from, source_ip_till, source_nat, source_netmask, destination,
destination_app, destination_zone, destination_ip_from, destination_ip_till,
destination_nat, destination_netmask)
VALUES('".$changeid."', '".$verkeerstroomid."', '".$source_name."',
'".$source_app."', '".$source_zone."', '".$source_ip_from."',
'".$source_ip_till."', '".$source_nat."', '".$source_netmask."',
'".$destination."', '".$dest_app."', '".$dest_zone."', '".$dest_ip_from."',
'".$dest_ip_till."', '".$dest_nat."', '".$dest_netmask."')");
header("Location:"."");
}
After submitting the dynamic values are like: source_name2, source_ip_from2, source_ip_till2, destination2, dest_ip_from2, dest_ip_till2
and counting up to the amount of rows generated by pressing the addition(+) button.
Like I said before I need to loop through the query somehow like this;
foreach source_name(or source_name2 or 3,4 etc), source_ip_from, source_ip_till, destination, dest_ip_from, dest_ip_till
Insert it seperately into the table like everything with a 2 in the same row and everything with a 3 in the same row and counting up like that.
I hope anyone can help me it is giving me an headache ;-p
html forms allow you to give input fields a name:
<input type='text' name='name' value='22'>
In the event you get multiple inputs but you do not know how many. You can make an array of the input fields by changing the <input name='name'> to <input name='name[]'>
Then you can write a simple for loop in php to work through the array:
<?php
$count = count($_POST['name']);
$name = $_POST['name'];
for($i = 0; $i < $count; $i++){
// do your sql stuff with:
$name[$i]; // this is the value of the inputfield number $i.
}
?>
Also I'd advice to look into using prepared statements. With your current php code you are vulnerable to SQL-injection.
<?php
$sql = "INSERT INTO verkeersstroom(`changes_idchange`, `protocol`, `tcpudp`, `port_nr`)
VALUES( ?, ?, ?, ?);";
$stmt = mysql_connect('localhost', '', '')->prepare($sql);
$stmt->bind_param("ssss", $changeid, $protocol, $tcpudp, $portnr);
$stmt->execute;
?>
This is an example, for more look at: http://php.net/manual/en/mysqli.quickstart.prepared-statements.php

How do i save a dynamic form?

I am really stuck.
All i want to do is save a form not just the data into a session, the actual form. The idea is the administrator can add as many extra's to a product. My problem is i cannot work out how to save the form into a session (current code not working). I just cannot get my head around it. I am a newbie so i am getting rather confused.
At the moment i have the dynamic form but the form and data disappear on page refresh.
I have created the dynamic form:
var counter = 1;
var limit = 50; // the amount of addons that are allowed
function addInput(divName){
if (counter == limit) {
alert("You have reached the limit of adding " + counter + " inputs");
}
else {
var newdiv = document.createElement('div');
newdiv.innerHTML = "Entry " + (counter + 1) + " <br><label id='cat_label' name='cat_label' class='lab'>Name</label>\n\
<input type='text' id='cat_name' name='cat_name' value=''>\n\
<br>\n\
<label id='desc_label' name='desc_label' class='lab'>Description</label>\n\
<input type='text' id='cat_desc' name='cat_desc' value=''>\n\
<br>\n\
<hr id='dotted'>\n\
<br>\n\
<p id='menu_head'> Menu Item</p>\n\
<input type='button' value='Add New item to ...' onClick='addInput('new item');'>";
document.getElementById(divName).appendChild(newdiv);
counter++;
}
}
<div id="dynamicInput">
<br><!--<input type="text" name="myInputs[]">-->
<label id="cat_label" class="lab">Name</label>
<input type="text" id="cat_name" name="cat_name[]" value="<?php print $_SESSION['form']['cat_name'][$counter]; ?>">
<br>
<label id="desc_label" class="lab">Description</label>
<input type="text" id="cat_desc" name="cat_desc[]" value="<?php print $_SESSION['form]['cat_desc'][$counter]; ?>">
</div>
<input type="button" value="Add" onClick="addInput('dynamicInput');">
<input type="submit" id="submit" name="submit" value="Save...">
</form>
I started this:
if (count($_POST) > 2 && $_POST['submit'] == "Save...") {
$countNumberOfInputs = count($_POST['cat_name']);
foreach($_POST as $key=>$value) {
if(!is_array($value)) {
$value = strip_tags($value);
$value = preg_replace("/[^0-9a-z -,.!]/i", "", $value);
}
$_SESSION['form'][$key] = $value;//save to session
}
if ($countNumberOfInputs < 1 ) {
$countNumberOfInputs = 1;
$counter = 0;
}
How can i resolve this, even better could someone highlight where i went wrong?

php increase and decrease quantity of product?

im noob at php but my question is this:
im having a while loop which presents to me all the products from the db
im trying to add a + and - quantity buttons next to the buy now button that will increase and decrease by pressing them (just display the number not affect the db)
but the problem is that the quantity number won't pass the number 2. Can anyone lend me some brains with this one?
$value = 1; //to be displayed
if(isset($_POST['incqty'])){
$value= $value +1;
echo $value;
}
if(isset($_POST['decqty'])){
$value = $value -1;
echo $value;
}
<form method='post'>
<input type='hidden' name='item'/>
<td><button name='incqty'>+</button><input type='text' size='1' name='item' value='$value'/><button name='decqty'>-</button></td>
</form>
I already tried to do it with js
<form name="f1"> <input type='text' name='qty' id='qty' />
<input type='button' name='add' onclick='javascript:document.getElementById("qty").value++;' value='+'/>
<input type='button' name='subtract' onclick='javascript: document.getElementById("qty").value--;' value='-'/>
</form>
but the buttons were unclickable...
I'm guessing you're learning PHP and because of that not doing this with javascript. Below code should work for you:
<?php
$value = isset($_POST['item']) ? $_POST['item'] : 1; //to be displayed
if(isset($_POST['incqty'])){
$value += 1;
}
if(isset($_POST['decqty'])){
$value -= 1;
}
?>
<form method='post' action='<?= $_SERVER['PHP_SELF']; ?>'>
<!--<input type='hidden' name='item'/> Why do you need this?-->
<td>
<button name='incqty'>+</button>
<input type='text' size='1' name='item' value='<?= $value; ?>'/>
<button name='decqty'>-</button>
</td>
</form>
If I understood the question, you need to show the values of the items in the cart and modify it by pressing + and - button.
I think you shoud use javascript for this (as you are saying that no affects database)
I'm writing some code in jQuery to show an example of the plus button
$('button[name="incqty"]').bind('click', funcion(){
var actual = $('input[name="intem"]').val();
if (actual <= 1) {
actual = actual +1;
}
$('input[name="intem"]').val(actual);
});
Of course is better not to hardcode values in the code and use constants or variables (for the 1 limit) but I hope this example help you.
I tried your javascript snippet and it worked perfectly.
That being said, is there a reason you are not using the HTML number input?
<input type="number" name="quantity" min="1" max="99">
Edit: I used the code from Daan's answer as the template but...
<?php
$value = isset($_POST['item']) ? $_POST['item'] : 1; //to be displayed
?>
<form method='post' action='<?= $_SERVER['PHP_SELF']; ?>'>
<!--<input type='hidden' name='item'/> Why do you need this?-->
<td>
<input type="number" name="item" min="1" max="99" value="<?= $value; ?>">
</td>
</form>
<input type="button" value = "-" onclick="minusbot()" />
<input type="number" name="kgcount" id = "kilohere" value = "1" >
<input type="button" value = "+" onclick="plusbot()" />
<script>
function minusbot()
{
document.getElementById('kilohere').value = parseInt(document.getElementById('kilohere').value) - 1;
var checknumifzero = parseInt(document.getElementById('kilohere').value);
if(checknumifzero < 1) //preventing to get negative value
{
document.getElementById('kilohere').value = 1;
}
}
function plusbot()
{
document.getElementById('kilohere').value = parseInt(document.getElementById('kilohere').value) + 1;
var checknumiffifty = parseInt(document.getElementById('kilohere').value);
if(checknumiffifty > 50) //just a limit
{
document.getElementById('kilohere').value = 50;
}
}
</script>

Add form fields dynamically populated dropdown list with php

I'm trying to make 3 form fields (a dropdown list dynamically populated by a .php script and 2 text fields) and also with a button add 3 more and 3 more and so on (as user clicks the button) I have tried several ways but nothing seems to work for me. (I'm noob in JS, AJAX, jQuery so I mostly tried scripts I've found on the internet).
Here's the code of these form fields:
<form id="form1" name="form1" method="post" action="results.php">
<div id="itemRows">
<select name="species">
<option value="">Select Species</option>';
<?php $sql = "SELECT common FROM species";
$speciesq = mysqli_query($con, $sql);
while($row = mysqli_fetch_array($speciesq))
{
echo "<option value=\"" . $row['common'] ."\">" . $row['common'] ."</option>";
}
?>
</select>
Number: <input type="text" name="speciesnumber1" size="7" /> Weight: <input type="text" name="speciesweight1" /> <input onClick="addRow(this.form);" type="button" value="+" />
</div></form>
and after this form there's the code:
<script type="text/javascript">
var rowNum = 0;
var ddsel = '<select name="species'+rowNum+'>';
var ddopt = '<option value="">Select Species</option>';
var ddselc= '</select>';
function addRow(frm) {
rowNum ++;
$.post("getlist.php", function(data) {
for (var i=0; i<data.length; i++) {
ddopt += '<option value="'+data[i].value+'">'+data[i].value+'</option>';
}
}, "json");
var row = '<p id="rowNum'+rowNum+'">'+ddsel+ddopt+ddselc+'Number: <input type="text" name="speciesnumber'+rowNum+'" size="7" value="'+frm.add_qty.value+'"> Weight: <input type="text" name="speciesweight'+rowNum+'" value="'+frm.add_name.value+'"> <input type="button" value="-" onclick="removeRow('+rowNum+');"></p>';
jQuery('#itemRows').append(row);
frm.add_qty.value = '';
frm.add_name.value = '';
}
function removeRow(rnum) {
jQuery('#rowNum'+rnum).remove();
}
</script>
getlist.php is a simple script that populates the dropdown list and sends the data:
<?php
include("dbcon.php");
$sql = mysqli_query ($con, "SELECT common FROM species");
$result = array();
while ($row = mysqli_fetch_array($sql)){
$result[] = array(
'value' => $row['common'],
);
}
echo json_encode($result);
?>
So when I click the "+" button (to add the row) nothing happens.
SOLVED: for those who come here please read also the comments below the answer.
You just have some code in the wrong spot:
var row = '<p id="rowNum'+rowNum+'">'+ddsel+ddopt+ddselc+'Number: <input type="text" name="speciesnumber'+rowNum+'" size="7" value="'+frm.add_qty.value+'"> Weight: <input type="text" name="speciesweight'+rowNum+'" value="'+frm.add_name.value+'"> <input type="button" value="-" onclick="removeRow('+rowNum+');"></p>';
jQuery('#itemRows').append(row);
frm.add_qty.value = '';
frm.add_name.value = '';
needs to be moved into the post return function like this:
function addRow(frm) {
rowNum ++;
$.post("getlist.php", function(data) {
var frm = document.getElementById('form1');
for (var i=0; i<data.length; i++) {
ddopt += '<option value="'+data[i].value+'">'+data[i].value+'</option>';
}
var row = '<p id="rowNum'+rowNum+'">'+ddsel+ddopt+ddselc+'Number: <input type="text" name="speciesnumber'+rowNum+'" size="7" value="'+frm.add_qty.value+'"> Weight: <input type="text" name="speciesweight'+rowNum+'" value="'+frm.add_name.value+'"> <input type="button" value="-" onclick="removeRow('+rowNum+');"></p>';
jQuery('#itemRows').append(row);
frm.add_qty.value = '';
frm.add_name.value = '';
}, "json");
}

Categories

Resources