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));
}
});
}
Related
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) {
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'm using Select2 3.4.5 for create select boxes,
I use this code for creatre a Multi-Value Select Boxe and everything is fine.
<select id="e1" name="mydata" multiple>
<option value="D1">Data1</option>
<option value="D2">Data2</option>
<option value="D3">Data3</option>
</select>
...
<script>
$("#e1").select2();
</script>
For get multiple selected values of select box in php I have to modify name="mydata" by name="mydata[]", and in PHP I get values by this code:
<?php
foreach ($_POST['mydata'] as $names) {
print "You are selected $names<br/>";
}
?>
But my question: How can I send selected values of select box to PHP as string to recover in php like this : 'D1,D2,D3' , and thanks.
Edit:
I want to send the data as string, not receive it as an array then
change it as string
Server-side with PHP
Ideally you would do this with PHP once the value is sent. To convert the selected items just want to implode the array
$names=implode(',', $_POST['mydata']);
Where $_POST['mydata'] is an array
[0]=>'D1',
[1]=>'D2',
[2]=>'D3'
implode(',', $_POST['mydata']) would be 'D1,D2,D3'
Client-side with jQuery
Your title says "send selected values of select box to PHP as string". You would do that in JS by catching the submit event of the form and using .join() to change the value of that field.
$('#formid').on('submit', function(){
$('#e1').val($('#e1').val().join(','));
});
Your form (not given) would need an id <form id="formid" ...>
If you want a client-side solution, try getting the val() and calling join():
$('#e1').val().join()
http://jsfiddle.net/gwgLV/
You can do it with javascript.
<select id="e1" name="mydata" multiple>
<option value="D1">Data1</option>
<option value="D2">Data2</option>
<option value="D3">Data3</option>
</select>
<button id="but" onclick="now()">Show selected values</button>
javascript code
function getSelectValues(select) {
var result = [];
var options = select && select.options;
var opt;
for (var i=0, iLen=options.length; i<iLen; i++) {
opt = options[i];
if (opt.selected) {
result.push(opt.value || opt.text);
}
}
return result;
}
function now(){
var el = document.getElementsByTagName('select')[0];
var x = getSelectValues(el);
alert(x);
}
Demo here
Instead of alert store in a variable and send it along with the rest of the form data. Or you can use join (as mentioned in other answers ) to send it over post to php.
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 hava made a select box of skills..there are skills listed in it.. if we select it once it will be added out side in a DIV..n the first thing what i want is it can't be select again in the select box if once it's there in DIV...n there's a 'x' there in div..if it's clicked..that div will b deleted...
now my point is. the second thing what i wnt is when the value of DIV is deleted by clicking on 'X'...the same value of it in the select box will b live again(we can select it(enabled))...
This is the javascript i used in this tuts..
<script type="text/javascript">
var i=0;
function generateTextbox(){
if(i<5){
var d=document.getElementById("div");
var skilldiv=document.getElementById("skill").value;
d.innerHTML+="<div>"+skilldiv+"<a class='close_notification' onclick='this.parentNode.parentNode.removeChild(this.parentNode); '>X</a></div>";
i=i+1;
}
}
</script>
select box values come dynamically..
<select id="skill" name="skill" multiple="multiple" style="float:left; height:160px; width:375px;" onchange="generateTextbox();">
<?php foreach ( $fivesdrafts as $fivesdraft )
{
$fivesdraft->skill_name;
$fivesdraft->skill_id;
?>
<option value="<?php echo $fivesdraft->skill_name; ?>" onclick="this.disabled='disabled';" > <?php echo $fivesdraft->skill_name; ?></option>
<?php } ?>
</select>
}
</script>
<?php } ?>
And this is the div where my select box values come after click on them...
<div id="div"></div>
Do you want something like this: http://aloksah.org/listbox/listbox.html
jQuery Code:
// function: UnAssignment
function assignList()
{
// loop through first listbox and append to second listbox
$('#firstList :selected').each(function(i, selected){
// append to second list box
$('#secondList').append('<option value="'+selected.value+'">'+ selected.text+'</option>');
// remove from first list box
$("#firstList option[value='"+ selected.value +"']").remove();
});
}
// function: UnAssignment
function unassignList()
{
// loop through second listbox and append to first listbox
$('#secondList :selected').each(function(i, selected){
// append to first list box
$('#firstList').append('<option value="'+selected.value+'">'+ selected.text+'</option>');
// remove from second list box
$("#secondList option[value='"+ selected.value +"']").remove();
});
}