Taking value from HTML select statement for a JS If Statement - javascript

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>

Related

When appending an <option></option> in jQuery, how to set selected?

In my code, I empty a <select> element and rebuild it again with available times.
However I am trying to set the <option> to selected if it matches the previously selected time:
if(time == currenttime) {
console.log("Matched Time "+currenttime);
$("#time-start").append($("<option></option>").attr("value", time).text(time)).prop("selected","selected");
} else {
$("#time-start").append($("<option></option>").attr("value", time).text(time));
}
I get the console message Matched Time but the .prop("selected","selected") isn't setting the newly created option to be selected.
How can I set it to be selected?
I think your code will get more readable like this (and thus makes it easier to set the selected property at the right place):
let $opt = $("<option></option>").attr("value", time).text(time);
if(time == currenttime) {
console.log("Matched Time "+currenttime);
$opt.prop("selected","selected");
}
$("#time-start").append($opt);
You were close, set selected with option element
var option = $("<option>", {"selected" : time == currenttime, text: time, value: time });
$("#time-start").append(option );
OR, Use .val()
$("#time-start").val(time)
Change it to following:
$("#time-start").append($("<option></option>").prop("selected",true).attr("value", time).text(time));

HTML selected option not changing when user chooses different option

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="".

Javascript to select a drop down option in a class

I have a chrome extension that when I click it, it will click all the same element buttons on a page and then after the function is done, I want it to select all the 'P's on the drop down. I have multiple 'pf' classes on the page and will need to set all of the to P. The first function is working, when it gets to the second function, there is an error showing the option.length is undefined. My question is how do it get all the option counts inside a class?
function clickUpdate(_callback) {
var updateArray = document.getElementsByClassName("updateButton");
[].slice.call(updateArray).forEach(function(item) {
item.click();
});
console.log("this is the array legnth: " + updateArray.length);
_callback();
}
//Get select object
var objSelect = document.getElementsByClassName("pf");
//Set selected
setSelectedValue(objSelect, "P");
function setSelectedValue(selectObj, valueToSet) {
clickUpdate(function(){
console.log("I am done with the first function");
});
for (var i = 0; i < selectObj.options.length; i++) {
if (selectObj.options[i].text == valueToSet) {
selectObj.options[i].selected = true;
return;
}
}
}
<select class="pf">
<option selected="selected" value="">Not Run</option>
<option value="P">Pass</option>
<option value="F">Fail</option>
<option value="N">N/A</option></select>
Here's your problem:
//Get select object
var objSelect = document.getElementsByClassName("pf");
This doesn't just return the select dropdown - it returns an HTMLCollection (ie, a group of elements) with any elements matching that class name. Even if there's only one present, it'll come back as a collection. But your setSelectedValue function isn't expecting a collection, just a single element - that's why you get the undefined error.
There are a few ways you can handle this, depending on what you're doing elsewhere on the page:
You can use document.querySelector('.pf') to return the first element with that class - do this if you're only going to have one .pf on the page, or only want to manage one of them.
Alternately, you can use document.getElementsByClassName('pf')[0] to achieve the same thing.
Or you can give the select an id and use document.querySelector('#pf') or document.getElementById('pf')
If, on the other hand, you plan to have multiple .pf elements that all work this way...you'll have to do some refactoring first. But that's a whole other discussion.

Alert when user select the same <option> in dynamically created <selects>

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.

Javascript - Form Select Box syntax for selected option

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

Categories