jquery add table row with json data in dropdowns - php

I have a web form with a table that the user can add additional rows to. The first row of the table consists of dependent dropdowns. The dropdowns are populated with json data from a referenced file. The code that I am using for it is as follows:
//the add row function
$(function(){
var newgroup = $('<tr>').addClass('rec-rows');
$('#addRow').click(function(e){
e.preventDefault();
$('.rec-rows').first().clone().appendTo(newgroup).appendTo('#details'); });
});
//onChange function
$(".rec-rows #section").live('change',function(){
var sSec =$(this).parent().find('#section').val();
$("#divParts").hide();
$("#divDesc").hide();
$("#divGroup").hide();
if(sSec=="select") {
$("#divCategory").hide();
} else {
$.getJSON("static/site_category.json", function(json) {
var catJson = json[sSec];
var options = "<option value=\"select\">Select Area Type</option>";
for(i=0;i<catJson.length;i++) {
options +="<option value=\""+catJson[i].ky+"\">"+catJson[i].val+"</option>"
}
Theoretically, a new row is added and the onChange code I pasted will work for each additional row. However, the results are not like that at all. Instead, when the row is added and the user makes a selection on the new row, the values are updated in the first row.The first part of the table looks like this:
<td width="" align="left">
<div>
<select id="section" name="section" style="margin-top:15px;">
<option value="select">Select Area</option>
<option value="a">a</option>
<option value="b">b</option>
<option value="c">c</option>
</select>
</div>
</td>
I appreciate any help to get this code working as desired - which would be a simple added row where the dropdown selections only update on the row that they are found on. Thank you.

you can look at my answer here of how to add a row dynamically to the start of a table:
How can I dynamically generate a table row with it's tds?
It might help you here.
or i also i see a problem.
change $("#section").change(
to:
$("#section").live('change',...
that could be why the new dropdowns are not working

Got the solution! I was advised to declare the parent such as in the following context:
$(".section").change( function () {
var sSec =$(this).val();
context = $(this).parents("tr");
if(sSec=="select") {
$("#divCategory", context).hide();
} else {
$.getJSON("static/site_category.json", function(json) {
var catJson = json[sSec];
var options = "<option value=\"select\">Select Area Type</option>";
for(i=0;i<catJson.length;i++) {
options +="<option value=\""+catJson[i].ky+"\">"+catJson[i].val+"</option>"
Now for every "add row" click, a row gets added and the dropdowns are changed upon user selection for that row and only that row.

Related

PHP - Get unselected values of multi select

I'm working with a multi select for users to save what there favourite sites are.
Unfortunaly i can't post an image and the application is not working online. I'll try to explain how the multi select shows up:
LEFT BOX (with values that are not selected)
RIGHT BOX (with values that ARE selected)
Users can add values from the left to right box, this is working fine. But when they save, i can only get the new selected values. The values that have been selected earlier are not passed to the form processor. This way i also can't determine if a value is removed from the right column. I want all values from the left box to be posted also. Then i know which values can be "unselected" in the database.
When a value is selected from the left box, it will disappear from this box and appear in the right box.
This is what the form looks like:
<select multiple name="main_categories_1[]" class="multiselect" id="select1">
<option value="26">SAP</option>
<option value="29">SEO</option>
<option value="22">Servicemanager</option>
<option value="28">SharePoint</option>
<option value="34">Stages</option>
<option value="6">Systeembeheerder</option>
<option value="5">Tester</option>
<option value="31">UIDesigner</option>
<option value="35">Zend Dev</option>
</select>
So, to clarify. I DO get the newly selected values, i don't get the unselected values and values that already where selected. I want the unselected values also.
EDIT
Ok, solved it. Like ejrowley said, i need to select all "selected" values with javascript. Done it like this:
$(document).ready(function() {
$('#saveAccount').submit(function() {
$("#select2").find('option').attr('selected',true);
});
});
Even though you solved it... But, just for the sake of variety, you can try this code:
var selected = [];
var noselected = [];
$(document).on('click', '#button', function (){
$.each($('#select2 option'), function (key, value) {
if (!$(this).prop('selected')) {
noselected[key] = $(this).val();
//alert($(this).val());
} else {
selected[key] = $(this).val();
//alert($(this).val());
}
});
});
With this you get 2 arrays, 1 with the selected values and the other with the non-selected.
Here's an JsFiddle Demo.

Dual select box not POSTing correctly

I'm still trying to learn jquery so bear with me. I have a dual select box that only works if I select all the results of the second select box after I move them there. What I want is when the first box transfers values to the second second select box, it doesn't require highlighting the options, but posts that second select box on form submit. Here is what
I have:
HTML:
<span id="dualselect1" class="dualselect">
<select name="select1[]" multiple="multiple" size="10">
<?php
$c='0';
foreach($lp_name as $lpn){
echo '<option value="'.$lp_id[$c].'">'.$lpn.' ('.$lp_url[$c].')</option>';
$c++;
}
?>
</select>
<span class="ds_arrow">
<span class="arrow ds_prev">«</span>
<span class="arrow ds_next">»</span>
</span>
<select name="select2[]" multiple="multiple" size="10">
<option value=""></option>
</select>
</span>
JQUERY:
<script type="text/javascript">
jQuery(document).ready(function(){
var db = jQuery('#dualselect1').find('.ds_arrow .arrow'); //get arrows of dual select
var sel1 = jQuery('#dualselect1 select:first-child'); //get first select element
var sel2 = jQuery('#dualselect1 select:last-child'); //get second select element
sel2.empty(); //empty it first from dom.
db.click(function(){
var t = (jQuery(this).hasClass('ds_prev'))? 0 : 1; // 0 if arrow prev otherwise arrow next
if(t) {
sel1.find('option').each(function(){
if(jQuery(this).is(':selected')) {
jQuery(this).attr('selected',false);
var op = sel2.find('option:first-child');
sel2.append(jQuery(this));
}
});
} else {
sel2.find('option').each(function(){
if(jQuery(this).is(':selected')) {
jQuery(this).attr('selected',false);
sel1.append(jQuery(this));
}
});
}
});
});
PHP:
if(isset($_POST['submit'])) {
var_dump($_POST['select2']);
}
Like I said, I have this sort of working. But, if I send a value to select2, I have to highlight it before I submit or else it wont POST. Any ideas?
I've come across this before and you have a couple of options. Using JS you can either push all of the values in the second box into a hidden field as well, or also using JS you can select all of the values in the second box as an onsubmit handler on the form.
I've actually done the latter before, and it works just fine.
Ultimately, a select box (multi or single select) only sends the values that are selected -- so that's why it only works if you select them first. It works a lot like checkboxes do, where the unchecked values just don't get posted.
This should "select" all of them:
$('#myform').submit(function() {
var sel2 = $('#dualselect1 select:last-child');
sel2.find('option').each(function(){
$(this).attr('selected',true);
});
});
OR this would put them into a series of hidden fields:
$('#myform').submit(function() {
var sel2 = $('#dualselect1 select:last-child');
sel2.find('option').each(function(){
var hidden = $('<input type="hidden" name="selectedOptions[]"/>');
hidden.val($(this).val());
sel2.after(hidden);
});
});
and then in PHP you'd get these values by using $_POST['selectedOptions'];
You can simply modify this line jQuery(this).attr('selected',false); in sel1.find....block
with jQuery(this).attr('selected',true); .
In this mode al selection moved from first to second box is automatically selected,
so when you submit form, you directly pass this value.
Try it.
this should work:
if(t) {
sel1.find('option').each(function(){
if(jQuery(this).is(':selected')) {
jQuery(this).attr('selected',true);
var op = sel2.find('option:first-child');
sel2.append(jQuery(this));
}
});
}

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...

Changing contents of HTML select based on dropdown

I have a select item, that is filled with a list of files. This list of files is stored in a php variable.
I have another list of files, from another directory, stored in another variable.
I have a dropdown, with 2 options. When I change the dropdown, I want the items in the select to change to the file list associated with the item selected.
For example, my dropdown contains:
Misc Images
People
I have 2 variables, $misc and $people.
When Misc is selected, I want the select to contain all the images listed in $misc, and when the People option is selected I want the select to contain all the options listed in $people.
As far as looping through the php to generate all the items is fine, what I don't understand is how to do the javascript portion?
Thanks, and apologies for poor wording.
Try this code out.
PHP:
<?php
$miscArray = array("misc1", "misc2", "misc3");
$misc = implode(", ", $miscArray);
$peopleArray = array("people1", "people2", "people3");
$people = implode(", ", $peopleArray);
?>
HTML:
<form action="#">
<select id="fileCat">
<option id="misc">Misc</option>
<option id="miscData" style="display:none"><?php echo $misc ?></option>
<option id="people">People</option>
<option id="peopleData" style="display:none"><?php echo $people ?></option>
</select>
<select id="files"></select>
</form>
JS:
init();
function init()
{
addListeners();
}
function addListeners()
{
document.getElementById("fileCat").onchange = fillSelect;
}
function fillSelect()
{
var fileCat = document.getElementById("fileCat");
var imageFiles;
switch(fileCat.options[fileCat.selectedIndex].id)
{
case "misc":
imageFiles = document.getElementById("miscData").innerHTML.split(", ");
break;
case "people":
imageFiles = document.getElementById("peopleData").innerHTML.split(", ");
break;
}
var parent = document.getElementById("files");
parent.innerHTML = "";
if(imageFiles.length)
{
for(var i=0;i<imageFiles.length;i++)
{
var option = document.createElement("option");
//populate option with corresponding image text
option.innerHTML = imageFiles[i];
parent.appendChild(option);
}
}
}
I mocked up some data in PHP and then echoed it into a hidden <option> tag for each category. Then, the data is grabbed using a case/switch depending on the id of the selected option.
I think something like this would work. You would set the onchange attribute of your drop down box to call that function. You will need to have a URL that returns the options you want to use in JSON (selectMenus.php in that example). You'd need two different urls or one that takes a parameter to indicate which option set.
could You provide us some code? It is quite heavy to write it completely of nothing :)
UPDATE:
then how about You try the following (or similar) by using jQuery:
<select id="foo">
<option class="misc">MISC</option>
<option class="misc">MISC2</option>
<option class="people">People1</option>
</select>
<script type="text/javascript">
$(document).ready(function(){
$('option.misc').click(function(){
$('#foo').html('<option class="misc">MISC</option>
<option class="misc">MISC2</option>');
});
});
</script>
PHP is server side. JavaScript is client side. You have two options
(1) send an XmlHTTP request back to your server to pull the options and update the select list, or (2) send the values to a hidden field on the initial render of the page and get the values from there.

how to populate the second drop down using the selected value in first drop down?

Say I have two drop downs which are populated when the my jsp loads
<select id="Group" name="group"> -- first drop down
<option value="0001">1</option>
<option value="0002">2</option>
</select>
<select id="subGroup" name="class"> -- second drop down
<option value="0001-000">A</option> -- sub group associated with option value 001
<option value="0001-010">B</option>
<option value="0001-020">C</option>
<option value="0001-030">D</option>
<option value="0001-040">E/option>
<option value="0002-000">F</option> -- sub group associated with option value 002
<option value="0002-010">G</option>
<option value="0002-020">H</option>
<option value="0002-040">I</option>
</select>
Now I need to filter the second drop down based on the selected value in first drop down. I can't use the PHP code which uses the DB callback methods. in my script I have something like this.
$("#Group").change(function() {
var groupVal = $(this).find("option:selected").val();
$('#subGroup option').filter(function( {return!$(this).val().indexOf(groupVal)!=-1);}).remove();
});
the script is working fine, it removes all the options other then the one selected. but my problem is that next time when i select other value in first drop down, second drop down goes empty. I even worked with hide/show but guess they wont work with <select> :(
is there any way by which I can repopulate the second drop down when I selected some other option in first drop down?
If you are removing elements, you aren't getting them back. Use hide() and show() as you yourself suggested:
$("#Group").change(function() {
var groupVal = $(this).find("option:selected").val();
$('#subGroup option').hide();
$('#subGroup option[value^='+groupVal+']').show();
});
In other words, every time the #Group selectbox is changed, hide all options in #subGroup and show only the ones whose value attribute starts with groupVal.
Store all the options for the second select box into a array when the page loads. Then populate the select box from that array on change.
You are removing the second "batch" of options so they don't exists any more the next time you want to use them.
In order to do that you need to store all available options somewhere and then repopulate from that data set. for example
var availableOptions = {
'groupOne': {/* options as {value: '', text: ''} */},
'groupTwo': {/* options as {value: '', text: ''} */}
};
$("#Group").change(function() {
var groupVal = $(this).find("option:selected").val();
var sub = $('#Subgroup');
$.each(availableOptions[groupVal], function(i, data){
sub.append('<option value="'+data+'">'+data.text+'</option>');
});
There's also a related select box plugin by Remy sharp that I've had success with if you want to try:
http://remysharp.com/2007/09/18/auto-populate-multiple-select-boxes/

Categories