So I am trying to output a dynamically populated dropdown through jquery. The problem is that it just works for one iteration. The script -
<script> $(function()
{
$("#projects").change(function() {
$("#tasks").load("getdata.php?choice=" + $("#projects").val());
});
}); //getdata.php queries data and echoes <option>
//#projects -> <select> id and #tasks->options id
</script>
I know it has something to do with introducing each there, but I cannot seem to get it to work.
This is the div where that is being looped -
foreach($days as $key=>$day) //inside <select id="projects">
{
echo '<td align="center" width="65">
<div>'.$day.'<br><input name="hours" type="text" size="2" placeholder="hours">
<select id="tasks">
<option>Select a Project First</option>
</select>
</div>
</td>';
}
Return from php file will change content of #task
$(document).ready(function(){
$('.#projects').change(function(){
var getdata = 'getdata.php?choice='+$("#projects").val();
alert(getdata);
$('#tasks').load(getdata);
});
})
You need to use .on() for the elements which will come dynamically.
$(document).on('change','#projects',function(){
//code here
});
you need to refresh the dropdown list after you dynamicaaly appen val
//refresh value
$('select').selectmenu('refresh');
//refresh and force rebuild
$('select').selectmenu('refresh', true);
So I figured this one out with a friends help.
Firstly, a very fundamental mistake of mine -
Since <select id="tasks"> field is being looped over for display it is more viable to change id to class.
After that its just comes to changing the #tasks to .tasks and the jscript does the work.
Otherwise each() can also be used to achieve the result like this -
$(".tasks").each(function()
{
$(this).(load)("getdata.php?choice=" + $("#projects").val());
});
Related
I'm trying to create a select box that refreshes its options when selected by the user, but I'm encountering a problem that I can't figure ho to solve.
Being still a beginner with jquery I've already asked an advice for the same program: Keeping selected an option in select dropdown with jquery after refresh.
Following the suggestion now it works almost completely, but I'd like the dropdown to behave exactly as a non dynamic one, keeping the selected option when opened, except for having the options list also refreshed: now it “almost” keeps the value selected (it retains it in the dropdown) but resets to the first option when the element lose focus to others in the page and I don't know how to resolve the problem. I tried to pass a variable with ajax to the php page to have it selected on refresh, but it still resets when focus is change.
The JS code:
$(document).ready(function() {
$("#UsersDiv").focusin(function() {
var UsersSelect = $('#UsersList').val();
$.get(
"userlist.php",
{ UserSelect1: UsersSelect },
function(data) {
$('#UsersList').html(data);
}
);
})
$('#UsersList').val(UsersSelect);
});
The html page:
<div name="UsersDiv" id="UsersDiv">
<select name="UsersList" id="UsersList">
<option value="User1">User1</option>
<option value="User2">User2</option>
</select>
</div>
The php file (the “users” array is in place of the sql query, both work properly):
$UserSelect1 = $_GET['UserSelect1'];
$users=array( 'User1','User2','User3','User4','User5');
echo '<select name="UsersList" id="UsersList">';
foreach($users as $list):
echo '<option value="'.$list.'" ';
if ($UserSelect1 == $list) {
echo 'selected=selected';
}
echo '>'.$list.'</option>';
endforeach;
echo '</select>';
Thanks to everyone for the answers.
$("#UsersDiv")
than you assigning this
$select=$(this) // $select is $("#UsersDiv");
and than you are trying to get val from div
UsersSelect = $select.val() // $select.val() is undefined
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 drop down list (ddlAccount) which i can choose an item from it and do a db query in test.php to retrieve corresponding data, then output an input element with the returned data.
This is my javascript code:
function load1(){
$('#divAccountNum').load('test.php?accountInfo=' + document.getElementById('ddlAccount').value , '' ,function() {
alert('Load was performed.')});
}
load1 function called when i change the dropdown list items, and it takes the value of the selected option and sends it to test.php in a parameter called "accountInfo".
my html:
<select name="ddlAccount" id="ddlAccount" onchange="load1();">
<option value="1"> Account1</option>
<option value="2"> Account2</option>
<option value="3"> Account3</option>
</select>
<div id="divAccountNum" >
</div>
And test.php :
if($_GET['accountInfo'])
{
$account = $accountDAO->load($_GET['accountInfo']); //mysql query
//print an input holding account number as its value
echo "<input type='text' name='txtAccountNum' id='txtAccountNum' value='".$account->accountnumber."'/>";
}
The problem is that nothing happened when i choose an option (nothing appear in div (divAccountNum))
Any suggestions? Thanks in advance.
Edit:
I used #thecodeparadox 's bit of code and it works and i found a solution for the problem that i mentioned in the comments below which is that when choosing one item from the dropdown list it shows the value in input element and loads the form again. The solution is in:
jQuery Ajax returns the whole page
So my jquery code now looks like:
$(document).ready(function(){
$('#ddlAccount').on('change', function() {
$.get('testJquery.php?accountInfo=' + $(this).val(), function(accountNum) {
//console.log(accountNum);
$('input#txtAccountNum').val(accountNum);
});
});
And testJquery.php :
if($_GET['accountInfo'])
{
$account = $accountDAO->load($_GET['accountInfo']);
$accountNum = $account->accountnumber;
echo $accountNum;
}
And at last i added input element in divAccountNum which has id="txtAccountNum"
Though you don't give enough info about your problem, but you can try this:
function load1(){
$('#ddlAccount').on('change', function() {
$.get('test.php?accountInfo=' + $(this).val(), function(response) {
$('div#divAccountNum').html(response);
}, 'html');
});
}
NOTE:
$('#ddlAccount').on('change', fires when dropdown change
$.get('test.php?accountInfo=' + $(this).val().. send a get(ajax) request to test.php with value selected from drop down
parameter response with in $.get() second parameter callback function is the response from the server
'html' as third parameter of $.get() for data type you return, as you return a html so it is html.
for more info read:
change()
$.get()
To get selected option value from select input use:
$('#ddlAccount option:selected').val()
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.