Creating form fields from user input - javascript

I found a code that creates some form fields based on a number chose by the user.
<script type='text/javascript'>
function addFields(){
var number = document.getElementById("member").value;
var container = document.getElementById("container");
while (container.hasChildNodes()) {
container.removeChild(container.lastChild);
}
for (i=0;i<number;i++){
container.appendChild(document.createTextNode("Member " + (i+1)));
var input = document.createElement("input");
input.type = "text";
input.name = "Member["+i+"]";
container.appendChild(input);
container.appendChild(document.createElement("br"));
}
}
</script>
<input type="text" id="member" name="member" value="">Number of Members: <br />
<input type="button" id="enterdetails" value = "Enter Details"onclick="addFields()">
<div id="container"/>
</div>
It works fine. But I want to create elements with names/values imported from a database. In php I do like this:
<SELECT name='smth'>
<OPTION value=""></OPTION>
<?php
$qry = $dbh->query("select * FROM table");
while ($a = $qry->fetch(PDO::FETCH_ASSOC)) {
$smth = $a['smth'];
echo "<OPTION value='$smth'>".$smth."</OPTION>";
}
?>
</SELECT>
Need help on how to do it in javascript.

You cant get database fields with javascript. You must use php or something like this.
Maybe this can help you. Here is the link. choose your database and table, and select your field names, and choose field's type of form (text area, text, radio button groups, etc) and push create. You will have a bootstrap designed form and php insert code writed with medoo (medoo.in).
you can use this. create your database first and make form automaticly. Copy code and paste to your pages.
Also i offer you to use meddo to connect and use sql with it. There is a sample in that link form.min.php, includes your database and user and pass information.

Related

How to make divs which are created when a form is submitted, remain in place when the form is resubmitted

I am making a webpage where the user can use a form to search for a string and then divs will appear showing rows with matching info from a database. Then when a checkbox is clicked on a row it will move up to another div. I would like for the rows which have been selected via the checkbox to remain where they are when the form is resubmitted but still disappear when the checkbox is unclicked.
I have taken this video to show how it is currently working, which should hopefully make my question make sense.
https://imgur.com/a/DmkP0ut
This is the code for my form
<form action = "" method = "POST">
<div class = "searchcontainer">
<input id = "search" type="search" name = "search" class = "textbox" placeholder
= "Type the students name and press Enter to search...">
<input type = "submit" style="display:none" id = "submitsearch"/>
</div>
</form>
Then when the form is submitted this code will run to create the divs that appear (This is just a really short version, let me know if you need to see all of it)
<?php
if(isset($_POST['search'])){
$input = $_POST['search'];
$result = $conn->query("select * from logins");
let r<?php echo $studentid ?> = document.createElement("div");
r<?php echo $studentid ?>.id = "r<?php echo $studentid ?>";
r<?php echo $studentid ?>.className = "rowcontainer";
document.getElementById("tablecontainer").appendChild(r<?php echo $studentid ?
>);
Then this is the Javascript code which moves the rows to the 'selected' container when the checkbox is ticked and back to the 'tablecontainer' when unckecked.
<script>
const main = document.querySelector(".tablecontainer");
const selected = document.querySelector(".selected");
main.addEventListener("click", function(e) {
const tgt = e.target;
if (tgt.classList.contains("move")) {
const rowContainer = tgt.closest(".rowcontainer");
if (tgt.checked) {
selected.append(rowContainer);
}
}
})
selected.addEventListener("click", function(e) {
const tgt = e.target;
if (tgt.classList.contains("move")) {
const rowContainer = tgt.closest(".rowcontainer");
main.append(rowContainer)
}
})
</script>
From what I found online it looks like I will need to se session variables to keep the rows in place once they have been selected, but I dont really know how to do this, so help would be appreciated.
Thanks
Edit: I have a had a look through these answers but as a beginner they do not make much sense to me. I have found that I can use
var rowsselected = document.getElementById("selected").children;
to get a list of all the children divs in my selected div, so is there a way I can save this list so it persists when the form is resubmitted and take the children from this list and append them to selected again. If you could show examples that would be good. Also I should have mentioned this in the main post but I would also like to carry over info from the rows which have been selected to the next page so if I could make the ids of these rows into session variables or something like that that would be good.

How to display mysql data through javascript in dynamic form field

I have a dynamically added HTML form field which takes a list of company names to store in MySql database. Since I have only 1 column in database, I am using serialize function to save & unserialize function to display again (on the edit page). The saving part works fine.
The issue is, I am unable to figure out how to display the various companies in the dynamic fields. I have hard coded $internname[0] at the first field (which is a static field) & added $internname[1] to the dynamic field (in script). This displays the first company name in the first field & the second company name in all the remaining fields.
I know, I need to pass an incremental number into the dynamic field, but how do i write this function? Tried using the already available xint variable which is incrementing anyway, didn't work.
<?php
$query = "SELECT * FROM user WHERE mail = '$mail' LIMIT 1";
$result=mysqli_query($db,$query);
while($row = mysqli_fetch_array($result))
{
?>
<div class="field_wrapperint">
<div class="inlineinput2b">
<div align="left">Internships:</div>
<?php $internshipname = unserialize($row['internshipname']);
foreach ((array) $internshipname as $internname[])
?>
<input type="text" name="internshipname[]" placeholder="Company Name" value="<?php echo htmlspecialchars($internname[0]);?>"/>
</div>
<div class="inlineinputb">
<img src="add-icon.png"/>
</div>
</div>
<input type="submit" name="update_profile" class="action-button" value="Update Profile" />
<?php
}
mysqli_close($db);
?>
<!-- Script for dynamic button adding -->
<script type="text/javascript">
$(document).ready(function(){
var maxField = 4; //Input fields increment limitation
var xint = 0; //Initial field counter is 1
var addButtonint = $('.add_buttonint'); //Add button selector
var wrapperint = $('.field_wrapperint');
var fieldHTMLint = '<div><div class="inlineinput2b"><input type="text" name="internshipname[]" placeholder="Company Name" value="<?php echo htmlspecialchars($internname[1]);?>"/></div><div class="inlineinputb"><img src="remove-icon.png"/></div></div>' ; //New input field html
//Once add button is clicked
$(addButtonint).click(function(){
//Check maximum number of input fields
if(xint < maxField){
xint++; //Increment field counter
$(wrapperint).append(fieldHTMLint); //Add field html
}
});
//Once remove button is clicked
$(wrapperint).on('click', '.remove_buttonint', function(e){
e.preventDefault();
$(this).parent('div').parent('div').remove(); //Remove field html
xint--; //Decrement field counter
});
});
</script>

javascript onchange with 2 different dropdown lists

Im pretty new with javascript programming.
I have some .php code, where 2 dropdown lists (in the same FORM) are populated by 2 different mysqli queries, this works without any problem.
Im trying to get javascript to handle the selected parts of the dropdown lists, with onchange, this works for only one dropdown list, and i cant really figure out how to get around this one.
This is the code that works with one dropdown menu, and it updates automaticly the page without submitting:
$chosen_location = $_GET['Lid'];
$chosen_car = $_GET['Cid'];
?>
<script type="text/javascript">
function changeDropDown(dropdown){
var location = dropdown.options[dropdown.selectedIndex].value;
*var car = dropdown.options[dropdown.selectedIndex].value;*
document.getElementById("form1").action = "test.php?Lid=" + location + "&Cid=" + car;
document.getElementById("form1").submit();
}
</script>
Part of the .php code:
<select size="1" name="form_location_id" id="form_location_id" onchange='changeDropDown(this);'>
<option value = <?php echo ($location_id) ?> selected><?php echo ($location_name) ?></option>
<select size="1" name="form_car" id="form_car" onchange='changeDropDown(this);'>
<option value = <?php echo ($car_type_id) ?>><?php echo "" . ($car_class) . " - " . ($car_manufacturer) . " - " . ($car) . "" ?></option>
The italic marked I know will not catch the correct value, but this is where im at right now...
How is it possible to get an action URL with both selected values ? as this is going to be used in a mysqli query to show data from the actual selection
Thanks in advance... :)
Currently, you are submitting the form through JavaScript. If the selects are inside the form, their values will automatically be submitted when you submit the form. You don't even have to change the action of the form.
So, you can just generate a normal form (including submit button, if you will), and it will work. Then, add a little JavaScript sauce to make it submit automatically.
The code below does just that. JavaScripts adds a class to the body. This is a way to easily change styling based on JavaScript being enabled or not. In this case, I use it to hide the submit button, which is only needed in a non-JavaScript situation.
Then, I bind the on change handler, not unlike yours, to submit the form when a value is selected. By giving the selects a proper name, their values will automatically be added as intended.
Note how the event handlers are bound through code. You don't have to hardcode any calls to JavaScript in the HTML, so you can keep the HTML clean and separate (readability!).
// Bind to load event of the window. Alternatively, put the script at the end of the document.
window.addEventListener("load", function() {
// Indicate that JavaScript works. You can use this to style the document, for instance
// hide the submit button, if the form is automatically submitted on change..
document.body.classList.add("js");
// With JavaScript, you can automatically submit the form, but you still don't have to modify it.
var theform = document.getElementById("theform");
var selects = document.querySelectorAll("#theform select");
for (var i = 0; i < selects.length; ++i) {
selects[i].addEventListener("change",
function() {
alert("submitting now");
theform.submit();
});
}
});
.js button[type="submit"] {
display: none;
}
<!-- Just a form with selects is enough. You don't even have to have JavaScript to post this. -->
<form id="theform" action="test.php" method="get">
<select name="Lid">
<option>Example...</option>
<option>Use PHP,</option>
<option>to fill these.</option>
</select>
<select name="Cid">....</select>
<button type="submit">Post</button>
</form>
You can update your code to following
function changeDropDown(){
var elLocation = document.getElementById('form_location_id');
var elCar = document.getElementById('form_car');
var location = elLocation.options[elLocation.selectedIndex].value;
var car = elCar.options[elCar.selectedIndex].value;
document.getElementById("form1").action = "test.php?Lid=" + location + "&Cid=" + car;
document.getElementById("form1").submit();
}
try to do this
<script>
// get select elements
var form_location_id = document.getElementById('form_location_id');
var form_car = document.getElementById('form_car');
// on change
form_location_id.addEventListener('change', changeDropDown1);
form_car.addEventListener('change', changeDropDown2);
</script>
And change the 'changeDropDown1' and 'changeDropDown2' to your handler function
try this
<script type="text/JavaScript">
var dropdownLocation = document.getElementById("form_location_id");
var dropdownCar = document.getElementById("form_car");
function changeDropDown() {
var location = dropdownLocation.options[dropdownLocation.selectedIndex].value;
var car = dropdownCar.options[dropdownCar.selectedIndex].value;
document.getElementById("form1").action = "test.php?Lid=" + location + "&Cid=" + car;
document.getElementById("form1").submit();
}
</script>
dropdownLocation et dropdownCar are outside the function to save time because this 2 vars need only to be set one time

Dropdown list to JavaScript array to fill text boxes

I am trying to display a MySQL table on a job sheet system form that I am making the drop down list shows the customer details and then once selected the fields should be filled in on the main form.
I know people tend to use AJAX but this is to be used on a tablet tethered to a mobile and want to ask the server as little as possible.
Because I have already got the details from the SQL to display the drop down I thought I could use this. I found the original code at:
http://board.phpbuilder.com/showthread.php?10372137-RESOLVED-How-do-I-populate-multiple-text-boxes-from-a-dropdown-(I-can-populate-1-text-box!)
but I also want to display items that aren't on the dropdown list. Someone said it works but the more I have learned I couldn't see how because the array it was building just didn't seem to be in a JavaScript format.
I have the drop down working and also it fills a JavaScript array using names but I just cannot work out how to use the array to show in the fields.
It seems to be the named indexes used in the array. I can get a test array to display when I use the normal static array but I have commented them out but as soon as I try to use the names on the array I get undefined errors.
<html>
<head>
<script type="text/javascript">
<?php
include_once 'includes/db_connect.php';
$query1 = "SELECT * FROM customer";
$result1 =($mysqli-> query($query1));
// build javascript array building an object
// build javascript array
while($row=mysqli_fetch_array($result1)){
echo 'customer['.$row['customer_id'].'] = new Array(';
echo 'customer['.$row['customer_id'].'][customer_id] = "'.$row['customer_id'].'";';
echo 'customer['.$row['customer_id'].'][post_code] = "'.$row['post_code'].'";';
echo 'customer['.$row['customer_id'].'][company_name] = "'.$row['company_name'].'");';
}
?>
</script>
</head>
<body>
<form name="customerform" form id="customerform">
<p>
<select name="customerselect" id="customerselect" onChange="showname()">
<option value="">Select customer</option>
<?php
$query1 = "SELECT * FROM customer";
$result1 =($mysqli-> query($query1));
// build javascript array
while($row=mysqli_fetch_array($result1)){
echo'<option value="'.$row['customer_id'].'">'.$row['forename'].'">'.$row['surname'].'">'.$row['customer_name'].'</option>';
}
?>
</select>
</p>
<p>
<input type="text" name="cust" value="" id="cust" />
<input type="text" name="cust" value="" id="customerselected" />
<input type="text" name="post_code" value="" id="post_code" />
</p>
<p>update
<input type="button" name="update" id="update" value="update" onClick="showname()">
<p> </p>
<p>
<input name="submit" type="submit" id="submit" value="submit" />
</p>
</form>
</body>
<script>
//var customer = Array();
var customer = Array();
//This below is a test multi dimensional Array which does work. //
//customer['CCS'] = Array[{forename:'Robert', surname:'Grain', company:'HOMS'}];
function showname() {
//this var takes the result of the selected drop down list and shows the correct part of the array.
var customerselected = document.getElementById('customer');
customername = customerselected.value;
// this does work but not from the array just fills the details up
document.customerform.customerselected.value = customername;
// the next part takes the selected dropdown data and calls for the correct place in the array
// document.getElementById("cust").value = customer['CCS'][0];
// document.getElementById("cust").value = customer[CCS]["forename"] ;
// (customer[''][forename]);
document.customerform.post_code.value = customer[customerselect]["post_code"];
}
window.onload=function() {
showname();
}
</script>
</html>
This is the source code from Explorer in the console. from the JavaScript Array.
</body>
</html>customer[118] = new Array(customer[118][customer_id] = "118";customer[118][post_code] = "L37 4RG";customer[118][company_name] = "jc knight");customer[119] = new Array(customer[119][customer_id] = "119";customer[119][post_code] = "DE56 7HG";customer[119][company_name] = "farm Customer giles");customer[122] = new Array(customer[122][customer_id] = "122";customer[122][post_code] = "LE67 8FH";customer[122][company_name] = "a test company");
Also this dropdown list creates:
<select name="customerselect" id="customer" onChange="showname()">
<option value="">Select customer</option>
<option value="118">John">Knight"></option><option value="119">Bill">Giles"></option><option value="122">Robert">Grain"></option> </select>
</p>
Maybe I should move the code to the bottom of the HTML for the JavaScript array although I wasn't sure if this wouldn't be initialised when required because it has ran the HTML first. I'm a little unsure if the order of things were correct.
The error I receive happens as soon as I change the drop downlist and it shows the following:
document.customerform.post_code.value = customer['customerselect'][post_code];
}
X 'post_code' is undefined
I think somewhere I am getting my document.value wrong when showing my array ?
Rather don't hope that a constant will work here.
Instead try the below as a replacement:
// build javascript array
while($row=mysqli_fetch_array($result1)){ ?>
var customer["<?=$row['customer_id']?>"] = [];
customer["<?=$row['customer_id'];?>"]['customer_id'] = "<?=$row['customer_id'];?>";
customer["<?=$row['customer_id'];?>"]['post_code'] = "<?=$row['post_code'];?>";
customer["<?=$row['customer_id'];?>"]['company_name'] = "<?=$row['company_name'];?>";
<? }
Thanks smftre for that. In the end I have opted for the jquery and ajax. and I think it has worked out betted for it originally I was trying to make the code as efficient as possible on bandwidth because the system is to be used but ajax seems to be the standard for a reason and works very well.

javascript: create dynamic checkbox from dropdown menu

I have a dropdown menu which get the values dynamically from an array with a foreach loop. I know that the javascript "getElementById" need a unique key. The problem is that my unique key is a combination of "service_select" and "$value2". So that every service can be more than one.
The only unique key I have from the dropdown elements is the variable $value.
<?php
echo'<select id="service_name" name="service_select">';
foreach($array_name_new as $key=>$value)
{
echo'<option value="'.$value.'">'.$value.'</option>';
}
echo'</select>';
echo'<p>Parameter: <input name=\"$value2\" value=\"$value2\'/></p>';
?>
For each selected value in the dropbox I want a "checkbox" with the dropbox selection as name and value. I need although a seperate textfield with "$value2" as value.
I have already found this thread (How to create list of checkboxes dynamically with javascript), but I'm a newbe to javascript and don't understand the code completely.
What does the if clause in function "function populate()"? Is
this for generating the checkboxes?
Where has the codepart in the answer be added into the original code?
According to the mentioned thread I tried to modify my code like this:
<?PHP
.
.
.
echo'<select id="service" name="service_select" onchange="add_service(this.id,$_POST['service_select'],$value2)">';
foreach($array_command_name_new as $key=>$value)
{
echo'<option value="'.$value.'">'.$value.'</option>';
}
echo'</select>';
$key2 = array_search($value,$command_in_hostfile[0]);
$value2 = $command_in_hostfile[1][$key2];
$id2 = compact("$_POST['service_select']", "value2");
<script type="text/javascript">
function add_service($id2, $_POST['service_select'], $value2)
{
foreach($array_command_name_new as $key=>$value)
{
var elementid = docuemnt.getElementById($id2);
var checkbox = document.createElement('id');
checkbox.type = "checked";
checkbox.name = "$_POST['service_select']";
checkbox.value = "$_POST['service_select']";
checkbox.id = "$id";
var label = document.createElement('$_POST['service_select']')
label.htmlFor = "id";
label.appendChild(document.createTextNode('$_POST['service_select']');
container.appendChild(checkbox);
container.appendChild(label);
}
echo'<p>Parameter: <input id="parameter" name=\"$value2\" value=\"$value2\' onclick="addService('value_parameter')" /> </p>';
var s1 = document.getElementById($id2);
}
</script>
.
.
.
?>
I would be pleased if anyone can help me.
I'm afraid the solution will be a bit more complex... you need to add inputs to your form for every value the user selects...
Something like this:
[Option a] Parameter: [__________] [X]
[Option b] Parameter: [__________] [X]
[Please select... ][v]
Every time a user selects a new option you must add a new line to allow the parameter to be entered.
You will then need a [X] button in each line so the user can remove unwanted entries.
This is Javascript intensive :)

Categories