how to generate dynamic textboxes based on user input in php/javascript? - javascript

This code below is displaying data through a dropdown and I was wondering on how can I convert this into like a when a user enters a number in a textbox and click set, dynamic dropdowns appear based on the number he entered.
$query = mysqli_query($con, "SELECT * FROM topic WHERE SubCat = $subcat ");
echo "<select name='topdd' >";
echo " <option>--None Selected--</option>";
while ($row = mysqli_fetch_array($query)) {
echo "<option value='$row[topic_id]' selected>";
echo $row["title"];
echo "</option>";
}
echo "</select>";

This code it's ok for you ? I make your job, the next time try yourself
<form method="POST">
<label for='choiceNumber'>Number of dropdowns choice</label>
<input type='number' name='choiceNumber'>
<input type='submit'>
</form>
<?php
$resultArray = array(1,2,3,4,5,6,7);
$display = "<select name='topdd'><option>--None Selected--</option>";
if (!empty($_POST['choiceNumber']) && $_POST['choiceNumber'] > 0) {
for($i = 0; $i < $_POST['choiceNumber']; $i++) {
$display .= "<option>".$resultArray[$i]."</option>";
}
}
echo $display."</select>";
?>

Related

Only getting last record from mysql database

I am stuck on a code where I want to fetch data from MySQL into an array.. I have a form containing color and size select boxes, an onclick javascript function is triggered and it created two more select boxes like above, I have managed to get data into the javascript code where the code for creating new select boxes is written.
But I am only getting the last inserted record from both the tables. Although I have used a while loop.
Can someone help me out and I am also getting name of all select boxes likes name="color[]" , I want to insert records into a bridge table containing ids of color and size. below is my code please help ..
I will clear it up , each time I click add more button it should create 2 new dropdown lists, one for color and 2nd for size, both dropdowns should have the distinct data from database. so the ids for each record would be same in every dropdown list, I want to add more than 1 records in bridge table which contains product_id,color_id and size_id, so if I go for 3 dropwdown boxes , and i select blue color and small size in the first, then for second dropdown i again select blue color and size medium, as for the last dropdown which was also generated by the javascript function . i choose black color and large size. so from the dropdown it will get ids of size,color and it would be inserted accordingly.. so when i display the product and color blue is selected i would only see the sizes which were added to the color blue at the time of adding the product.. i hope this clears everything :)
$result=mysql_query("SELECT * FROM color,size");
while($row=mysql_fetch_array($result)) {
?>
<script>
var room = 1;
function add_fields() {
room++;
var objTo = document.getElementById('room_fileds')
var divtest = document.createElement("div");
divtest.innerHTML = '<div class="label">Room ' + room + ':</div><div class="content"><span>Color: <select name="color[]"><option value="<?php echo $row['color_id']; ?>"><?php echo $row['color']; ?></option></select></span><span>Size: <select><option value="<?php echo $row['size_id']; ?>"><?php echo $row['size']; ?></option></select></span></div>';
objTo.appendChild(divtest)
}
</script>
<?php
}
HTML code
<div id="room_fileds">
<div>
<div class='label'></div>
<div class="content">
<input type="button" class="btn btn-success" id="more_fields" onclick="add_fields();" value="Add More" /> <br /><br />
<select name="color[]" class="form-control">
<option value="0">Select Color</option>
<?php
$result=mysql_query("SELECT * FROM color");
while($row=mysql_fetch_array($result)){
?>
<option value="<?php echo $row['color_id'] ?>"><?php echo $row['color']; ?></option>
<?php } ?>
</select>
<select name="size[]" class="form-control">
<option value="0">Select Size</option>
<?php
$result=mysql_query("SELECT * FROM size");
while($row=mysql_fetch_array($result)){
?>
<option value="<?php echo $row['size_id'] ?>"><?php echo $row['size']; ?></option>
<?php } ?>
</select>
</div>
</div>
</div>
Replace your first code with the following:
<script>
var colors = [];
var sizes = [];
var room = 1;
<?php
$result = mysql_query("SELECT * FROM color");
while ($row = mysql_fetch_array($result)) { ?>
colors.push(['<?php echo $row['color_id'] ?>', '<?php echo $row['color'] ?>']);
<?php }
$result = mysql_query("SELECT * FROM size");
while ($row = mysql_fetch_array($result)) { ?>
sizes.push(['<?php echo $row['size_id'] ?>', '<?php echo $row['size'] ?>']);
<?php } ?>
function add_fields() {
room++;
var objTo = document.getElementById('room_fileds');
var divtest = document.createElement("div");
var html = '<div class="label">Room ' + room + ':</div><div class="content"><span>Color: <select name="color[]" class="form-control">';
for (i = 0; i < colors.length; i++) {
html += '<option value="' + colors[i][0] + '">' + colors[i][1] + '</option>';
}
html += '</select></span><span>Size: <select name="size[]" class="form-control">';
for (i = 0; i < sizes.length; i++) {
html += '<option value="' + sizes[i][0] + '">' + sizes[i][1] + '</option>';
}
html += '</select></span></div>';
divtest.innerHTML = html;
objTo.appendChild(divtest);
room++;
}
</script>
$divs='';
$result=mysql_query("SELECT * FROM color,size");
$room=1;
while($row=mysql_fetch_array($result)) {
$divs.='<div><div class="label">Room ' . $room . ':</div><div class="content"><span>Color: <select name="color[]"><option value="'.$row['color_id'].'">'.$row['color'].'</option></select></span><span>Size: <select><option value="'.$row['size_id'].'">'.$row['size'].'</option></select></span></div></div>';
$room++;
} ?>
<script>
function add_fields() {
var objTo = document.getElementById('room_fileds');
objTo.appendChild(<?php echo $divs; ?>);
}
</script>
Try this code hope it works for you
<script>
var room = 1;
function add_fields() {
room++;
var objTo = document.getElementById('room_fileds');
var divtest = document.createElement("div");
<?php
$div_start='<div class="label">Room '."'+ room +'".' :</div><div class="content">';
$color='<span>Color: <select name="color[]">';
$size='<span>Size: <select>'
$result=mysql_query("SELECT * FROM color,size");
while($row=mysql_fetch_array($result)) {
$color.='<option value="'.$row['color_id'].'">'.$row['color'].'</option>';
$size.='<option value="'.$row['size_id'].'">'.$row['size']'.</option>';
}
$color.='</select> </span>';
$size.='</select> </span>';
$div_close='</div>';
$innerHTML=$div_start.$color.$size.$div_close;
?>
divtest.innerHTML ='<?php echo $innerHTML; ?>';
objTo.appendChild(divtest);
}
</script>
This is the final code , it would help if anyone wants to code a similar thing.. just change values and it would work as per your need... and i would like to thank all people who replied to the thread and specially Mohammad Anini .. it wouldnt have been possible without his help !!!
$query = mysql_query("INSERT INTO products (product_name,product_description, product_pic1, product_pic2, product_pic3,product_price,category_id,subcategory_id,product_status,color,size,product_slug, meta_keywords,entrydate)
VALUES ('$product', '$description' , '$image', '$image2', '$image3', '$product_price', '$category', '$subcategory', '$product_status', '$capture_field_vals', '$size', '$product_slug1', '$meta_keywords', Now() )") or die(mysql_error());
if ($query === TRUE) {
$lastid = mysql_insert_id();
$color["color"]=array();
$size["size"]=array();
foreach ($_POST['color'] as $key => $colorvalue) {
}
foreach ($_POST['size'] as $key => $sizevalue) {
}
$cid=array();
foreach($color as $rec){
$cid[]=$rec;
}
$sz=array();
foreach($size as $rec){
$sz[]=$rec;
}
$length=sizeof($color);
for($i=0;$i<$length-1;$i++){
$query2 = mysql_query("INSERT INTO bridge (product_id,color_id, size_id)
VALUES ('$lastid', '$cid[$i]' , '$sz[$i]')") or die(mysql_error());
// echo "<script>alert('New Product successfully Addedd');windows.location.replace('addedit_product.php');</script>";
}

Validating a form created via php with javascript

I have a PHP form.
The form elements are created based off the user's selection which is in a dropdown menu.
What I am trying to accomplish is loop through that form and validate the values of two elements with the id's of "action" and "amt".
Now, I should mention the form which I am trying to validate can have x amount of elements because it needs to be based on the users needs. When I call my validate function it does check the id's and alerts the value, however, it alerts the value of the first input element with the id "amt" three/multiple times.
This is bad as because I need to perform some computation and the duplicate entries would cause an error in the the computation.
Here is my script
<script type="text/javascript">
function validate(){
var i;
var passtest = 0;
var test = "";
var form = document.getElementById("myForm");
alert("Enter function");
for( i = 0; i < form.elements.length; i++){
if(form.elements[i].id === "action" && form.elements[i].value === "Debit" || form.elements[i].value === "Credit"){
test = form.elements[i].value;
// Alerts action
alert(test);
if(document.getElementById("amt").value !=""){
// Get the value from the input element id amt
test = document.getElementById("amt").value;
// Alerts value from id amt
alert(test);
//passtest = 1;
}
else{
document.getElementById("amtTD").innerHTML = "Check Amounts";
return false;
}
alert("End of if stmt");
}
else{
// If it is not id action or id amt just Alert value if any
test = form.elements[i].value;
alert(test);
}
}
///****** END OF FOR LOOP ****** ///
if(passtest === 1){
return true;
}
else{
alert("Submission failed");
return false;
}
}
</script>
Here Is the php code that which displays the form
<form name='transaction' id="myForm" onsubmit="return validate()" action='' method='post'>
<?php
if (isset($_POST['add'])) {
if (isset($_POST['acctN'])) {
echo "<table class='table' id='myRow'' style=''>";
echo "<thead>";
echo "<tr>";
echo "<th>Account Name</th>";
echo "<th>Action</th>";
echo "<th>Amount</th>";
echo "</tr>";
echo "</thead>";
foreach ($_POST['acctN'] as $name) {
$query = "SELECT * FROM ChartOfAccounts WHERE AccountName = '$name'";
$results = mysqli_query($cxn, $query) or die(mysqli_error($cxn));
$row = mysqli_fetch_assoc($results);
echo "<tbody>";
echo "<tr>";
echo "<td class ='col-md-6'><select name='account[]' class='form-control' style=''><option>" . $row['AccountName'] . "</option></select></td>";
echo "<td class ='col-md-2'><select name='debOrCred[]' id='action' class='form-control' style=''>
<option value='Debit'>Debit</option>
<option value='Credit'>Credit</option>
</select></td>";
echo "<td class ='col-md-2'> <input type='text' name='amount[]' class='form-control' id='amt' style=''/> <span id ='amtTD' style='color:red;'> </span></td>";
echo "<td class ='col-sm-2'>$</td>";
echo "<td class ='col-sm-2'><button type='button' onclick='removeCell()' class='btn btn-danger'value='Remove' name='".$row['AccountName']."'>Remove</button></td>";
echo "</tr>";
}
echo "</tbody>";
echo "</table>";
}
echo "<label style='margin-left:7px;'>Documentation</label>";
echo "<textarea name='src-doc' class='form-control' rows ='4' cols='50' placeholder='Description' style='max-width:575px; margin-left:8px;' ></textarea>";
echo "<div style='padding:10px;'>";
echo "<label>Source</label>";
echo "<input type='file' name='fileToUpload' id='fileToUpload'>";
echo "</div>";
echo "<input type='submit' class='btn btn-primary' value='Submit' name='subTrans' style='margin-top:7px; margin-left:8px; '/>";
}
?>
</form>
Thank you all that help and provide input.

Get mysql column of a clicked item

I have searched endlessly for an answer but have found none. I am trying to get the id of a clicked item. The item that I am clicking is from mysql database and has been displayed through a for loop. When the item is clicked I am taken to another page. In this page I want to utilize the id from the clicked item to get other information from that row in mysql database; this much I can do. The problem is getting the id from the clicked item and sending it.
This is the most recent way that I tried:
First I displayed the items from mysql.
<?php
$query = "SELECT `video` FROM `challenge_name` ORDER BY `id`";
$result = mysql_query($query);
if($result = mysql_query($query))
{
for($i = 0; $i < mysql_num_rows($result); $i++)
{
$id = $i;
$code = "<div id=\"challenge_preview\"><h7 class=\"challenge_preview_item\"
id=\"challenge_preview_name\"></h7><a href=\"challengeprofile.php\">
<video
class=\"challenge_preview_item\" id=\"challenge_video\"
src=\"".mysql_result($result, $i)."\"></video></a></div>";
echo $code;
}
}
else
{
die('Couldn\'t connect'. mysql_error());
}
?>
Than I put the id in a hidden form so that I could attempt to POST it to the other page:
<form action="<?php echo $current_file; ?>" method="POST">
<input type="hidden" name="id" value="14">
</form>
On the script.php file that is included in both pages, I put
$(#challenge_video).click(function(){ <?php $id = $_POST['id']; ?> ;});
And on the page that the id is being posted to I put
<?php
include 'script.php';
echo getChallengeData('name', 'id', $id)
?>
Please help, Thank you
These are the edits
<div id='challenge_previews'>
<?php
$query = "SELECT `video` FROM `challenge_name` ORDER BY `id`";
$result = mysql_query($query);
if($result = mysql_query($query))
{
for($i = 0; $i < mysql_num_rows($result); $i++)
{
$id = $i;
echo "<div id=\"challenge_preview\"><video class=\"challenge_preview_item challenge_video\" src=\"".mysql_result($result, $i)."\"></video></div>";
}
}
else
{
die('Couldn\'t connect'. mysql_error());
}
?>
<form action="<?php echo $current_file; ?>" method="GET">
<input type="hidden" name="id" value="14">
</form>
</div>
This is the code for page 2
<h1 id="challenge_profile_name">
<?php
$id = substr(base64_decode($_GET['id']),6);
echo getChallengeData('name', 'id', $id);
?>
</h1>
This is the code for the getChallengeData method in the core.inc.php
function getChallengeData($field1, $field2, $field3)
{
$query = "SELECT `$field1` FROM `challenge_name` WHERE `$field2` = '$field3'";
if($query_run = mysql_query($query))
{
if($query_result = mysql_result($query_run, 0, $field1))
{
return $query_result;
}
}
}
That error that I'm getting has to do with the implementation of the getChallengeData method on page 2. The error says
Warning: mysql_result(): Unable to jump to row 0 on MySQL result index 10 in C:\xampp\htdocs\ChallengeNetworkWebsite\core.inc.php on line 42

checking dynamically created textboxes for values

I am creating a form for inserting data which technologies are being used by which customers.
I get data of customer's ID and name and select a customer in an drop-down list, and i get data from technologies id and description and display description in a table + it creates a textbox (ID='box-". $row1['ID_T']."') for every technology entry in a DB.
So now i would like to check this dynamically created textboxes with jquery for value (if empty or filled with data) (getelementbyid) but i can not find a way to check theese DYN textboxes.
The ID_T and ID_C will be loaded into another table containing these two PK's and add string from textbox to value.
i would appreciate your help so much!
<HTML>
<HEAD>
<SCRIPT>
function update_tech(id,description)
{
var x = confirm('Do you want to edit technology '+description);
if (x == true)
{
document.getElementById('update_id').value = id;
//document.getElementById('description').value = description;
//document.form_update.submit();
}
}
</SCRIPT>
</HEAD>
<?php
include "connection.php";
$sql = "SELECT ID_C, Name FROM empresa";
$rs = mysql_query($sql, $conn);
$sql2 = "SELECT ID_T, description FROM technologies";
$rs2 = mysql_query($sql2, $conn);
while($row = mysql_fetch_array($rs2))
{
if (isset($_POST["box-".$row["ID_T"]]))
if ($_POST["box-".$row["ID_T"]] != "")
echo "INSERT ....".$_POST["box-".$row["ID_T"]]."<br>";
}
$rs2 = mysql_query($sql2, $conn);
mysql_close($conn);
?>
<BODY>
<SELECT NAME="customers" ONCHANGE="showCustomer(this.value)">
<?php
if (mysql_num_rows($rs))
{
while($row = mysql_fetch_array($rs))
{
?>
<option value='<?php echo $row['ID_C'] ?>'><?php echo $row['Name']?></option>
<?php
}
}
else {
echo "<option value=\"0\">No customers</option>";
}
?>
</SELECT>
<FORM METHOD="POST">
<?php
echo "<table border='0'>";
while($row1 = mysql_fetch_array($rs2))
{
echo "<tr>";
echo "<td><INPUT TYPE='text' name='box-". $row1['ID_T']."' ID='box-". $row1['ID_T']."'></td>";
echo "<td>" . $row1['description'] . "</td>";
echo "</tr>";
}
echo "</TABLE>";
?>
<INPUT TYPE="SUBMIT">
</FORM>
</BODY>
</HTML>
You can either maintain an array of input box ids or use the jquery partial selector to identify all the input boxes.
jQuery approach is something like:
$('input[id^="box-"]').each(function(e, i) { console.log(e); };

How to add select box field dynamically after clicking add button by using php or javascript and store selected value in selected box in database

if (isset($_POST['dept']) && isset($_POST['batch']) && isset($_POST['Month']) && isset($_POST['Year']) && isset($_POST['semester'])) // based on these values selected from database
{
$dept = $_POST['dept'];
$batch = $_POST['batch'];
$month = $_POST['Month'];
$year = $_POST['Year'];
$semester = $_POST['semester'];
$query = db_select('student_master');
$query->fields('student_master', array('reg_no','name','dob','dept_code','degree','batch_year'));
$query->condition('dept_code',$dept,'=') AND $query->condition('batch_year',$batch,'=');
$results = $query->execute();
echo "<table>";
echo "<tr>";
echo "<td><label for='reg_no'> Registration Number </label></td>";
echo "<td>";
echo "<select name='reg_no'>";
foreach($results as $student_result)
{
echo "<option value ='$student_result->reg_no'> $student_result->reg_no</option>";
}
echo "</select>";
echo "</td>";
echo "</tr>";
$query = db_select('subject');
$query->fields('subject', array('subject_name','credits','subject_code'));
$query->condition('dept_code',$dept,'=') AND $query->condition('semester_appear',$semester,'=') ;
$subject_results = $query->execute();
echo "<tr>";
echo "<td><label for='Subject'>Subject Name</label></td>";
echo "<td>";
echo "<select name = 'sub_name' id = 'sub_name'>";
foreach($subject_results as $subjects_result)
{
echo "<option value ='$subjects_result->subject_code'> $subjects_result->subject_name</option>";
}
echo "</select>";
echo "</td>";
echo "</tr>";
echo "<tr>";
echo "<td><label for='Subject'>Subject Serial Number</label></td>";
echo "<td>";
echo "<select name='subject_serial' id = 'sub_name'>";
if ($semester == "SEMESTER-I")
{
for($i=101; $i<=110; $i++ )
{
echo "<option value ='$i'>$i</option>";
}
}
elseif ($semester == "SEMESTER-II")
{
for($i=201; $i<=210; $i++ )
{
echo "<option value ='$i'>$i</option>";
}
}
elseif ($semester == "SEMESTER-III")
{
for($i=301; $i<=310; $i++ )
{
echo "<option value ='$i'>$i</option>";
}
}
elseif ($semester == "SEMESTER-IV")
{
for($i=401; $i<=410; $i++ )
{
echo "<option value ='$i'>$i</option>";
}
}
echo "</select>" ;
echo "</td>";
echo "</tr>";
echo "</table>";
}
else
{
return "please check the your input";
}
How to add select box field dynamically after clicking add button (the selected box contain the datas from database after clicking the add button, and same selected value store in database) by using php or javascript and store selected value in selected box to database
Create a PHP page that returns the required HTML string only
And then on client side using jquery you can append that html to desired element
e.g.
$("#btnAddnew").click(function(){
$.get('ajax/test.php?id=1', function(data) {
$('#divDropdown').html(data);
});
});
Then in post you can pass the selected dropdown's value using javascript
e.g. If it is like
then $("#drpRegNum").val() would give you the selected value

Categories

Resources