I'm having some issues with a dropdown I created with HTML. The options that populate the select dropdown come from my database. I want the user to be able to choose a place type (job, school, work etc.) from the dropdown, once selected the user can click on the map to drop a point or type in the address.
The input for the address is disabled until the user selects something from the dropdown. My problem is that the selected dropdown option does not reflect the change to the user. It's just stuck on the job option, but when you click on the map the point and the correct label title is placed.
HTML:
<select name="places" id="places" class="form-control" onchange="addPlace(this)">
<option value="" selected disabled="">Choose one</option>
</select>
JavaScript:
function addPlace() {
places = document.getElementById("places");
place = places.options[places.selectedIndex].textContent;
if (place.value === "") {
alert("Alert Message");
document.getElementById("address").disabled = true;
} else {
document.getElementById("address").disabled = false;
}
if (place !== "") {
placeTogo.push(place);
if (map1 === undefined) {
loadAPI();
}
} else if (place == "Other") {
placeId = places.selectedIndex + 1;
} else {
placeId = places.selectedIndex + 1;
placeTogo.push(place);
if (map1 === undefined) {
loadAPI();
}
}
for (var i = 0; i < places.length; i++) {
places[i].selected = false;
}
}
(It's a little difficult to ascertain how exactly this code fits into your application (and whether or not it will run as intended), but here's my best crack at solving the specific problems you mentioned above
My problem is that the selected dropdown option does not reflect the change to the user. It's just stuck on the job option, but when you click on the map the point and the correct label title is placed.
The for-loop at the end of your addPlace function is causing this behavior; it is deselecting every option the moment your selection changes, and the browser doesn't know what to do other than pick the first non-disabled option ("Job"). The browser already does the work of updating the selected state of each option for you; just delete that for-loop entirely.
Instead of using textContent to determine which option is selected, use the value property (then you can change the visible text later without having to worry about your JS code breaking).
Disable your input#address with an HTML attribute, because the change event won't be fired on change load (and thus your address would otherwise be editable by default).
There are a few sections of your change handler that don't seem necessary, but since I don't have the whole context of your project at hand I hesitate to adjust much else. For example, your alert will never run, because the only option with an empty string value is disabled (despite being initially selected).
/* Here are all of the things I guessed about
your implementation to get this example to work */
var placeTogo = [], // `push` made me guess this is an array
map1 = {} // some object loaded by the api?
function loadAPI() {
console.log('Tried to load API')
}
/* Here's where your original code begins, with edits */
function addPlace() {
places = document.getElementById("places");
place = places.options[places.selectedIndex].value;
if (!place) {
alert("Alert Message");
document.getElementById("address").disabled = true;
} else {
document.getElementById("address").disabled = false;
}
if (place) {
placeTogo.push(place);
if (map1 === undefined) {
loadAPI();
}
} else if (place == "Other") {
placeId = places.selectedIndex + 1;
} else {
placeId = places.selectedIndex + 1;
placeTogo.push(place);
if (map1 === undefined) {
loadAPI();
}
}
}
<select name="places" id="places" class="form-control" onchange="addPlace(this)">
<option value="" selected disabled>Choose one</option>
<option value="Jobs">Jobs</option>
<option value="Work">Work</option>
<option value="Other">Other</option>
</select>
<input id="address" disabled placeholder="123 Main Street"/>
For one thing, I think in HTML option tag it's just 'disabled' , not disabled="".
Related
I'm running into a little trouble trying to determine the value of an HTML select object.
I've got 2 items, which I'm putting down as Value 1 or Value 2, however any method I try just returns "Undefined" when printed to console
var catId = document.getElementById('catid');
var catCheck = catId.options[catId.selectedIndex].value;
console.log(catId);
console.log(catCheck);
<select name="catid" id="catid">
<option value="1">Category</option>
<option value="2">Product</option>
</select>
However when I console.log(catId.Value) or console.log(catCheck.value) (I'm obviously not trying both at the same time) I just returned an "Undefined" value.
I want to run an IF ELSE statement based on this variable, so ideally I'd like it to be able to pick up at least one of the two values!
Likelihood is I've made a dumb mistake and just can't see the wood for the trees but any help would be appreciated
You could also get the selected <select> <option> like this:
var catCheck = document.getElementById("catid").selectedIndex;
console.log(catCheck);
Your first option would return 0, your second 1 and so on.
You wouldnt have to use value this way.
You can listen for the select element to change by adding an event listener for the change event. This will trigger the performDropdownAction function anytime you select a new value within the dropdown list. You can then use this.value to get the value of the current drop-down item you're on.
Also, I've added a window.onload event, which will fire when your webpage has loaded, meaning it will perform the performnDropdownAction when the page loads and when a new item is selected.
See working example below :
const performDropdownAction = function() {
let current = this.value || document.getElementById('catid').value;
if (current == 1) {
console.log("One is selected");
} else if (current == 2) {
console.log("Two is selected");
}
}
window.onload = performDropdownAction;
document.getElementById('catid').addEventListener('change', performDropdownAction);
<select name="catid" id="catid">
<option value="1">Category</option>
<option value="2">Product</option>
</select>
I have built a one page website that is broken up by section and each section has ids. My client wants to be able to navigate to each section using a href (#'s) in the search bar like
www.website#gohere
And with my sections, this works well. My problem is they just threw a curve ball and I don't know how to go about doing this -
On my page in a certain section called #labSearch I have a dropdown that is populated from a csv file using jQuery here:
var location = arrayOfEvents[i][0];
if (location != prevLoc)
{
select.innerHTML += "<option id = "+"test" +" value=\"" + location + "\">" + location + "</option>";
}
When a dropdown option is selected, certain divs show up according to the value of the dropdown. They need it so that say the dropdown option is Dallas, when they go:
website.com#Dallas
It takes them to the section with the dropdwin (this is #labSearch) and acts as if the user has selected the Dallas option, meaning the right divs are displayed. I have tried as you can see above giving the options ids, however this does nothing.
How can I make an a href in the search bar select a certain dropdown option? Is this possible?
Why won't the option id work?
Here is my dropdown code in my labSearch section:
<form id="locationForm" style = "width: 70%; margin: auto; padding-bottom: 30px;">
<select class = "form-control" id="selectNumber" style = "">
<option>Choose a location</option>
</select>
</form>
EDIT: Ok at the end of my javascript outside of document ready or anything I have:
var selectHashOption = function () {
console.log("hash changed");
var select1 = document.getElementById('selectNumber');
var parts = location.href.split('#');
if (parts.length > 1) {
var hash = parts[1]; // Get the hash part of the URL
console.log("HASH="+hash);
select1.value = hash; // Select the option in the dropdown list
//select1.onchange();
dropdownChange();
// Trigger the onchange event handler
}
};
window.onhashchange = selectHashOption;
});
</script>
This all works well, except I am unable to call dropdownChange - I get that it is undefined, however I have declared the variable at file scope here:
<script>
var dropdownChange;
Then set it in document ready:
$(".form-control").change(function () {
dropdownChange = function()
{
//stuff
This was explained here Why can I not define functions in jQuery's document.ready()? and I did it as they did. This is BEFORE my hash change window stuff. I can't even call onchange because that is undefined as well. What can I do?
EDIT 2:
I now have my func declared initially at scope level then set here:
dropdownChange = function () {
}
$(".form-control").change(dropdownChange);
In my hash stuff after I tried:
if (parts.length > 1) {
var hash = parts[1]; // Get the hash part of the URL
console.log("HASH="+hash);
select1.value = hash; // Select the option in the dropdown list
select1.onchange();
}
and got same this function is undefined. I then call the function directly with:
if (parts.length > 1) {
var hash = parts[1]; // Get the hash part of the URL
console.log("HASH="+hash);
select1.value = hash; // Select the option in the dropdown list
dropdownChange();
}
And the function is called but the value (I console.log(this.value)) is undefined here -
You can select an option by setting the value attribute of the dropdown list. I assume that the option value matches the hash part of the URL typed by the user.
For this HTML markup:
<select id="select1">
<option value="Dallas">Dallas</option>
<option value="New York">New York</option>
<option value="Los Angeles">Los Angeles</option>
<option value="Chicago">Chicago</option>
</select>
You can select the option that matches the hash part of the URL with this code:
var selectHashOption = function () {
var select1 = document.getElementById('select1');
var parts = location.href.split('#');
if (parts.length > 1) {
var hash = parts[1]; // Get the hash part of the URL
select1.value = hash; // Select the option in the dropdown list
select1.onchange(); // Trigger the onchange event handler
}
};
window.onhashchange = selectHashOption;
Once the option is selected, I call onchange to trigger the event handler of the dropdown list. Depending on the way the event handler was set, you may need to do it differently, as mentioned in How can I trigger an onchange event manually?.
I needed to monitor the onhashchange event to make it work in my test code, as you can see on the last line of the code sample.
I have a PHP page that creates multiple selects depending on how many the page before it gives it and creates the same number of options that there are selected (it's to choose the priority).
<select name="select1" id="idSelect" onchange="javascript:SelectOnChange();">
<option value="Select one">Select one</option>
<option value="1">1</option>
<option value="2">2</option>
</select>
What I want to do is, whenever the user chooses an option that was already selected in another selection, to show an alert in order to let them know that their choice has already been taken and deny the change.
I want to compare the currently selected option to every previously selected option every time the user selects something from every select.
Basically your looking for a change event to loop through each select and notify duplicates.
$("select").change(function() {
var currentSelection = this.value;
$("select").each(function() {
if (this.value == currentSelection) {
alert("you've already chosen this!");
}
});
});
Something like this should work
Listen for change events
Get the element's seletedIndex
Grab all of the selects with getElementsByTagName()
Loop through and get the selected index
Compare to see if used
This could maybe work :
var $selects = $('select');
// WHen a select is changed.
$selects.onchange(function() {
// Storing it's selected value, assuming there is only one per select.
var value = $(this).selected().first().attr('value');
var $changedSelect = $(this);
// For each select...
$selects.each(function() {
var $otherSelect = $(this);
// ...that is not the one that just changed.
if( ! $otherSelect.is($changedSelect)) {
// If that other select's selected value is the same as the changed one's
if($otherSelect.selected().first().attr('value') === value) {
alert('...');
}
}
});
}
I didn't try it though, you might have to change a few details in it if it doesn't work.
I have this JavaScript code:
function change(varam){
if(confirm("Select this option?"))
{
} else {
if(varam=="1")
{
alert("Return selected to NO");
} else {
alert("Return selected to YES");
}
}
}
And the HTML code:
<select id="sel" name="sel" onchange="change(this.value)">
<option value="1">YES</option>
<option value="0">NO</option>
</select>
What I want:
Suppose the selected default is YES. If the user selects NO, appear confirmation boxes if he wants to change to NO or not, if the choice is "OK", the option NO will be selected, if the choice is "CANCEL" then NO option is not selected, but back to the YES option are selected. And vice versa.
See this fiddle : http://jsfiddle.net/CtxUy/
If you're only ever concerned about these two elements, you can just set the values manually:
if(varam=="1")
{
document.getElementById('sel').value = 0;
} else {
document.getElementById('sel').value = 1;
}
If there are potentially other values, what you can do is keep track of the initially selected value and set the selector value back to that when they refuse to confirm, or overwrite that stored value if they do confirm.
Like so: http://jsfiddle.net/CtxUy/2/
You can iterate over the options and select the one that has the selected attribute. If none has it, select the first one (which is always the default in absence of the selected attribute).
var select = document.getElementById('sel');
var options = select.options;
options[0].selected = true; // preemptively select the first option
for (var i = 0, l = options.length; i < l; i++) {
if (options[i].hasAttribute('selected')) {
options[i].selected = true;
break;
}
}
DEMO
Reference: HTMLSelectElement, HTMLOptionElement.
if (document.myform.mycheckbox.checked)
If checkbox is checked, then do something...
...what line of code would do the same thing for a select box option?
if (document.myform.myselectbox.myselection.selected)
Is it something like that? I can't seem to find what it is I'm looking for.
What I'm doing is here:
Link to stuff nada workola
you are looking for:
if (document.myform.myselectbox.selectedIndex != -1)
When there is nothing selected the index returns -1.
If you actually want the internal value or text string for the selected option you can access it by index:
var selObj = document.myform.myselectbox;
var selIndex = selObj.selectedIndex;
var selOptionValue = selObj.options[selIndex].value;
var selOptionText = selObj.options[selIndex].text;
However you need to be aware that the behavior is also a bit dependent on how you have it displayed. With a "single" select element (e.g. a "drop down") if you don't specify that a particular option is "selected" then the first option (index 0) is considered to be selected as that is how it is visually displayed.
<select>
<option>red</option><!-- "selected" by default when rendered -->
<option>orange</option>
<option>yellow</option>
...
</select>
If you have a select element with a size attribute greater than 1 (e.g. 6) then visually there are none selected, thus the element will return -1 by default (if none were selected)
<select size="6">
<option>red</option><!-- NOT "selected" by default when rendered -->
<option>orange</option>
<option>yellow</option>
...
</select>
Either way, you can use code like this to determine what to do:
var mySelect = document.myform.myselectbox;
var selIndex = mySelect.selectedIndex;
if(selIndex != -1){
//an option is selected
if(selIndex == 0){
//first option is selected
} else if(selIndex == 1){
//second is selected
} else if(selIndex == 2){
//third is selected
}
} else {
//no option is selected
}
You could write this using a switch/case statement too, I've just expanded this to indicate a few values