JavaScript DOM dynamc Form from PHP - php

My MySQL Database Provides A List of Items (and integer IDs with them) in a <select> and a qty field for usage on my web form (with style display: none so it is hidden). But: I want the user to be able to select how many choices of this type he wants to enter in the form - how can I dynamically make multiple selects?
Example: The products in the inventory are oranges, bananas and peaches. There is one select tag:
<select name="p[0]">
<option value="2">Orange</option>
<option value="23">Banana</option>
<option value="31">Peach</option>
</select>
QTY <input type="text" name="qty[0]" />
Now I want to add another dropdown allowing the user to chose between ordering one, two or three classes of products. he could choose 2, and then two copies of the above code are inserted into the DOM so he can enter two product choices and quantities. (the Script would give them the names p[0] and p[1] etc.)
Can anyone help me here?

The simplest thing is to clone the nodes you already have as many times as needed (as opposed to creating new DOM via document.createElement() or innerHTML.
To start, surround your existing <select> and <input> with a div which has a well-known ID. Also, you want to add another DIV to put the repeated inputs into:
<div id="template">
<select name="p[0]"> ... </select>
QTY: <input name="qty[0]"/>
</div>
<div id="copies">
</div>
Now, create a function that will replicate the template some N number of times:
function makeCopies(num) {
var template = document.getElementById('template');
var output = document.getElementById('copies');
// Delete existing nodes.
output.innerHTML = '';
// We start with 1, not 0, because we already have the template.
for (var i = 1; i < num; i++) {
var copy = template.cloneNode(true);
// Change the input names according to index.
copy.getElementsByTagName('select')[0].name = 'p[' + i + ']';
copy.getElementsByTagName('input')[0].name = 'qty[' + i + ']';
output.appendChild(copy);
}
}

Related

save all html select box contents to sql server table

EDIT : PLEASE FIND MY SOLUTION BELLOW
I have two select boxes in a FORM that i populate from two different tables.
SELECT1 displays client specific options.
SELECT2 displays all available options except those already on SELECT1
Everything works fine populating them, moving items from one to the other etc.
What I don't have a clue is how to, after submit of the FORM, I store those items of SELECT1 back to the database.
For each item on that SELECT box I need to check if it already exists on MY_TABLE_2 and if it does not, store it.
When I check var_dump(SELECT1) I only see the value of the last selected item but it normally contains more than one item in SELECT1.
For now I'm calling a stored procedure for all the other fields that will go on MY_TABLE_1 and that is OK.
I would need to do some transaction that updates the two tables or rolls back if i get an error. That is working if i store only one item.
But how I send to the stored procedure ALL the items.
Any help or clues?
Here's a print-screen if it can help understand:
The code to generate the form:
echo '<select name="ed_clilabelcodes" id="ed_clilabelcodes" style="width: 200px" multiple>';
while($row = sqlsrv_fetch_array($dvclilablist)){
echo '<option value="'.$row[0].'">'.$row[0].' - '.$row[1].'</option>';
}
echo '</select>';
----------- MY SOLUTION -----------
All items on any of those select boxes exist in a table (dbo.MyItems) identified by the field OptCode.
What I really needed was to store witch of those items were selected by a particular client.
I was thinking of having a second table where I would store those items but I was in reality duplicating information and I didn't find it to be the best solution.
Since I really only needed those selected codes attached to the client file I did the following:
I have one javascript function inspired from HERE that allows me to move items between the two select boxes and, by the way, from HERE to create a function that sorts the items in the boxes.
Each time I add or remove an item from the client's list box I immediately call the sort function, so I just update a hidden input value with all item values (codes) present in the select box immediately calling this javascript function :
function RecheckCodes() {
var vlist = document.getElementById("ed_clilabelcodes");
var vlabcodes = "";
var i;
for (i = 0; i < vlist.length; i++) {
if (i == 0) {
vlabcodes = vlabcodes + "\'" + vlist.options[i].value + "\'";
}
else {
vlabcodes = vlabcodes + ",\'" + vlist.options[i].value + "\'";
}
}
document.getElementById("v_clilabcodes").value = vlabcodes;
}
On FORM Post i just save that string in a client field.
Latter i can repopulate the boxes for edit using following 2 stored procedures to get the items (first SQL will get the string with the codes and is called from the 2nd one that gets the item description from items table).
ALTER PROCEDURE [dbo].[DavGetOptCodeByClient]
#vclicode nvarchar(12),
#vopttype nvarchar(12),
#voptcodes nvarchar(300) OUTPUT
AS
BEGIN
SET NOCOUNT ON;
SELECT #voptcodes = optcodes
FROM dbo.dav_client_options
WHERE clinumber = #vclicode AND opttype = #vopttype
END
ALTER PROCEDURE [dbo].[DavGetOptDetailByClient]
#vclicode nvarchar(12),
#vopttype nvarchar(12)
AS
BEGIN
SET NOCOUNT ON;
DECLARE #v2optcodes nvarchar(1000)
DECLARE #vsql nvarchar(1000)
exec dbo.DavGetOptCodeByClient #vclicode,#vopttype, #v2optcodes OUTPUT
SET #vsql = 'SELECT optcode, optdetail ' +
'FROM dbo.dav_global_options ' +
'WHERE ("optcode" IN ('+#v2optcodes+')) AND (opttype = '''+#vopttype+''')'
EXEC sp_executesql #vsql
END
So everything is working fine for what I needed even if I'm sure some improvement can be made on the code.
to be able to send all the elements the simplest option is to select them, it is not enough that they are in the list but they have to be selected, for that it must be activated the "multiple" option of the select, once done that by pressing the key "control" or "shift" you can make multiple select in your list.
<form action="#" method="post">
<select name="Color[]" multiple> <!--the option multiple must be active and be array -->
<option value="Red">Red</option>
<option value="Green">Green</option>
<option value="Blue">Blue</option>
<option value="Pink">Pink</option>
<option value="Yellow">Yellow</option>
</select>
<input type="submit" value="Get Selected Values" />
</form>
Another option is to add this small javascript (jQuery) in an html so you do not have to press or control or shift when you select several options, just click and you will be selected
$('option').mousedown(function(e) {
e.preventDefault();
$(this).prop('selected', !$(this).prop('selected'));
return false;
});
Source :How to avoid the need for ctrl-click in a multi-select box using Javascript?
And at the end you have your data with a simple php
<?php
$data=$_POST;
if($data) {
foreach ($data['Color'] as $option) {
echo $option;
}
var_dump($data);
}
?>

If first drop down changes to auto change of second drop down using php

I have two drop downs, one is repositories list where lists not get from database
another one drop down is their branchs
if I select "a" repo option another drop down should show their branches and user change his mind select "b" option second drop down should show their branches
how can done this using php without using database ?
If I understand your question properly, you want to create something like this:
I assume that you are aware of all consequences from not using DB for this, so I skip this part.
You will have to use some Javascript, and to make it easier - jQuery, that makes two things:
Shows the second dropdown after user selects an option from the first one,
Updates options in 2nd dropdown when value of the 1st dropdown changes.
So here's your HTML:
<select id='dropdown1' name='branch'>
<option value='it'>IT</option>
<option value='entertainment'>Entertainment</option>
</select>
<select id='dropdown2' name='branch-sub' style='display:none;'></select>
And here's your jQuery / javascript:
var options = {
'it': ["Programming", "Software", "Hardware", "..."],
'entertainment': ["PC Games", "Movies", "Music", "..."]
// And so on
}
$(document).ready(function(){
$('#dropdown1').change(function(){
$('#dropdown2').show();
$('#dropdown2').html('');
var opts = options[$('#dropdown1').val()];
for(var a = 0; a < opts.length; a++)
$('#dropdown2').append("<option value='" + opts[a] + "'>" + opts[a] + "</option>");
});
});
Edit (15-03-2018): I updated the JS code, so it's working now.

Dynamic select list & PHP array

I want to create a PHP array of a select list. The list have dynamic options, the options are filled with the help of javascript. I want to get all the options on next page.
So I want to create an array of options. Is there any another way to complete this stuff?
Can anybody help me out? Thank you so much in advance.
<script type = "text/javascript">
var val = "";
function removeOptions(selectbox) {
val = selectbox.value;
for (var i = selectbox.options.length-1; i>=1; i--) {
if (selectbox.options[i].selected) {
addOption(document.form1.list2,val,val);
selectbox.remove(i);
document.form1.list1.focus();
}
}
}
function addOption(selectbox,optiontext,optionvalue ){
var optn = document.createElement("OPTION");
optn.text = optiontext;
optn.value = optionvalue;
selectbox.options.add(optn);
}</script>
//list1
<select name="list1" size="7" multiple="multiple" id="jumpMenu" onchange="removeOptions(this)" style="width:200px">
<option>Choose Area...</option>
<?php foreach($dbh->query($sql) as $row){
$a=$row['name'];?>
<option value="<?php echo $a?>"><?php echo $a?></option>
<?php }?>
</select>
//list2
<select name="list2" size="7" multiple="MULTIPLE" id="list2" style="width:170px">
</select>
First: if You want to use multiple with select box, then this selectbox's name have to contain sharp brackets: name="list1[]" and name="list2[]" - this way a PHP will know that this is an array of values.
Second: learn jQuery - though it may seem hard in the beginning it will save You a lot of time and browser-compatibility problems in the future. And jQuery will save Your a*s many times in the future.
For Your purpose I would recommend not just using onchange events but implement additional 4 buttons between the two multiselectboxes that will move the selected options from one to another or all from one to another. This kind of multiselect looks like the one pictured below.
By the first button >> all the options from 1. select are moved to the second one and vice versa with the 4th button <<.
By the second button > only the selected option(s) is(are) moved the second select and vice versa with the third button <.
By this You only catch the click event on the buttons... That is really easy using jQuery...

Get values from multiple select boxes with same name? Including its value with jquery and php

I have looked for answers on here and have not found anything that directly can help me so I am going to ask here. I have a form with multiple select boxes:
<select name="acabados[]">
<option value="1">ABC</option>
<option value="2">DEF</option>
<option value="3">GHI</option>
</select>
<select name="acabados[]">
<option value="1">ABC</option>
<option value="2">DEF</option>
<option value="3">GHI</option>
</select>
As you can see they are the exact same select box. I have told the client to use select multiple but he wants it this way. The user can add as many as these select boxes as they desire (so it could be up to 20 select boxes at a time) and I need to get the value (1 or 2 or 3) and the text inside the option. It is then an array that I need to break down cause I need to add the total values of the select boxes in php. I could either use jquery for collecting the values or php, which ever is easier. Thank you in advance for any help!!
Try this, it will work for dynamically created select elements too.
$(document).on('change', 'select[name="acabados[]"]', function(){
var total = 0;
$('select[name="acabados[]"]').each(function(){
total += parseInt($(this).val());
});
});
total var will contain the total of all the select elements selected value.
If you want to retrieve the values in PHP, you can just use $_POST['acabados'] and it will contain all the values selected in each menu. See a demo. As long as you include the [] after the name, it will compound all the values for any element with that name into a single array. You can even mix select menus, inputs, and textareas together!
$(function () {
var $select = $('select');
$select.on('change', function () {
var output = 0;
for (var i = 0, len = $select.length; i < len; i++) {
output += parseInt($select.eq(i).val());
}
//the `output` variable now contains the addition of all the values from the `acabados[]` select elements
});
});
Here is a demo: http://jsfiddle.net/aPXXA/1/
You can change var $select = $('select'); to var $select = $('[name="acabados[]"]'); to only select the select elements with the acabados[] name attribute.
Why not just give them different id's and do the count in jquery/javascript. Alternatively give them all the same class, and do .each() to grab the values in all of them.

how to implement a dynamic combo box selection system

I'm implementing a system these days, i want to implement a combo box selection process but i don't know how to implement it, so asking you guys favor?
my scenario is this, let's say we have two combo box selection lists, left one and right one, left one is the main one and the right one is the child of the left one.
when i select a item from the left combo box the right combo box's content should be changed according to the selection of the left one,
Ex: let's think about mobile phones, if i select the brand
Nokia
from the left combo box right combo box's content should be changed to
C6-01
E7-00
5232
X3-02
C1-01
C7-00
5228
C5-03
5250
6120ci
E5-00
E73
like wise. please help me to implement a this kind of scenario!
any tutorial links, sample codes to understand the scenario is better!
regards,
Rangana
The trick is do subscribe to the change event and reset the contents of the second box accordingly.
HTML:
<select id="brand">
<option value="">- select -</option>
<option value="nokia">Nokia</option>
<option value="apple">Apple</option>
</select>
<select id="type"></select>
JavaScript (on ready):
var selectBrand = $("#brand");
var selectType = $("#type");
var optionsList = {
nokia: [
"C6-01",
"E7-00"
],
apple: [
"iPhone 3",
"iPhone 3G",
"iPhone 4"
]
};
selectBrand.change(function() {
var brand = selectBrand.val();
var options = optionsList[brand];
var html;
if (options) {
html = '<option value="">- select -</option>';
$.each(options, function(index, value) {
html += '<option value="' + value + '">' + value + '</option>';
});
} else {
html = '<option value="">Select a brand</option>';
}
selectType.html(html);
}).change();
Full example at See http://www.jsfiddle.net/TJJ8f/
This works by having two things. Firstly, a server that will return JSON for the category you need and, secondly, the code for the front end.
<?php
// Do what you need to
$modelsArray = getModelsForBrand($_REQUEST['brand']);
echo json_encode($modelsArray);
?>
This uses the json_encode function to get the JSON on the array returned by whatever you use to get the models. I haven't used this function myself but it looks pretty simple.
Then your jQuery would look like this:
$("#brandCombo").change(function(){
var chosenBrand = $(this).val(); // Get the value
$.getJSON('/your-php-file.php', { "brand" : chosenBrand }, function(request){
// Successful return from your PHP file
$("#modelCombo").empty();
// For each item returned, add it to your models combo box
$.each(request, function(i,item){
$("#modelCombo").append("<option value='" + item.value + "'>"+ item.name + "</option>");
});
});
});
In this example, brandCombo is the ID of the list with the brands and modelCombo is the ID of the list the models should appear. When the value of brandCombo is changed, it makes the request to your PHP file to get the array of models in JSON. Then it goes through each one and adds a new option to your modelCombo list.
A similar question I answered is here, where I mentioned how to do it with all the data already on the page and in listboxes (hiding/showing them) or by AJAX requests (as the example above).
The other option, as shown in dyve's answer is to have all the information you need on the page already, in the form of a JavaScript object. If you wanted to do this, then then PHP json_encode function could still be of use (although you just call it once with all your data and plop it onto the page).
A number of previous SO posts cover this topic, have a look at this for example: Using javascript and jquery, to populate related select boxes with array structure

Categories