Populating Drop Down Boxes Via Javascript Change Selected Item - php

I populate a drop down box from an array that uses Javascript on the page load. But I am pulling data out of a database how would I change which one was selected? I would prefer not to have to use PHP to create the drop down boxes, as I have other non php things that use the javascript as well. What Can I do to get my Drop DownList populated from PHP?
You can see that it just calls the SelectdeptDropdown function.
<label for="collegedropdown">Collge</label>
<select name="collegedropdown" id="collegedropdown" onChange="SelectDeptDropdown();">
<option selected="selected">Choose a college</option>
</select>
<br />
<label for="deptdropdown">Department</label>
<select name="deptdropdown" id="deptdropdown">
<option selected="selected">Choose a department</option>
</select>
Javascript Code:
removeAllOptions(document.profilecreate.deptdropdown);
addOption(document.profilecreate.deptdropdown, "", "Choose One", "");
if(document.profilecreate.collegedropdown.value == 'MY CHOICE #1'){
//all options here
}
//repeat for other cases here
NOTE: removeAllOptions calls another function that simply clears the dropdown list. addOption calls a function that creates the option element.

basically you need to use an XHR Request. The XHR request will hit another end point of your php server which will return data for you to populate the dropwdown field and then you can use some smart javascript to insert into the dom.
Tne end point should ideally return a json data which will only be the dropdown values and you generate the markup on the client side this is ont compulsory but recommended.. read more abt XHR and json here.
Finally I would suggest you to use a library like jquery that gives you simple api for XHR requests and DOM manipulation using which you can get your job done quickly.

Related

Create <select> elements on the fly and send multiple POST as an array using jQuery and PHP

I wonder if it's possible to populate <select> elements with option values generated by PHPto a page (after load) whenever a user is clicking a button withid='add'and then be able to store each value selected as an array then send this via $_POST to a PHP page?
I would like to populate the <select> element like this:
/theloader.php
echo "<select class='plan_id'>\n";
while ($row = mysql_fetch_array($course_elements)) {
echo "<option value='".$row['plan_id']."'>".$row['plan_name']."</option>\n";
}
echo "</select>\n";
?>
This will output
<select class='plan_id'>
<option value='1'>Description</option>
<option value='2'>Description</option>
<option value='3'>Description</option>
</select>
Then when the user has populated the needed elements and selected values, click save and send everything to anotherfile.php:
$("#save").click(function() {
// Store each value as a variable then send to /anotherfile.php
});
I lack knowledge in how to perform this kind of action and would really appriciate som tips in the right direction.
Thank's in advance.
Is there any reason the population of the selects has to be dynamic? Does the data change, or are you just letting the user add more line items to choose from pre-set options?
If the data in the dropdown itself is dynamic, you will need a combination of javascript and ajax calls to get the data from the php in real time.
If the options are not dynamic, then you do not need ajax at all, just populate the variables in javascript and create an action to add more dropdowns using the already defined variables.

Making a select box that users can type values in, or choose from list

Is there a way to mimic the C input/select box where you have a pull down with a blank text-entry at the top? Users would either type a new value or select from the list. Has anyone figured a way to do this with PHP/Javascript? An AJAX type of solution would even be better.
I'm not sure what to call this type of box, I don't think it is a "combo box" like most people think of.
You have a few options.
Here's a quick function I threw together in jQuery that will do what you want. This option required the client have JavaScript enabled to work.
http://jsfiddle.net/QrA4N/25/
If you don't want to make JavaScript a requirement
If you want a solution without JavaScript (client side code). You are stuck with placing an input box with the same "name" as your select box next to it or after it and adding an "Other" option to your select box.
<select name="selAnimals" id="selAnimals">
<option value="dog">Dog</option>
<option value="cat">Cat</option>
<option value="bird">Bird</option>
<option value="guineapig">Guinea Pig</option>
<option value="">Other</option>
</select>
<input type="text" name="selAnimals_Other" id="selAnimals_Other" />
Now your PHP will have to check both $_POST["selAnimals"] and $_POST["selAnimals_Other"] to derive the correct value.
The best option is to combine the HTML above and the JavaScript above that to create a gracefully degrading solution for those with JavaScript enabled or disabled.
http://jsfiddle.net/QrA4N/26/
I added the extra HTML INPUT tags to the jsfiddle from the top of the answer and only changed 1 line of the jQuery function (makeInputSelect).
var $inp = $("#" + id + "_Other");
You can use famous Chosen library for that :)
BTW, see the second example of countries.

how to submit combo box value with out form using javascript?

I need to submit combo box value with out form. When I click on any value of combo that suppose to submit automatically using javascript. I am using PHP in backend.
<select name="select" id="select" style="width:50px;">
<option value="25">25</option>
<option value="50">50</option>
<option value="100">100</option>
<option value="All">All</option>
</select>
Here a js part:
function getinfo() {
var aList = document.getElementById("select");
var val = aList.options[aList.selectedIndex].value;
// document.write("<p>Here what you select: "+val+"</p>");
// here you can send `val` to the server using... are you using any js library?
}
And you need to change your select declaration:
<select name="select" id="select" style="width:50px;" onchange="getinfo()">
--------------------
</select>
OK, how to send val to the server is another question... If you are using jQuery - you can use jQuery.ajax(...) or any helper like jQuery.get(...). If you are vanilla-js user you can use XMLHttpRequest way and if you use any other lib - just check this lib's documentation to get helped about sending data to the server.
You can use the methods below.
1) Use Session or Cookie to send external data
2) Send a POST request using XMLHttpRequest in javascript.Checkout the link here.
3)You can use cURL function to send HTTP POST request. Please go through the link here.
Some comments:
The select element should always be inside a form. But you don't need to expose the form on the page--you do not need to include a submit input element.
You can use Javascript (JS) to submit the form after the user has changed the value of the select.
Or you can use JS with Ajax to submit the form asynchronously in the background--the user will not be aware that the data had been submitted and the page will not reload or "flash"
What would you like to do?

Drop down live update in a form

How do you live update the content of drop down 2 based on the selection made in drop down 1 in a PHP based web form?
Would appreciate any code examples to work from.
Many thanks!
You are going to have to use AJAX, I would recommend jQuery's abstraction.
e.g.
<select id="sel1">
<option value="1">1</option>
<option value="2">2</option>
</select>
<select id="sel2">
</select>
<script type="text/javascript">
$('#sel1').change(funciton(){
$.ajax({url: 'fetchSel2.php',
data:{sel1:$('#sel1').val()},
success:function(data){
$('#sel2').html(data);
}
});
});
</script>
This presumes there is a 'fetchSel2.php' that is ready to serve the options for the second select.
e.g.
function getSecondOptions($sel1){
$r=mysql_query(RELEVANT_QUERY);
$opts='';
if($r && mysql_num_rows($r)>0){
while(list($label,$val)=mysql_fetch_row($r)){
$opts.='<option value="'.$val.'">'.$label.'</option>';
}
}
return $opts;
}
if(isset($_GET['sel1'])){
echo getSecondOptions($_GET['sel1']);
}
exit;
For live update, you need to use AJAX and require JS enabled browser. If the user-browser don't support JS or JS is disabled, the only option is to submit the form and reload the whole page with the updated option in the 2nd dropdown. If you want the JS code to perform AJAX, can you kindly tell me the JS library you want to use, so I can provide the code accordingly.
What you are looking for is a cascading dropdown list. This is done using AJAX triggered in sequence by each dropdown. Here is an example via Google (http://codestips.com/php-ajax-cascading-dropdown-using-mysql/), note I'm not endorsing this link, it's just the first reasonable result.
I recently did this with jQuery http://jsfiddle.net/tBrXt/1/
You have these options:
Use AJAX if you don't want the form to refresh and update parts of
the form.
If you don't want to use ajax and can bear with refreshing the whole
form, you can capture the onChange event of the drop down using
javascript.
If the user does not have javascript enabled, the above 2 methods
will fail. Therefore, it is best to include a button users can click,
which will ask the PHP side to rerender the form.
My personal preference is to use the last method as a fall back for those who do not have javascript enabled. Then use the first method (AJAX) to progressively enhance the form for those that have javascript.

How do you set the default value of a drop down list that is being called via AJAX from another page?

For my code, my drop down lists are initiated on the original page, via
<select name =country id=country
onchange=showRecords(this.value,'country','province')>"
This function is taking the value, equating it to country, then querying MySQL, and setting the results where id=province, and creating cascading dropdown lists. This is obviously via Ajax.
So, when $_REQUEST['province'] is set, then the Province dropdown list gets populated with all provinces from the country to which it belongs, etc.; i.e.;
<?if(isset($province)){
echo "<script>showRecords('".$country."','country','province');</script>";}?>
However, for the life of me, I cannot figure out how I can set the default value equal to $_REQUEST['province']. I cannot use the traditional way:
if (($selected) == ($value)) {
$options.= " selected";
}
Because it is querying the AJAX page with one piece of information at a time.
Any ideas would be greatly appreciated.
Your code doesn't seem to make a lot of sense. The particular thing that worries me is that you say ajax is loading one item at a time?
Perhaps something like this. A country select tag like...
<select onchange="showRecords(this)">
As well as creating the javascript function showRecords() which will be called when someone chooses an option in the select tag.
<script>
function showRecords(calling_element) {
// do AJAX call here using calling_element.options[calling_element.selectedIndex].value as the selected country. this.value does not work for select tags.
}
</script>
the PHP page that receives this AJAXed request would reply with a JSON object containing all of the province values, or a delimited list.
once the Javascript showRecords function receives the responce from the PHP page, it would add each of these options to the correct select tag. Once finished, it would set the default value to whichever option it wants by something like the following:
target_element.selectedIndex = {desired list index here};
I have a lot of assumptions to your questions,
first is, if bydefault you have the select province like this
<select id="province">
<option value=""></option>
<option value="California">California</option>
<option value="Washington">Washingthon</option>
</select>
then you can use this script to default select
document.getElementById("province").value="Washington";
but if bydefault you have the select province like this
<select id="province"></select>
then you can use this script to default select
document.getElementById("province").innerHTML='<option value="Wahsington">Washington</option>';
so it depend on your code and your need. maybe if you have another case the problem should be solved in another way.
cmmiiw :)

Categories