Been kinda stuck with this one for awhile.
I need my code to create 2 elements on a click of a button (Text input and Select). The Select element needs to be populated with values from a database.
So far I've got this:
<!DOCTYPE html>
<html>
<head>
var counter = 1;
var dynamicInput=[];
function removeInput(){
var elem = document.getElementById('ingredients');
elem.removeChild(elem.lastChild);
/*return elem.parentNode.removeChild(elem);*/
counter--;
}
function addInput(){
var newdiv = document.createElement('div');
newdiv.id = dynamicInput[counter];
newdiv.innerHTML = "Entry " + (counter) + " <br><input type='text' name='quantities[]'><select name='products[]'></select>";
counter++;
document.getElementById('ingredients').appendChild(newdiv);
}
</script>
<?php
$link = mysqli_connect("localhost", "root", "", "cocktails");
// Check connection
if($link === false){
die("ERROR: Could not connect. " . mysqli_connect_error());
}
?>
</head>
<body>
<form method="POST">
Ingredients:<br>
<div id="ingredients">
<div id="dynamicInput[0]">
<input type="text" name="quantities[]">
<select name="products[]">
<?php
$sql = mysqli_query($link, "SELECT name FROM inventory");
while ($row = $sql->fetch_assoc()){
echo "<option value=\"".$row['name']."\">" . $row['name'] . "</option>";
}
?>
</select>
<button type="button" onClick="addInput();">+</button>
<button type="button" onClick="removeInput();">-</button>
</div>
</div>
</form>
</body>
</html>
How can I populate the select that's created on a click of the button?
Of course whatever the user selects I will need to work with. How can I work with those values after?
Any pointers in the right direction will be greatly appreciated.
Related
My intention is to create a form in HTML where the user could register some quality features of a product. The number of features to be registered varies according to the model, this info is registered on a table in SQL.
So far I manage to generate the inputs, but it is very fast, the user cannot fill all the inputs.
## query to get the product information from database ##
$query_list = "SELECT * FROM data_products";
$result_list = mysqli_query($conn, $query_list);
## get the number of rows
$query_data_rows = mysqli_query($conn, $query_list);
$data_rows = mysqli_fetch_array($query_data_rows);
?>
## here is the first form, where the user selects the product model,
## therefore it should query the number of raws (n) registered on the table
<div class="container">
<form action="" method="post" onsubmit="getdata()">
<select name="select1">
<option value=" "> </option>
<?php
while ($row = mysqli_fetch_array($result_list)) {
echo "<option value='" . $row['customer_Id'] . "'>" . $row['customer_Id'] . "</option>";
}
?>
</select>
<input type="submit" name="submit" value="Go"/>
</form>
</div>
## here my intention is to return the (n) number of input fields
## it correctly displays the number of input fields, but it is very fast
## I am missing something here
<?php
if(isset($_POST['select1'])){ ?>
<form id="form" action="" method="post">
<input type="submit">
</form>
<?php
}
?>
## I am almost zero skilled on Javascript,
## but browsing on the world web wide and reading the documentation of the language
## I got the code below.
<script>
function getdata() {
var no = <?php echo $data_rows['number'] ;?>;
for(var i=0;i<no;i++) {
var textfield = document.createElement("input");
textfield.type = "text";
textfield.value = "";
textfield.name = i+1 + "a"
textfield.placeholder = i+1
document.getElementById('form').appendChild(textfield);
}
}
</script> ```
Here what actually happening is that when you are submitting the form getdata() function is called till the it get submitted, after submission is done the content called by function disappears, in order to avoid this use return false statement at the end of the function.
<div class="container">
<form action="" id="form_id" method="post" onsubmit="return getdata()">
<select name="select1">
<option value=" "> </option>
<?php
//accesing the database table
$query_list = "SELECT * FROM `data_products`";
$result = mysqli_query($conn, $query_list);
//to get rows
$data_rows = mysqli_num_rows($result);
echo $data_rows;
while ($row = mysqli_fetch_array($result)) {
echo "<option value='" . $row['srno'] . "'>" . $row['srno'] . "</option>";
}
?>
</select>
<input type="submit" name="submit" value="go"/>
</form></div>
<?php
if($_SERVER['REQUEST_METHOD'] == 'POST' ){
echo '<form id="form" action="" method="post">
<input type="submit">
</form>';
}
?>
<script>
function getdata() {
var no = <?php echo $data_rows;?>;
for(var i=0;i<no;i++) {
var btn = document.createElement("INPUT");
btn.type = "text";
btn.value = "";
btn.name = i+1 + "a"
btn.placeholder = i+1
document.getElementById('form').appendChild(btn);
}
return false;
}
</script>
This is working. Here I have made some changes in your code like replacing 'textfield' with 'btn', 'customerid' with 'srno' (for easy understanding) and avoid using php again and again.
I have code in html that adds data in a list by selecting the data in the combo box and clicking on the add button. I am encountering an error "undefined index: subjectlist" when submitting the form. Appreciate your advise this? Thank you. I am still an newbie in web programming.
<h4>Subjects</h4>
<ul class="list-group list" id='subjectlist' name='subjectlist' >
</ul>
<div class="form-group">
<input class="submit" name="submit" type="submit" value="Save">
</div>
</form>
<button class="add_field_button" onclick="getsubject()">Add Subject</button>
<button class="add_field_button" onclick="removesubject()">Remove Subject</button>
<script>
function getsubject(){
var ul = document.getElementById("subjectlist");
var candidate = document.getElementById("st");
var SelectedValue = candidate.options[candidate.selectedIndex].text;
var li = document.createElement("li");
li.setAttribute('class',"list-group-item");
li.setAttribute('id',"subjectlistitem");
li.appendChild(document.createTextNode(SelectedValue));
ul.appendChild(li);
}
</script>
<?php
if(isset($_POST['submit'])){ // Fetching variables of the form which travels in URL
$sectioncode = $_POST['sc'];
$sectiongroup = $_POST['ccg'];
$selectedsubject = $_POST['st'];
$subjectlist = $_POST['subjectlist'];
$i = 0;
foreach ($subjectlist as $qst) {
$sql = "INSERT INTO sectionsubject(sectioncode, subjectcoden) VALUES ('" . $csectioncode . "',
'" . $subjectlist[$i] . "')";
if ($link->query($sql) === TRUE) {
echo "success";
} else {echo "error" . $link->error;}
$i++;}
}
?>
because $_POST,$_GET only deal with <input> tags and <ul>,<li> are not input methods.
I have problem with Web Development,
i have added drop down list using PHP, MySQL and HTML. Now i want to use button and dynamically generate same Select box again and again. How can i do this, please help me..
Here is my Select Box Code.
<Select name="txt-computer_sn" class="form-control" id="txt-computer_sn">
<?php
include ('../svr/connection.php');
$sql = "SELECT * FROM supplier";
$result = mysqli_query($conn, $sql);
while ($row = mysqli_fetch_array($result)) {
echo '<option value=' . $row['supplier_id'] . '>' . $row['supplier_name'] . '</option>';
}
?>
</select>
if the data of dropdown will remain same then you can do that in this way
html and php
<Select name="txt-computer_sn" class="form-control dynm_drop" id="txt-computer_sn">
<?php
include ('../svr/connection.php');
$sql = "SELECT * FROM supplier";
$result = mysqli_query($conn, $sql);
while ($row = mysqli_fetch_array($result)) {
echo '<option value=' . $row['supplier_id'] . '>' . $row['supplier_name'] . '</option>';
}
?>
</select>
jquery
$("#buttonid").click(function(){
$(".dynm_drop").clone().appendTo("class or id of element");
});
Try this:
<div class="select_wrapper">
<select name="txt-computer_sn[0]" class="form-control" id="txt-computer_sn_0">
<?php
include ('../svr/connection.php');
$sql = "SELECT * FROM supplier";
$result = mysqli_query($conn, $sql);
while ($row = mysqli_fetch_array($result)) {
echo '<option value=' . $row['supplier_id'] . '>' . $row['supplier_name'] . '</option>';
}
?>
</select>
<input type="button" name="add_select" class="add_select" value="Add New">
</div>
<script type="text/javascript">
$(document).ready(function() {
var s=1;
$('.add_select').click(function(e){ //Once add button is clicked
e.preventDefault();
s++;
$('.select_wrapper').append('<select class="form-control" name="txt-computer_sn['+s+']" id="txt-computer_sn_'+s+'">'+$('#txt-computer_sn_0').html()+'</select>');
});
});
</script>
there is 3 method to do this.i am not familiar with php.but i tell the method how to work it out.
1.you have to set an hidden field for count
2.
<select class="form-control" name="txt-computer_sn--" id="txt-computer_sn_--">
3.in the script write this var rep=/--/gi;
4. take your count from hidden field
var Count= $("#Count").val()
Count =++Count
("#div1").append($("#div2").html().replace(rep,Count));
on click the add button you have append the div2 with select to another
div1
on remove the
$("#div3"+id).remove()
in the order
<div1></div>
<div2 id="name1--"style=display:none>
<div3 id="name2--"></div3>
</div2>
it will work.use this concept .you can do this in php also..
How would I code into my program using PHP/JavaScript and HTML/CSS to display data from a database I made in MySQL Monitor on the blue section below:
I made buttons that use PHP to go into the database and show the data on the HTML page:
HTML:
<form action="fullridez.php" method="post">
<h4 id="Filter">GPA</h4>
<input id="FilterBox" name="gpa" type="text"/>
<h4 id="Filter">Amount</h4>
<input id="FilterBox" name="amount" type="text"/>
<h4 id="Filter">School</h4>
<input id="FilterBox" name="school" type="text"/>
<input type="submit" id="FilterBox" name="myForm" onkeypress="checkEnter()" ><img src="search.png" width=15 height=15 /></button>
</form>
<script>
</script>
PHP:
<?php
if(isset($_POST['myForm'])) {
$servername = "localhost";
$username = "root";
$password = "";
$database = "scholarshiplist";
$conn = mysqli_connect($servername, $username, $password, $database);
$gpa = $_POST['gpa'];
$amount = $_POST['amount'];
$count = "SELECT * FROM scholarships";
$result = mysqli_query($conn, $count);
if ($result->num_rows > 0) {
$sql = "SELECT * FROM scholarships WHERE GPA <= " . $gpa . " AND Amount <= "
. $amount;
if ($result = mysqli_query($conn, $sql)) {
while ($row=mysqli_fetch_row($result)) {
for($i = 0; $i < count($row); $i++) {
echo $row[$i] . '<br>';
}
}
}
} else {
echo "0 results";
}
$conn->close();
}
SQL:
USE ScholarshipList;
CREATE TABLE Scholarships
(
id int unsigned NOT NULL auto_increment,
School varchar(500) NOT NULL,
GPA decimal(10,2) NOT NULL,
Amount decimal(10,2) NOT NULL,
PRIMARY KEY (id)
);
I am using XAMPP
When I click the button on the HTML file it bring me to the PHP page and all I see is the PHP code. I don't want it to go to the page but stay on the same page showing the data below the buttons.
This is what the page looks like so far
page
What am I doing wrong?
If your HTML form is contained within the 'fullridez.php' file and you are posting the form inputs to that same file, then you need to have some PHP where you'd like to output to be checking for results and then looping through those results while echoing them out:
<table>
<tr><td>Col 1</td><td>Col 2</td><td>Col 3</td></tr>
<?php
while($row = mysql_fetch_assoc($result))
{
echo "<tr><td>"
. $row['col_1'] . "</td><td>"
. $row['col_2'] . "</td><td>"
. $row['col_3'] . "</td></tr>";
}
?>
</table>
You can build a wireframe div table with for loop:
<?php
$num_rows = mysql_num_rows($result);
for ($i=0;$i<$num_rows;$i++) {
//loop through all rows of data
$row = mysql_fetch_assoc($result); // your data is now: $row['fieldName']
?>
<div>
GPA <input name="" value="<?php echo($row['gpa'])?>;" type="text">
AMOUNT <input name="" value="<?php echo($row['amount'])?>;" type="text">
SCHOOL <input name="" value="<?php echo($row['school'])?>;" type="text">
</div>
<?php
} //end of the loop
?>
I am trying to input a value (Rating) from the database when an item is selected. I need to also be able to update that rating and then put that value into another table.
My problem is that I'm trying to figure out how to make the value in the text box be related to the selection made in the drop down. I've found coding to make another option box but cannot figure out how to make that a text box.
REWORDING: Originally when I posted the question I thought it was possible to do this without JQuery and was trying to copy the for loop and run a while loop to populate the text box. I now know that isn't possible and would like to figure out how to run a script to populate a text box on change for the drop down box. The problem being the function has to be connected to the database as well as the drop down.
1. pull the data for the drop down (from the JOURNAL table). 2. Select a journal from that drop down 3. Inside the JOURNAL table a JournalRating has been assigned to every journal pull that value and place inside a textbox.
What I've tried to do is
<?php
include 'dbc.php';
connect();
//insert form values into database
$sql = "SELECT JournalName, JournalID, Rating, JournalActive from JOURNAL where JournalActive = 1;";
//Can take out JournalActive if we do not want it
$result = mysqli_query($conn, $sql);
if (!$result) {
$message = 'Invalid query: ' . mysql_error() . "\n";
$message .= 'Whole query: ' . $query;
die($message);
echo "there was an issue";
}
$sql2 = "SELECT FName, LName, FacultyID from FACULTY where FacultyActive = 1;";
//Can take out JournalActive if we do not want it
$result2 = mysqli_query($conn, $sql2);
if (!$result2) {
$message = 'Invalid query: ' . mysql_error() . "\n";
$message .= 'Whole query: ' . $query;
die($message);
echo "there was an issue";
}
//array to hold all of the data
$journals = array();
//print out all of the first names in the database
$rownumber = 0;
while ($row = mysqli_fetch_assoc($result)) {
$journals[$rownumber][0] = $row['JournalName'];
$journals[$rownumber][1] = $row['JournalID'];
$journals[$rownumber][2] = $row['JournalRating'];
$journals[$rownumber][3] = $row['JournalActive'];
$rownumber++;
}
$faculty = array();
//print out all of the first names in the database
$rownum = 0;
while ($row = mysqli_fetch_assoc($result2)) {
$faculty[$rownum][0] = $row['FName'];
$faculty[$rownum][1] = $row['LName'];
$faculty[$rownum][2] = $row['FacultyID'];
$rownum++;
}
?>
<!DOCTYPE html>
<head>
<link href="styles.css" rel="stylesheet">
<h1> Miami University </h1>
<h4> Information Systems and Analytics Department </h4>
<script>
(function($){
$(function(){
$("#JournalID").on('change', function() {
$("#JournalRating").val($(this).find("option:selected").data('Rating'));
});
});
})(jQuery);
</script>
</head>
<body>
<div class="StyleDiv" >
<!-- coding for journal -->
<form id="form1" name="form1" method="post" action="RR2.php">
<label for="FacultyID">Faculty Name</label>
<select multiple="multiple" name="FacultyID[]" id="FacultyID">
<?php
for($i = 0; $i < sizeof($faculty); $i++) {
print "<option value=\"" . $faculty[$i][2] . "\">" . $faculty[$i][0] .' '. $faculty[$i][1] . "</option>\r\n";
}
?>
</select>
<br class="clear" />
<br class="clear" />
<label for="JournalID">Journal Name</label>
<select name="JournalID" id="JournalID">
<?php
for($i = 0; $i < sizeof($journals); $i++) {
print "<option value=\"" . $journals[$i][1] . "\" data-rating=\"" . $journals[$i][2] . "\">" . $journals[$i][0] . "</option>\r\n";
}
?>
</select>
<br class="clear"/>
<label for="JournalRating">Journal Rating</label><input type="text" name="JournalRating" id="JournalRating" />
<br class="clear" />
<!-- coding for publication -->
<label for="Title">Publication Title</label><input type="text" name="PubID" id="PubID" />
<br class="clear" />
<label for="Year">Year</label><input type="text" name="Year" id="Year" />
<br class="clear" />
<label for="Volume">Volume</label><input type="text" name="Volume" id="Volume" />
<br class="clear" />
<label for="Issue">Issue</label><input type="text" name="Issue" id="Issue" />
<br class="clear" />
<label for="Comments">Comments</label><textarea name="Comments" id="Comments" cols="45" rows="5"></textarea>
<br class="clear" />
<input type="submit" name="Submit" id="Submit" value="Submit" />
<br class="clear" />
</br>
</br>
</div>
</form>
<?php
//Post Parameters
$JournalID = $_POST['JournalID'];
//for($i = 0; $i < sizeof($journals); $i++) {
//if ($JournalID = $journals[$i][1]) {
//$JournalName = $journals[$i][0];
//}
//}
$Year = $_POST['Year'];
$Comments = $_POST['Comments'];
$Volume = $_POST['Volume'];
$Issue = $_POST['Issue'];
$Title = $_POST['Title'];
$JournalRating = $_POST['JournalRating'];
$FacultyMemID = $_POST['FacultyID'];
//Query
//INSERT
$stmt = $conn->prepare(" INSERT INTO PUBLICATION ( JournalID, Year, Comments, Volume, Issue, Title, JournalRating ) VALUES ( ?, ?, ?, ?, ?, ?, ? )");
$stmt->bind_param('sssssss', $JournalID, $Year, $Comments, $Volume, $Issue, $Title, $JournalRating);
$stmt->execute();
$pubID = $stmt->insert_id;
$facmemid = 0;
$stmt = $conn->prepare(" INSERT INTO FACULTYPUBLICATIONS ( FacultyID, PubID ) VALUES ( ?, ? )");
$stmt->bind_param('ii', $facmemid, $pubID);
//for ($_POST['FacultyID'] as $FacultyMemID) {
for($i = 0; $i < sizeof($FacultyMemID); $i++) {
$facmemid = $FacultyMemID[$i];
$stmt->execute();
}
mysqli_close($conn);
?>
</body>
</html>
Add the rating to your HTML using a data attribute:
<select name="JournalID" id="JournalID">
<?php
for($i = 0; $i < sizeof($journals); $i++) {
print "<option value=\"" . $journals[$i][1] . "\" data-rating=\"" . $journals[$i][2] . "\">" . $journals[$i][0] . "</option>\r\n";
}
?>
</select>
Then you can access this using jQuery .data():
(function($) {
$(function() {
$("#JournalID").on('change', function() {
$("#JournalRating").val($(this).find("option:selected").data('rating'));
});
});
})(jQuery);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select id="JournalID">
<option>Select a journal</option>
<option value="1" data-rating="3">Journal #1</option>
<option value="2" data-rating="2">Journal #2</option>
<option value="3" data-rating="5">Journal #3</option>
</select>
<br>
Rating: <input id="JournalRating">