I have multiple dependent drop down which get from my database.
The first drop down will select eOpp and the second drop down will be based on selected eOpp from first drop down.
//First Drop down
<label>Select eOpp</label>
<?php erfq_generateOppDropdown($oppID,"erfq_rfq_oppID");?>
//Second Drop down
<label>Select Item</label>
<select id="item" name="item[]" multiple="multiple">
</select>
Here is my ajax to get value from first drop down.
function getItem(val) {
$.ajax({
type: "POST",
url: "get_item.php",
data:'erfq_rfq_oppID='+val,
success: function(data){
$("#item").empty().html(data);
$("#item").multipleSelect("refresh");
}
});
}
It works fine to generate both drop down. But when the first drop down (Select eOpp) has changed, the second drop down still will remain the previous value in my drop down. I use this multiSelect for my second drop down under the basics1. jquery.multiple.select.js
For example when I selected the first eOpp, the result will be like this:
Select eOpp: 1
Select Item:
Item 1(A)
Item 1(B)
But after I changed the Select eOpp, it will become like this:
Select eOpp: 2
Select Item:
Item 1(A)
Item 1(B)
Item 2(A)
It will retain the previous value where eOpp=1 but when I use php to $_POST it, I get no value. I have to remove the previous record accordingly when I change my Select eOpp
EDIT
The problem occurs when the multiSelect is implemented.
$(function() {
$('#item').change(function() {
console.log($(this).val());
}).multipleSelect({
width: '100%'
});
});
Destroying and reinitalizing should work:
$("#item").multiselect('destroy');
$("#item").multiselect();
After I have changed the multiSelect plugin, it works well with my code.
For more information, please see JSFiddle. A few changes of the function are
1) function MultipleSelect($el, options)
2) MultipleSelect.prototype = {
constructor : MultipleSelect,
init: function() {
var that = this,
html = [];
if (this.options.filter) {
html.push(
'<div class="item-search">',
'<input type="text" autocomplete="off" autocorrect="off" autocapitilize="off" spellcheck="false">',
'</div>'
);
}
3) optionToHtml: function (i, elm, group, groupDisabled) {
Related
I have 2 selectboxes
<h3>Results</h3>
<select id="register_form" name="sport" />
<option value="Rugby">Rugby</option>
<option value="Cricket">Cricket</option>
<option value="Football">Football</option>
</select>
<?php
echo'<select name="match">';
echo'<option value="'.$row['event_id'].'">'.$row['team1'].' VS '.$row['team2'].'</option>';
echo'</select>';
?>
<input id="register_form" type="submit" value="Display" name="submit" />
User searches for a result by:
selecting sport type in 1st selectbox and then in 2nd selectbox option values are populated based on sport type.
Is it possible to do this in PHP without the user having to first press submit to get the $_POST value of sport type?
What is my best option here?
PHP always need to reload the page to refresh your informations, so, as anant kumar singh said, you need to use AJAX for that. And as yak613 said, jQuery will help you to use AJAX easily
1.Ajax is the only option what you asked for that(without page refresh)
When you use php it's only possible with page refresh. but with ajax without page refresh it's possible.
helping links are:-
Use jQuery to change a second select list based on the first select list option
https://www.daniweb.com/web-development/php/threads/372228/php-and-ajax-auto-populate-select-box
https://remysharp.com/2007/01/20/auto-populating-select-boxes-using-jquery-ajax
You can use this Multiple Select Dropdawn lists: http://coursesweb.net/ajax/multiple-select-dropdown-list-ajax_t , it can be used for multiple sets of Select lists.
I've faced with the same problem in my project. But the needed functionality was higher - not two dependent selectboxes and bigger number. I've written a simple function to load my selectboxes:
//formId - form where selectbox is
//name - attribute "name" of selectbox
//dataSourceUrl - url to PHP-file
//affectingField - string with value that filters the selecbox's data
function loadSelectbox( formId, name, dataSourceUrl, affectingField ){
//console.log('Loading data to selectbox name="'+name+'":');
var selectbox = $('#'+formId+' select[name="'+name+'"]');
if(selectbox){
//console.log("Selecbox found");
if(affectingField != null){
var affectingValue = $('#'+formId+' [name="'+affectingField+'"]').val();
dataSourceUrl += '?affectingValue='+affectingValue;
}
var options = selectbox.find('option');
var jqxhr = $.ajax({
url: dataSourceUrl,
dataType: 'text'
})
.done(function(data) {
//console.log(data);
if(data != ""){
var optionsObject = JSON.parse(data);
var i = 0;
console.log(optionsObject);
var options = [];
$(optionsObject).each(
function(){
options[i] = '<option value="'+$(this)[0]['val']+'">'+$(this)[0]['text']+'</option>';
i++;
}
);
selectbox.html(options);
if(urlParamsSet[name] == false){
setParamFromUrl(name);
}
}
else{
selectbox.html('<option value="">Все</option>');
}
})
.fail(function() {
alert("Problems with server answer");
})
selectbox.prop("disabled", false);
}
else{
console.log("No selectbox with such name");
}
}
Not saying that this code is perfect, but it works. PHP-file must return the values to selecbox in JSON format (convert from with structure: array(index, value, text) ).
I found a jquery snippet to add and remove options from a select box from box 1 to box 2. This works great. However, when i try to print_r in PHP of the box where the new options are added then it won't show. I cant even see it on the resource after submit. Any solution?
$('#btn-add').click(function(){
$('#select-from option:selected').each( function() {
$('#select-to').append("<option value='"+$(this).val()+"'>"+$(this).text()+"</option>");
$(this).remove();
});
});
$('#btn-remove').click(function(){
$('#select-to option:selected').each( function() {
$('#select-from').append("<option value='"+$(this).val()+"'>"+$(this).text()+"</option>");
$(this).remove();
});
});
});
and html of the two select lists
<select class="gen" name="selectfrom" id="select-from" multiple size="6" style="width: 150px;">
</select>
<input name="" id="btn-add" type="button" class="add_list" style="vertical-align: top;">
<input name="" id="btn-remove" type="button" class="remove_list" style="vertical-align: top;">
<select class="gen" name="selectto" id="select-to" multiple size="6" style="width: 150px;">
</select>
upon submit i check the $_POST['selectto'] from the selectto box. Any idea's?
EDIT: the foreach in php;
$articles_ary = array();
foreach ($_POST['selectto[]'] as $options)
{
if (!empty($options))
{
$articles_ary[] = $options;
}
}
print_r($articles_ary);
when you POST a select the form submits only the selected option and bare in mind that it must be selected.
with your code you are just adding the options to the selectto, but you're not:
a) chosing one of them (if you want a single value posted)
b) chosing all of them to be posted on the PHP page. (if you want multiple values posted)
in the second case (i thought it's the one you need) you can use this simple jQuery function:
$("#buttonusedtosendform").click(function(e){
e.preventDefault();
$('#select-to option').each( function() {
$(this).attr('selected', true); //with this you select all the option
});
$('formname').submit();
});
bare in mind that if you want to retrieve all the options of a select with PHP you will have to use a little trick by naming the select with square bracket at the end (it's a feature that PHP offer, where it will overwrite the former variable with the latest parsing each one separately):
eg. selectto => selectto[]
this way php will handle it as an array and let you retrieve all the value as if it is one:
foreach($_POST['selectto[]'] as $options){}
When you enter data from one select box to second selectbox, you need to have items selected in second select box to show when you do print_r in php.
For this, after items are added to second select box say with id selectbox2, then you could select all items of second selectbox and then submit the form
for (var i = 0; i < selectbox2.options.length; i++) {
selectbox2.options[i].selected = true;
}
//then Submit form like this, assuming your form name is form1
document.form1.submit();
Hope this helps
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));
}
});
}
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.
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/