Selecting Values in PHP From Double Drop-Down Menu - php

I am creating a drop-down menu in which the second drop-down is dependent upon the first; the first drop down is a list of table, and depending on what table you select, the columns of that table will be able to be selected.
<form id = "table_column" action = "file_name.php">
<select id = "tables" name = "tables" onclick = "script();">
<option name = "table_option_one" value = "people">people</option>
<option>...</option>
</select>
<select id = "columns" name = "columns" onclick = "other_script();">
<option name = "column_option_one" value = "name">name</option>
<option>...</option>
</select>
<input type = "submit"></input>
</form>
I have tried the code below to no success.
$table_name = $_POST["tables"];
$column_name = $_POST["columns"];
How do I access the values selected in each drop-down menu in PHP?
I am only having a problem with the retrieval of the selected values. The menus depending on another and switching work fine

Okay, with your new clarification (you are populating the drop-downs fine), here is what you can do.
Give the input tag an ID as such:
<input type="submit" name="submit" id="submit" value="Submit"> <!--form submit button-->
and in your PHP do a conditional as such:
if (isset($_POST['submit'])) {
$table_name = $_POST["tables"];
$column_name = $_POST["columns"];
}
make sure your form also has the method="post" attribute as well:
<form id = "table_column" action="file_name.php" method="post">
That way when the submit button is hit, your values will be retrieved.

Use AJAX to get the data for the second menu by passing the value of the first menu to a PHP script.
Use the AJAX success function to populate the second menu.
On submission of the form, use PHP to get the values as normal, i.e. $_POST['tables'] and $_POST['columns']

This is more a job for Javascript than PHP. The simplest solution (not involving AJAX) would be to code all possible second dropdown lists, make them invisible (using CSS), then make the appropriate one appear upon a change in the first dropdown.

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);
}
?>

Sequential Order of Checkboxes Selected PHP

At the moment, my html code is:
<form id = "query" method = "post" action = "search.php">
<input type = "checkbox" name = "col_list[]" value = "host">host</input>
<input type = "checkbox" name = "col_list[]" value = "atom_name>atom_name</input>
…
<input type = "submit">Submit</input>
</form>
And my php code:
$columns = $_POST["col_list"];
Is there any way is which I can get the sequence in which the checkboxes where checked?
you'd need to add a some javascript to get that info.
<input type="hidden" name="order"/> <!-- goes inside the form -->
Here is an examply using jQuery:
$('[name*="col_list"]').change(function(){
if ($(this).prop('checked')){
$('[name="order"]').val($('[name="order"]').val()+','+$(this).val())
}
});
This should work fairly well with one caveat:
If the user un-checks then re-ckecks a checkbox it will be added to order twice.
order should result in something like:
,host,atom_name
Edit
Fixed some typos and here is a fiddle
If the order is important you will have to implement some form of JavaScript or AJAX and call it when the check boxes are checked. Forms do not track the order in which fields are filled. JavaScript is well suited to this because it can trigger at the time of the click.
An alternative to AJAX could be adding a hidden field element and using JS to store the order clicked. Then it would be passed when the form is clicked.

Dynamically Added Rows by jquery having issues

I have a form containing a select field id="projects" which upon being changed shows(using js) a hidden select field 'task' dynamically populating the tasks for the selected project by querying the dB. User can then enter hours which are updated on proj_id,task_id combination from the selects.
echo '<div id="dynform"><div class="rowhours"><select id="projects" name="project">';
if(mysqli_num_rows($res)==0)
echo '<option>No Projects assigned</option>';
else{
echo '<option value="0">Project - Choose one</option>';
while (list($proj_id, $title) = mysqli_fetch_row($res))
{
echo "<option value=$proj_id>$title</option>";
}
}
echo '</select></div><input type="button" id="add"></div>';
<select name="task" class="tasks" onchange="showOther(this, 'new');" onmouseover="showOther(this, 'new');"></select><br>
function showOther(fieldObj, otherFieldID) //Function displays text box for creating a new task on Addhours.php
{ //for the selected project when "Enter New Task" option chosen
var fieldValue = fieldObj.options[fieldObj.selectedIndex].value;
var otherFieldObj = document.getElementById(otherFieldID);
otherFieldObj.style.visibility = (fieldValue=='other') ? '' : 'hidden';
return;
}
Now I added an 'Add Row' button, this generates the same form many times.
<input type="button" value="Add Row" id="add">
jquery used to add rows: $(document).ready(function () {
$('#add').click(function () {
$('.rowhours').clone().appendTo('#dynform');
});
});
Now when I change the projects of any row, the tasks select fields of all rows get affected, I know this is because they have the same Id's.
Question is how can I make them have different Id's and be able to use them seperately in the same manner using jquery. Also as of now I just update using the if(isset($_POST['submit'])) What can I use for the multiple rows now?
I have a working example here http://fracktal.in/tms/addhours.php
I am basically looking for having a project[] and task[] that I have no clue how to access using jquery or to get the posted values on form submit to update dB
Once you add rowhours access the last element and change the id
$(".rowhours).last().attr("id","newId");
you can use arrays easily, just name your fields project[] (not project) and then access them with $_POST['project'][0], $_POST['project'][1], etc.
$total = count($_POST['project']);
foreach($_POST['project'] as $num=>$project) {
// do your code here, send to DB or whatever
// $project contains value of input (or select) and $num contains number of row
}

jQuery: second dropdown from array based on value of first dropdown

Question: I have two drop-down boxes. Using jQuery, I want to populate second drop-down box on selection of the first drop-down box (help with my existing code). I have marked the area I need help with in the jQuery code below, plus an explanation of what I want to achieve in "Code help".
I realise this is a VERY frequently requested item on SO and I have seen many comments that this can be done in simple JS, but since there are already other jQuery elements in use on the page (not coded by me) and for simplicity, I want to use JQ.
I am completely new to any jQuery code, I have researched many examples, however I am getting lost in the logic since I am not familiar with JS or JQ coding conventions, so keeping things simple is important so I can understand what is happening within the code (I am not just looking for help to get my code working, but also so I can learn and understand what is happening).
I found pretty much exactly the operation I want to achieve (except for one important point explained in "Code help" below) by following a tutorial here: http://jqueryfordesigners.com/populate-select-boxes/. A sample page showing the operation is here: http://jqueryfordesigners.com/demo/select-boxes.html
Code help: In the tutorial, the second dropdown is populated from the content of static html files in: $article.load('select-boxes-' + categoryName + '.html');
I need the second dropdown to be populated from the JS variable $st_list and the PHP variable $student_block based on the selected value in the first dropdown, as shown in my code below.
Could anyone please help with how to adapt the code to make that happen?
Thank you
My code:
For simplicity, the first dropdown is static with simple integer values, but will be populated from the DB in $test_seq in the working code with integer values same as the example code below (if that matters). Additionally, in a separate PHP process (later) the $test_seq, $student_id and other new variables will be used to send back data to the DB (included for reference only, though not relevant for this request).
select-boxes.php
$sql = "SELECT * FROM TBL_NAME";
$result = mysql_query($sql) or die(mysql_error());
while($row = mysql_fetch_array( $result ))
{
$test_seq = $row['SEQ'];
$student_id = $row['st_num'];
$student_name = $row['st_name'];
$student_block .= '<OPTION value="'.$student_id.'">'.$student_id.' - '.$student_name.'</OPTION>';
}
Form:
<form action="select-boxes.php">
<label for="test_day">Test day:</label>
<select name="test_day" id="test_day">
<option selected value=""> </option>
<option value="1">Day 1</option>
<option value="2">Day 2</option>
<option value="3">Day 3</option>
</select>
<input type="submit" id="next" value="next »" />
</form>
jQuery:
<script src="http://code.jquery.com/jquery-1.7.2.min.js"></script>
<script>
$(document).ready(function () {
var $test_day = $('#test_day'),
$st_list = null;
$test_day.change(function () {
var test_dayVal = $test_day.val();
if ($st_list == null) {
$st_list = $('<select name="st_name" id="st_name"><?php echo $student_block; ?></select>').appendTo('form');
$next.remove();
$('form').append('<input type="submit" value="process »" />');
}
$st_list.load('#test_dayVal'); //<--I think this is where I need help.. What do I do here?
});
var $next = $('#next');
$next[0].setAttribute('type', 'button');
});
</script>

Updating a registration form without refreshing a page

I'm designing a registration form in PHP using html. The form collects personal info from users some fields include the marital status, name of spouse, and the number of children. How can I code it such that whenever a user selects "Single" for his/her marital status, the textboxes for the name of spouse and number of children will be automatically disabled? All of this must be done without refreshing the page. Thanks!
Assuming you are using drop down for marital status, use the onchange event to capture the change in the drop down status
function maritalStatusChange()
{
var dropdown = document.getElementById("maritalstatus").value;
if(dropdown == 'Single')
{
document.getElementById("spousefld").readOnly = "readonly";
}
}
You can use JS for your purpose.
Try this code : (Assuming "single" is your radio button)
if (document.geElementById('maritalStatus').checked){
//disable resp textboxes
document.geElementById('spouce').disabled = true;
document.geElementById('children').disabled = true;
}
for more details see this
you can achieve this using the javascript function.
if you have used combobox for marrital status
<select id="a" onchange="if( this.options[this.selectedIndex].value=='s')
{document.getElementById('spouce').readOnly = true;}
">
<option value='s'>single</option>
<option value='m'>married</option>
</select>
<input type='text' id='spouce'/>
see the jsfiddle

Categories