i need some clarification on how to populate select(s) with data from mysql. Basically what I am trying to do is:
There will be a first select box with some data in it.
<select>
<option>1</option>
<option>2</option>
<option>3</option>
</select>
when the user selects a option in the first select,
there is a second select below that, which should reflect the values according to the selection made in the first select.
<select>
<option>1.1</option>
<option>1.2</option>
<option>1.3</option>
</select>
The data is commin from MySQL. I am not sure if need to post to same page, but if I do, how to retain the values alredy selected in the previous select boxes? do i need to use javascript?
any help?
Thanks.
You should use javascript so you don't need a page refresh. I just re-read your question and I'll have a solution involving an AJAX request in a second to pull dynamic data:
HTML
<select name="select1" id="select1">
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
</select>
<select name="select2" id="select2">
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
</select>
jQuery
<script type="text/javascript">
$(document).ready(function() {
$('#select1').change(getDropdownOptions);
});
function getDropdownOptions() {
var val = $(this).val();
// fire a POST request to populate.php
$.post('populate.php', { value : val }, populateDropdown, 'html');
}
function populateDropdown(data) {
if (data != 'error') {
$('#select2').html(data);
}
}
</script>
populate.php
<?php
if (!empty($_POST['value'])) {
// query for options based on value
$sql = 'SELECT * FROM table WHERE value = ' . mysql_real_escape_string($_POST['value']);
// iterate over your results and create HTML output here
....
// return HTML option output
$html = '<option value="1">1</option>';
$html .= '<option value="b">B</option';
die($html);
}
die('error');
?>
Related
I've to select boxes:
<select name="select1" id="select1" multiple="multiple">
<option value="8">Civics</option>
<option value="9">English</option>
<option value="10">Economics</option>
</select>
<select id="select2" size="4" multiple="multiple" name="select2[]">
<option value="1">Maths</option>
<option value="2">Physics</option>
<option value="3">Chemistry</option>
<option value="4">Biology</option>
<option value="5">History</option>
<option value="7">Social Studies</option>
<option value="11">Geography</option>
</select>
The data for both the boxes is fetched from the db on page load.
The idea is to either add/delete options from the select2 and save it to a table in the db. I delete the existing data in the table before updating it.
The issue I'm facing is while saving the data, only the new options which are added to the select2 are getting saved and if I remove any options, I'm getting an index out of bounds error. How do I make sure that the values which are already there in the select2 on page load are read as well?
The php code is as follows:
<?php
if(isset($_POST['save']))
{
$qry = 'delete * from table_sel2';
$exec = mysqli_query($conn,$qry);
foreach ($_POST['select2'] as $sel_val)
{
echo $sel_val;
$sql = "insert into table_sel2 (select2,status_id) values (".$sel_val.",1)";
$result = mysqli_query($conn,$sql);
}
$message = "Done!";
}
?>
Jquery code to move data between the selectboxes:
$('#add').click(
function(e)
{
$('#select1 > option:selected').appendTo('#select2');
});
$('#remove').click(
function(e)
{
$('#select2 > option:selected').appendTo('#select1');
});
Select all options from select2 upon form submission like this -
submit_bttn.click(function () {
$('#select2 option').each(function () {
$(this).attr('selected', true);
});
});
I have drop down boxes related to each other. The second dropdown values are filtered according to first dropdown box value.
Now I want to clone elements in div with class="old_div" into div with class="new_div" and add events to each new elements in div with class="new_div".
ADD
<div class="old_div" >
<select name="select1" id="select1">
<option value="1">Fruit</option>
<option value="2">Animal</option>
<option value="3">Bird</option>
<option value="4">Car</option>
</select>
<select name="select2" id="select2">
<option value="1">Banana</option>
<option value="1">Apple</option>
<option value="1">Orange</option>
<option value="2">Wolf</option>
<option value="2">Fox</option>
<option value="2">Bear</option>
<option value="3">Eagle</option>
<option value="3">Hawk</option>
<option value="4">BWM</option>
</select>
<br />
</div>
<div class="new_div">
</div>
I am able to clone elements to new div using Jquery
Jquery code:
$("#add_a").on('click',function(){
var data = $('.old_div').html();
$('.new_div').append(data);
});
$("#select1").on('change', function() {
if($(this).data('options') == undefined){
$(this).data('options',$('#select2 option').clone());
}
var id = $(this).val().trim();
var options = $(this).data('options').filter('[value=' + id + ']');
$('#select2').html(options);
});
But how can i make new elements to be related to each other.
I have created fiddle http://jsfiddle.net/6YEQx/ for reference.
You are using id with select box and making duplicates of it, this is causing problem to identify select box using id in jQuery. So use class instead of id.
HTML :
<select name="select1" class="select1">
<option value="1">Fruit</option>
<option value="2">Animal</option>
<option value="3">Bird</option>
<option value="4">Car</option>
</select>
<select name="select2" class="select2">
<option value="1">Banana</option>
<option value="1">Apple</option>
<option value="1">Orange</option>
<option value="2">Wolf</option>
<option value="2">Fox</option>
<option value="2">Bear</option>
<option value="3">Eagle</option>
<option value="3">Hawk</option>
<option value="4">BWM</option>
</select>
Also you are adding elements dynamically so need to bind change event using $(document) and on.
EDIT: also added new line in add_a button script to show all options in second select box initially.
jQuery :
$("#add_a").on('click',function(){
var data = $('.old_div').html();
$('.new_div').append(data);
// to show all options initially and remove any preselected option
$('.new_div').find('.select2:last option').show().removeAttr('selected');
});
$(document).on('change',".select1", function() {
var id = $(this).val().trim();
$(this).next('.select2').find('option').hide();
var $options = $(this).next('.select2').find('option[value=' + id + ']');
$options.show();
$options.first().attr('selected',true)
});
Demo
I have a form where I need to select multiple items from a single dropdown and use them in a query.
I have used the tag for the dropdown and used the 'multiple' attribute to allow multiple selection.
I want to get all the selected items/indexes in a variable/array so that I can use it in tha query.
I tried using document.getElementById('statusselect').selectedindex but I get only 1 and not all.
I even tried using $('#statusselect option:selected') in jquery but in vain.
Please help me out with this!!
Thank You.
This the code for the dropdown where the values are fetched from database.
I want to get all the selected values in a variable on a button click.
echo "<td>Status<br>";
echo "<select multiple name=\"status\" size=5 id=\"statusselect\">";
foreach($status_all as $status)
{
if (isset($_GET['status']) && $_GET['status'] == $status)
{
echo "<option value=\"$status\" selected>".status_in_words($status)."</option>";
}
else
{
echo "<option value=\"$status\" >".status_in_words($status)."</option>";
}
}
echo "</select>";
echo "</td>";
jQuery :selected on multiple select must use each to iterate through all the elements. As http://api.jquery.com/selected-selector/ suggested, use this:
<select name="garden" multiple="multiple">
<option>Flowers</option>
<option selected="selected">Shrubs</option>
<option>Trees</option>
<option selected="selected">Bushes</option>
<option>Grass</option>
<option>Dirt</option>
</select>
<script>
$("select option:selected").each(function () {
// your code
});
</script>
Here is a sample HTML:
<select id="multiselect" name="multiselect[]" multiple="multiple" size="5">
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
<option value="4">4</option>
<option value="5">5</option>
</select>
Using jQuery:
$("#multiselect").val()
Yields an array with selected values
My code reads 2 data from the database, and if those data are specific value, then it should remove values 2,3,4,5,6,7,8 from the select called smjer. Values from database are read in external .php script, and then sent back to web page using GET. My problem is next: In one specific case, when the second select in code is set to 3, then code should remove only 2nd and 3rd value from select smjer. I've done this with jQuery,and it works ,but my problem is that when i change value of other select, for example, from 2, I select value 3, nothing happens, so I have to refresh the page, so my changes would apply.
Selects look like this:
<select name="smjer" class="smjer">
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
<option value="4">4</option>
<option value="5">5</option>
<option value="6">6</option>
<option value="7">7</option>
<option value="8">8</option>
</select>
Second select:
<select name="godina" class="upis">
<option value="1" >1.</option>
<option value="2" >2.</option>
<option value="3">3.</option>
</select>
And the code for removal:
<?php }
if(($_GET['program1'])=='1'&&($_GET['stupanj_spreme1']=='2'))
{?>
<script>
$(document).ready(function(e) {
var ary=[2,3,4,5,6,7,8];
var provjera=$('.upis').val();
if(provjera=='3')
{
var ary=[2,3];
}
$('[name=smjer] option').filter(function(){
return ($.inArray(parseInt(this.value),ary) >-1);
}).remove();
});
</script>
<?php } ?>
I have been reading on net that something like this should be done with AJAX, but I don't know anything about AJAX, an I would like to avoid it. Tnx in advance.
Instead of running your javascript once onready, bind it to the change event of the select in question:
$(document).ready(function(e) {
// When the value of the select changes, run this:
$('.upis').change(function(){
var ary=[2,3,4,5,6,7,8];
var provjera=$('.upis').val();
if(provjera=='3')
{
var ary=[2,3];
}
$('[name=smjer] option').filter(function(){
return ($.inArray(parseInt(this.value),ary) >-1);
}).remove();
});
});
Also, best practice: if you don't want "upis" to EVER apply to another element on this page, consider using id instead of class.
I am trying to be able to change the value of a hidden field from multiple combo boxes.
Here is the example, I want to generate the value of the hidden field name="myNumbers" with the three previous select elements delimited by |.
How can I do this? with jQuery changing the .val() or with .attr() or maybe with a simple variable in PHP?
<select name="element1">
<option value="">Select One</option>
<option value="1">1</option>
<option value="2">2</option>
<option selected value="3">3</option>
<option value="4">4</option>
</select>
<select name="element2">
<option selected value="">Select One</option>
<option value="1">1</option>
<option selected value="2">2</option>
<option value="3">3</option>
<option value="4">4</option>
</select>
<select name="element2">
<option selected value="">Select One</option>
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
<option selected value="4">4</option>
</select>
<input type="hidden" name="myNumbers" value="3|2|4">
This will do what you want...
$(function(){
var str = $('element1').val() + '|' + $('element2').val() + '|' + $('element3').val()
$("[name='myNumbers']").val(str)
})
EDIT
A more complete solution that will iterate over every select element on the page
$(function(){
$('select').change(function(e){
var myNumbers = [];
$('select').each(function(){
myNumbers.push($(this).val());
})
$("[name='myNumbers']").val(myNumbers.join('|'));
});
});
Here it is http://jsfiddle.net/fuhQx/
You have to have an onChange function for each drop down that calls updateMyNumbers function
function updateMyNumbers() {
$("#myNumbers#").val(("#element1").val() +"|"+("#element2").val()+"|"+("#element3").val());
}
var select = document.getElementById('#element1');
var index = select.selectedIndex;
With this code, you can build the string for the hidden input
If you are wanting to set it once at the time the page is loaded, it would make sense to do it in php (see answers above).
If you want to do it whenever a user changes one of the selects, then you would want to use javascript (jQuery is one good way) to do that in response to an onChange event for any of those selects.
If you just want to do it when the form is submitted, you could also just use javascript (perhaps jQuery in particular) to do it as part of a general form validation for the onsubmit event.
If you want it to happen just prior to using the form values to store something in your database, again you would do it in php once the user has selected things and hit Submit. But then you really don't need the hidden value at all, you can just create it in php after you have the form submitted.
You would have to use javascript as php is run server-side, so before the page is loaded or after it has been submitted.
In text: You would have to capture the change events of the select boxes, generate your string and put that string in the hidden element.
Untested code:
$("select").change(function(){
var desired_value = $("[name='element1']").val() + "|" + $("[name='element2']").val() + "|" + $("[name='element3']").val();
$("[name='myNumbers']").val(desired_value);
});