I am trying to use php (and if not php, javascript) to link to a page and include a "?type=foo" or "#foo" at the end of the link so that when the linked page loads it will automatically select a specific option, depending on the end of the link, from a dropdown menu in a form. I have tried to search for this but do not know what this action is actually called, but I've seen it done before. Does anyone know how to achieve this? Thanks very much.
When I have created these in the past, for ease of use, I have simply inserted the selected value in the top of the select object, rather than roll through the whole list and mark the selected one as such when it is encountered.
Assuming the page is called like page.php?theSelectedList=Cougar:
<select name="theSelectList">
<?php
if( isset( $_GET['theSelectList'] ) )
echo '<option selected="selected">'.$_GET['theSelectList'].'</option>';
?>
<option>Aardvark</option>
<option>Baboon</option>
<option>Cougar</option>
<option>Dog</option>
<option>Elephant</option>
</select>
In that case, the option for Cougar would be displayed twice - once at the top of the list, and selected, and again further down the list in the normal location. This may sound confusing, but, in the instances I have used it, it has been quite intuitive.
It's nice and simple, but, I will mention the caveat, that the above would need a bit of re-jigging if the Option Labels and the Option Values are different (like it each option has a numeric value, but a text label.
If the option is in a <select> then the name you are looking for is the selected attribute. It can be applied to each <option> tag, like so: W3Schools.
Using that you can simply use a PHP if-statement, eg:
<?php
$options = array('Norway', 'United States', 'Springfield');
echo '<select>';
foreach($options as $country) {
if(array_key_exists('selected', $_GET) && $_GET['selected'] === $country) {
echo '<option selected="selected">'.$country.'</option>';
}
else {
echo '<option>'.$country.'</option>';
}
}
echo '</select>';
If the query is ?country=Norway then Norway would be selected when the page loads.
It can of course be solved using javascript as well.
Related
I'm sorry I haven't included "my attempt" as such with this one, I'm useless with jquery so need some advice!!
I would like to change the value of a second selctor based on the results of the first.
I have a database of builders and regions with the headers builder_name and builder_region. The list ends up looking like this ...
builder_1 region_1
builder_1 region_2
builder_2 region_1
builder_3 region_1
builder_3 region_2
builder_3 region_3
(You get the idea)
I'm using the following in the form I've built to get a list of the builders for the first select box ...
echo '<select class= "ml-select" name="gen_builder">';
echo '<option value=" ">Select Builder</option>';
while($row = mysql_fetch_array($rsBUILDER)) {
if($linebreak !== $row['builder_name']) {
echo '<option value="'.$row['builder_name'].'">'.$row['builder_name'].'</option>';
}
else {echo "";}
$linebreak = $row['builder_name'];
}
echo '</select>';
The $linebreak is to get rid of the duplicate builder names from the list, which works a treat.
What I would like to achieve is a second selector that selects the regions available, dependant upon the builder that has been selected in the first option. I hope this makes sense????
The second query needs to look at the builder selected in the first selector and filter out just the regions that are in rows with the builder name form selector one.
Please do say if you need further information, I'm not great at explaining myself.
As you said you don't have experience with jQuery or Ajax, I'll post my answer with as many comments as possible. I will assume that you have two select dropdowns in your page.
The first one contains the builders, so it will have id="builders".
The second one contains the regions, so it will have id="regions".
From what I understand, the first select will be exactly the one you posted in your question, generated server-side (by PHP). I only ask that you please make a slight change on it, making each option value be equal to the builder's database ID, and not its name (unless the builder's primary key is their name, and not an ID). This will make no difference for the final user but will be important for our jQuery solution. The second one will be empty, as the idea is to fill it dynamically with the regions related to the builder selected in the first dropdown.
Now let's get to the jQuery code:
//Everything that goes below this first line will be ready as soon as the page is fully loaded
$(document).ready(function() {
//The following code defines an event. More precisely, we are defining that the code inside it will run every time our select with id "builders" has its value changed
$('#builders').change(function() {
//$(this) is our builders select. $(this).val() contains the selected value, which is the ID of our selected builder
var currentValue = $(this).val();
//Now, this is our Ajax command that will invoke a script called get_regions.php, which will receive the builder's ID in $_GET['builder_id'] and you can use to query your database looking for all regions related to this builder. Make sure to create an array with the returned regions. Your get_regions.php's last line should be echo json_encode($regions);
$.get("get_regions.php", {'builder_id': currentValue}, function(data) {
//Inside this function is the code that will run when we receive the response from our PHP script. It contains a JSON encoded list of regions, so first of all we need to parse this JSON
var regions = $.parseJSON(data);
//Before filling our second select dropdown with the regions, let's remove all options it already contains, if any
$('#regions').empty();
//Now, all there is left is to loop over the regions, adding each as an option of the regions dropdown. I'll do it the universal way
for (var i = 0; i < regions.length; i++) {
var regionOption = '<option value="'+regions[i]['region_name']+'">';
regionOption += regions[i]['region_name'];
regionOption += '</option>';
$('#regions').append(regionOption);
}
});
});
});
Despite any syntax errors (can't test the code from here) this should do the trick. Hope the comments were clear enough for you to understand how things work in jQuery.
Is it possible to have multiple pre-selected options in a box? Below is my PHP code which makes logical sense to me and appears to output the correct HTML with everything in the right place, but it doesn't actually display with any options selected on the page.
<?php
$options = $wpdb->get_results( $query);
$number = count($options);
$optionsChosen = explode(",", $userInfo->userOptions);
// This is the list of options the user has chosen, separated by commas, i.e. "service1, service2,"
echo "<select name=\"option[]\" id=\"option\" size=\"$number\" multiple>\n";
foreach ( $options as $thisOption ) {
echo "<option value=\"$thisOption->optionName\" title=\"";
echo stripslashes($thisOption->optionDescription)."\" ";
for($i=0; $i<count($optionsChosen); $i++){
if($optionsChosen[$i]==$thisOption->optionName){
echo "selected=\"selected\" ";
} // End if()
} // end for()
echo ">$thisOption->optionName</option>\n";
} // end foreach()
?>
</select>
This is my PHP, and the HTML it's outputting looks fine and includes the selected="selected" in the right place for the appropriate values, but for whatever reason they aren't actually selected. Is this just not a possible thing in HTML? This works fine for me if I only have one possible selection, but I can't seem to find anywhere online mentioning that its only supported for single tags. If this isn't possible, is there a way to achieve something similar?
Edit: As everybody says, it works fine. For whatever reason, refreshing the page (which was built using get variables) in Firefox would refresh the source code but not what was shown inside the browser, closing the page and re-opening it made it work as predicted.
Yes, a <select> tag with multiple attribute can have multiple options with selected="selected" attrubute, which will automatically make these options selected on page load.
Yes Element in HTML can have multiple options selected. If it has multiple attribute.
Below is code
<select multiple>
<option>India</option>
<option selected>USA</option>
<option>Canada</option>
<option selected>China</option>
</select>
I have a drop-down and drop-down options in separate tables. That's good but now I want to be able to retrieve all the options with the drop-down code. On this page I have all of the drop-downs and items. Let's say the drop-down code is dropdown1.
I'd like to be able to do
$this->Form->input('dropdownitem_id', array('options' => $dropdown['dropdown1']));
Is there a way to do this without a helper?
In the controller,
$dropdownitems = $this->OtherModel->find('list');
$this->set(compact('dropdownitems'));
In your view
$this->Form->input('dropdownitem_id');
The options for select will be populated automatically.
But I don't understand, what you meant by helper ?
1) why do you want to do it "without a helper"?
2) Yes, use normal PHP stuff - ie foreach() loop that echos HTML content to the page
Just look at what content the helper generates, and use PHP to mimic it.
<select name="whatever">
<?php
foreach($items as $item) {
echo '<option value=" . $item['id'] . '">' . $item['name'] . '</option>';
}
?>
</select>
(something like that - I wrote that quickly off the top of my head, but you should get the idea)
You should use containable behavior.
http://book.cakephp.org/2.0/en/core-libraries/behaviors/containable.html
Then you would query the top level element.
After you have done so.
You must run a foreach loop still as Dave said and format the option.
Let me know if you need help with the containable, they are a life saver and your friend !
I created a custom helper to get the exact behavior I wanted.
I have two <select> one is category and the second is subcategory.
here is the first <select> for category.
<select name="category" size="10">
<?php foreach($categories->fetch(array('table' => 'categories')) as $category) { ?>
<option value="<?php echo $category['id']; ?>"><?php echo $category['name']; ?></option>
<?php } ?>
</select>
now the second <select> i.e subcategory should be hidden initially and when a user click on category <select> based on the value it should populate the value in subcategory.
One way of doing this is via AJAX by passing categoryId as POST Request and getting HTML as response.
however i would like to know if there is any other alternative so that it automatically pass the categoryId value to PHP and unhide the second <select> here is the code of second <select>
<select name="subcategory" size="10">
<?php foreach($categories->fetch(array('table' => 'subCategories', 'categoryId' => $categoryId)) as $subCategory) { ?>
<option value="1"><?php echo $subCategory['name']; ?></option>
<?php } ?>
</select>
the only thing i need here is $categoryId to be populated dynamically. is there any way of doing this?
thank you..
No, there is no way to do what you are suggesting. PHP is only run on the server, so by the time the page is rendered on the client the PHP has already been run.
Your best bet would be what you already suggested, running some AJAX after the first select is changed, sending back the category ID to the server and retrieving what you need to build the second select.
Is there a reason why you don't want to do it this way?
Sukumar has probably suggested the best and most intuitive solution to make it appear as if the data is being loaded dynamically to the user.
The other alternative would be to submit the form when the select box is changed. Once the form has been submitted PHP would pick up the ID from the POST array and then re-populate the sub-category select box. This is often used as a fallback in case the user doesn't have JavaScript enabled.
Structurally, there are three choices to solve this problem:
Use an ajax call to fetch the required data when a user selection is made as jbruno has described.
Submit the whole page to the server, let your PHP see the newly selected option and fill in the newly desired data in a returned page. This will cause the page to refresh so is less ideal than option 1.
Pre-populate the page with all possible data in a javascript data structure so you can use Javascript to just look up the desired category ID in a local data structure, modify the page and never have to talk to the server in order to update the page.
In my opinion, option 3) is the most desirable if the data set required for local lookup is not too large (say under 100k) and it's not too expensive on the server to collect all that data for inclusion in the original page and if the data doesn't change real-time or having data as of the page load time is OK.
If option 3) isn't feasible for any reason, then option 1) is next best. Option 2) is not as good a user experience so it should only be the last resort if you really can't implement options 1) or 3).
You asked more specifically about option 3. I don't really yet understand what the whole data you need looks like. If you really only have four total data types residential_plot, residential_apartment, office_space and showroom, then you can just make those be four keys on an object and store their data that way:
var data = {
"residential_plot": 1,
"residential_apartment": 2,
"office_space": 3,
"showroom": 4
};
The 1, 2, 3 and 4 are just whatever data you want to store for that type. It can be numbers, strings, arrays of data, other objects of data, anything.
To access this, you would do like this:
var id = data.residential_plot;
or
var index = "residential_plot";
var id = data[index];
If you wanted to store the notion of categories and sub-categories, you would need an extra level of objects:
var data = {
"residential": {"residential_plot": 1, "residential_apartment": 2},
"commercial": {"office_space": 3, "showroom": 4}
};
Then, you would access it like this:
var id = data.residential.residential_plot;
or like this:
var category = "residential";
var catType = "residential_plot";
var id = data[category][catType];
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 :)