Adding another option to a select box

I use php and html only in my application. I have no experience with javascript whatsoever.

I been searching for days on how to refresh a select box with Ajax without any success. It’s seems like everybody know how to dynamically update a second select box based on the result of a first select box but have not seen a single example anywhere on how to refresh just one select box.

Here is my problem:

I have several dozens of forms and pretty much all of these forms have a least a select box in them. Sometime when a user fills a form an option is missing from the list of option offered in a select box. I give the user the ability to create a new option for this select box but the problem is in order to be able to select this option in the form the select box must first be re queried in order to show it inside the select box. reloading the page has not been a problem so far but getting into an area where I have no choice to update or refresh only the select tag. Everyone has been telling me that this is the perfect job for Ajax, but can’t find any example anywhere on how to do that. Should maybe I change how I update my database through php only and somehow use JS & Ajax to do that instead, eliminating the popup form to create a new option in the select box? Pointing me in the right direction would be greatly appreciated. thank you

To me, the easier industry-standard technique is to have an Other option in the select box, which allows a text-field to be used to supply different information.

<form id="personalInformation">
    <p>Gender:
        <select name="gender">
            <option value="">Please choose...</option>
            <option value="male">Male</option>
            <option value="female">Female</option>
            <option value="other">Other</option>
        </select>
    </p>
    <div id="othergender">Other gender
        <input name="other-gender" />
    </div>
</form>

The above technique allows the other information to be available even when there is no scripting.

When there is scripting, we can add a class of “hidden” to the othergender area to hide it until we need it.

Style:

.hidden {
    display: none;
}

Script:

document.getElementById('othergender').classList.add('hidden');

So how do we use scripting to update things? We can take action when the select box changes:

var form = document.getElementById('personalInformation');
form.elements.gender.onchange = function () {
    ...
};

When the selected box changes, we check if the value is “other”. If it is we can remove the hidden class from the other gender section.

var selectedOption = this.options[this.selectedIndex],
    otherGender = document.getElementById('othergender');
    
if (selectedOption.value === 'other') {
    otherGender.classList.remove('hidden');
} else {
    otherGender.classList.add('hidden');
}

You can see this in action at http://jsfiddle.net/g6px8h14/1/

thank you Paul, I really appreciate you forwarding this logic to me. Unfortunately I can’t use it (although I wish I could, things would be a lot simpler.) The problem is I must save it to the database and assign an ID number to every option since I use it as criteria to create queries and reports. if the option doesn’t have an ID number it simply wont validate. I would have to somehow save it first along with all the other supporting information that makes an option valid:

example:

let’s say I am entering a “Location” option. A building can have 80 rental units but can also have commercial kitchen, library, offices and so on… there is no way anyone can pre-load all the location in a building and be 100% accurate. Therefore it is required to have the ability to create other location on the fly. That being said these locations have Categories, types and so on. this needs to be filled in before a location can be created. adding a simple “option name” won’t be sufficient most of the time.

This is something for which a detailed requirements list is needed, before a suitable recommendation can be made.

Detailed requirements list?

that’s impossible for me to come up with a list of requirement. I would have to write like 30 pages worth just to scratch the surface of all the various application select boxes have in my database. At this time I have roughly around 120 forms. When I will be finished with this project I surmise I will have double that amount, so its really hard for me to be specific at this time.

the simplest way I can put it is this:

At the top of every browser there is a refresh button.
I want to replicate what that refresh button does but to only refresh one field on a form and not the whole page.
I don’t mind having users clicking that refresh button if it can’t be done automatically.
the functionality and data is already in place. all works perfectly but in order for it to work I have the refresh the page. I would much rather only refresh the select box if it can be done while using ajax

You are wanting to send information to the server, and have the server send back information to the web page (for the select box) without needing to refresh the page.

My question is, why does the server need to be involved with things at this stage at all?

ok I see how I can be vague, let me try to explain the way I have this working:

Let’s I have a form that records the last fire drill performed in an assisted living for seniors citizens and saved into FireSafetyDrill.php

The specific of the drill is entered in a form of about 20 fields. Some of those fields are select boxes.

So let’s say there is a select box that ask

“Which safety Device was activated?” (a device that would engage the alarm of the building)
these devices have to be tested and we have to record which device was activated and tested succefully. the best way to do that is to assign an ID number to each device.

so let’s say there was a new device installed in the building and now required to be tested. this device being new won’t appear on the list of already existing fire safety device on the list so we must add it to the list.

The user click the “Add new device” button beside the select box and a pop up form FireSafetyDevice.php appears where they can describe the device and where it is located in the building. This device then gets saved and added to the database and is now available as an option in the select box of the FireSafetyDrill.php

but before I can select this option the page must be refreshed since we just added this new device. once I refresh the page and open the select box I then get the option of selecting the last fire safety device we jsut added.

What I want to do is simply be able to update the content of the option in the select box so a newly added item can be selected. THe only way I can do that is if I requery the select box which is in php script and the only way to update php is if I check to see if the submit button of the form has been set, or refresh the whole page. do you understand what I am saying? Forgive me I am French, not easy for me to explain in English.

Okay, that sounds fairly easy to achieve.

What JavaScript code libraries are you currently using? Also, it might be good if the existing server code that builds the select options, is used once again when it comes to rebuilding them. So some details on the server code that is currently used to build the select options would be useful too.

Should we abandon this thread for the near-duplicate that you began over at Can you a php script on the same page with ajax? ?

no no please stay with me lol. my other post was to ask people if they had any ideas on how I should formulate my question on google.

I am using the latest version of jquery

an example of the script to build the select tag would be similar to this:

 <div class="stretch">
                    <label for="locationid" class="labelStretch">Location of activated fire safety device?  Choose "none" if no real life firedrill was performed</label><br />
                    <select name="locationid" class="input" id="locationid" value="<?php echo escape (Input::get('locationid'));?>">
                         <option > Location </option>
                         <?php 
                            $location = DB::getInstance()->query("SELECT id, location FROM locations");
                            if($location->count()){
                                  foreach($location->results() as $row){
                                     $selected = $row->id == $user->data()->locationid ? ' selected="selected"' : null;?>
                                  <option value="<?php echo $row->id ?>"<?php echo $selected?> ><?php echo $row->location ?></option>
                                 <?php  
                                 }
                             }
                        ?>
                        </select>&nbsp;&nbsp;&nbsp;
                      <a class="newItem"href="#" onClick="MM_openBrWindow('location.php','locationPopup','toolbar=yes,menubar=yes,scrollbars=yes,resizable=yes,width=650,height=900')">New Location</a>
                </div>

Good one - move the code for creating the select in to a separate PHP function, and you will then be able to reuse that function later on when needed from the web page.

I 'm not sure I understand what you are saying to me???
are you saying to copy this bit of code into a separate file so I can then use Ajax to call it and run it to get the new updated data???
I can’t use it where it stand, I have to duplicate it in order for Ajax to work? is that how Ajax works?

It sounds like you need a primer on how Ajax works. Ajax is just a technique to send data to the server, and in turn receive a response from the server.

Commonly this is done to send information to a PHP page, and receive updated content from that same PHP page. That updated content might be a JSON data structure, it could be some HTML content, or there might even be no response at all.

In your situation, it seems that your FireSafetyDevice popup form is a completely different page. In that type of situation, it seems reasonable that when the FireSafetyDevice page is submitted, for that page to then trigger a refresh on the FireSafetyDrill page. No Ajax complications are needed at all. If that’s all you need then that’s fairly easy to achieve.

yes, and that is where I am at the moment but I would prefer just updating the select box and not the whole page if it is at all possible?

Both techniques require the pop up page communicating with the main page once the pop up page has finished. The Ajax communication is a further stage from just reloading the page.

In other words, once the work is done that’s needed to get to the point of being able to automatically reload the page, the relatively simple reload part can then be replaced with further additional work to do the Ajax part.

Making sure that other parts of the system work though is vital, which is why I suggest getting the reload part working first, as a first stage of testing.

1 Like

That’s all I need → trigger the refresh. Can this be done in javascript? “Just the select box” and not the whole page like JS location.reload(); or php header(“refresh: 3;”); or clicking the refresh button on top of the browser.

All the work has been done and everything works from beginning to end but only if I refresh the whole page. I am looking for an alternative in AJAX.

is this the function that will allow me to accomplish this?

$.ajax({  
url: url,  
data: data,  
success: success,  
dataType: dataType });

There are several things that you will need to do first before getting to use the ajax command, both before and after.

Before:

  1. The popup page needs to run some additional code after the form has been submitted
  2. The popup page needs to be told to run a function on the main page
  3. The main page needs an identifier of some kind so that the popup page can refer to that
  4. The main page needs a separate function somewhere so that the popup page can trigger it

At this stage is where you can reload the page to achieve some small level of usability from what you have done.

Before using ajax, you need to:

  1. separate out the PHP code that is used to create the select box in to a separate function
  2. test that code so that you can be sure that it works both from the normal page, and when called separately
  3. check that the appropriate output (a select box and options) occurs when you run that separate function

Now you are ready to use ajax, where you call that separate function and use its output to replace the existing select box.

My question to you is: do you want to do this all in one go, or do you want something that works while you prepare for the next stage of things?

This is awesome stuff Paul. Now that I know the steps that I must follow in order to get that done I think I will give this a go tonight when I get back home from work. I will let you know how it went and then post my script if it succeeded so others can benefit from your more than generous time you graciously extended to me with this problem. There is no rush for me to complete this since the site is not yet live. I still have quite of lot of work to do before this can happen.

Keep you posted if I hit an obstacle along the way, thanks a bunch amigo.

This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.