Javascript - Form Select Box syntax for selected option - javascript

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

Related

onChange is not invoked when dropdown menu has only 1 item

I am populating my dropdown menu dynamically and I sometimes end up with having a single element in the dropdown. For multiple elements, there is no problem, the onChange() of my select tag works perfect. However, when there is only 1 element, the onChange() does not invoke. How can I solve this problem? Thank you!
getOptions(){
var dynamicOptions = this.props.something
const returnedOptions = []
for(int i=0; i< dynamicOptions.length;i++){
returnedOptions.push(<option value = {dynamicOptions[i]}>something</option>
}
return dynamicOptions;
}
return(
<select onChange=this.onchangemethod, value = {something}>
{this.getOptions()}
</select>
)
You would be having the same problem if the user would like to select the first option of many, since it would be the already selected one and the user would not need to re-select it.
One workaround is to always specify an "empty" option with a placeholder text
<select onChange={this.onchangemethod}>
<option value="">Please choose an option</option>
{this.getOptions()}
</select>
This way, you will always have at least two options, and the user will have to open and select one.
An alternative is to pre-select the first option so that, again, in case of user inaction, there is one option selected.
for(int i=0; i < dynamicOptions.length; i++) {
const optionProperties = {value: dynamicOptions[i]};
if (i === 0) { optionProperties.selected: true };
returnedOptions.push(<option {...optionProperties}>something</option>);
}

Append and remove div with select input in jQuery

I'm trying to add and remove a div depending on the value of a select menu. This code works well a first: when the value of the select is 2 div appears. When I return to the first value (1), the div disappears. However if I select the value 2 again, the div is not add again. Any idea ?
<select id="interv_base_youorthird" name="interv_base[youorthird]" class="form-control">
<option value="1">Pour moi</option>
<option value="2">Pour un tiers</option>
</select>
<input type="hidden" id="extra-counter" value="0">
$("#interv_base_youorthird").change(function(){
if( $(this).val() == "2" ){
const index = +$('#extra-counter').val();
const tmpl = 'hello world';
//Add sub form
$('#interv_base_intervExtras').append(tmpl);
$('#extra-counter').val(index + 1);
}
else{
$('#interv_base_intervExtras').remove();
}
});
The problem is because you remove() the #interv_base_intervExtras element when you select the first option again. When you move back to the second option #interv_base_intervExtras no longer exists in order to read the data-prototype attribute from it.
To fix this use empty(), instead of remove(), to clear the content of the element instead of removing the entire element:
var $interv = $('#interv_base_intervExtras');
$("#interv_base_youorthird").change(function(){
if ($(this).val() === "2") {
const index = parseInt($('#extra-counter').val(), 10);
const tmpl = $interv.data('prototype').replace(/__name__/g, index);
$('#interv_base_intervExtras').append(tmpl);
$('#extra-counter').val(index + 1);
} else {
$('#interv_base_intervExtras').empty(); // <-- amend this
}
});
Note that I amended the logic slightly in the above example to cache the #interv_base_intervExtras element and to explicitly use parseInt() instead of coercing the string to an int using the + operator.

Taking value from HTML select statement for a JS If Statement

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>

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.

How to cancel selected option in a select list when user confirm false (cancel)

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.

Categories