How to change options of a select using JavaScript - javascript

I have an HTML page in which I have 2 selects.
<select id="field" name="field" onchange="checkValidOption();">
<option />
<option value="Plugin ID">Plugin ID</option>
<option value="Name">Name</option>
</select>
<select id="operator" name="operator" onchange="checkValidOption();">
<option />
<option value="EQUALS">EQUALS</option>
<option value="CONTAINS">CONTAINS</option>
<option value="NOT CONTAINS">NOT CONTAINS</option>
<option value="REGEX">REGEX</option>
</select>
What I'd like to happen is that checkValidOption() could make it so that if "Plugin ID" is selected in field that the only option is EQUALS (and it's selected) and otherwise all the other options are available. Any idea on how to approach this?
I tried changing the innerHTML of the operator select in JS:
document.getElementById("operator").innerHTML =
"<option value='EQUALS'>EQUALS</option>";
However this results in an empty select (this would also include manually setting the many options for going back to having all the ones listed above).
I can't think of another solution, any help would be greatly appreciated.

Try this:
Demo here
var field = document.getElementById('field');
var operator = document.getElementById('operator');
field.onchange = function () { fieldcheck(); }
operator.onchange = function () { fieldcheck(); }
fieldcheck();
function fieldcheck() {
if (field.value == 'Plugin ID') {
for (i = 0; i < operator.options.length; ++i) {
if (operator.options[i].value != 'EQUALS') {
operator.options[i].disabled = true;
}
};
operator.value = 'EQUALS';
} else {
for (i = 0; i < operator.options.length; ++i) {
operator.options[i].disabled = false;
};
}
}

To manipulate options when Plugin ID was selected:
function checkValidOption(){
var x=document.getElementById("field");
var y=document.getElementById("operator");
if (x.options[1].selected === true){
document.getElementById("operator").options[1].selected = true;
for(var i=0; i<y.length; i++){
if (i !== 1){
//disabling the other options
document.getElementById("operator").options[i].disabled = true;
}
}
}
else{
for(var i=0; i<y.length; i++){
//enabling the other options
document.getElementById("operator").options[i].disabled = false;
}
}
}
Here's a link to fiddle

A select field doesn't use the innerHTML method, you need to use value.
document.getElementById("operator").value = "...";

heres a jquery solution.
every time the first select changes, it produces new options from an array for the 2nd select. issue here is i had to change the option values of the first select to 0 and 1 to select which value in the array, you can manipulate those later if you are storing this info somewhere
http://jsfiddle.net/2TZJh/
$(document).ready(function() {
$("#field").change(function() {
var val = $(this).val();
$("#operator").html(options[val]);
});
var options = [
'<option value="EQUALS">EQUALS</option>',
'<option></option><option value="EQUALS">EQUALS</option><option value="CONTAINS">CONTAINS</option> <option value="NOT CONTAINS">NOT CONTAINS</option> <option value="REGEX">REGEX</option>'
];
});

Related

How to change to default the selected dropdown [duplicate]

I have the following HTML <select> element:
<select id="leaveCode" name="leaveCode">
<option value="10">Annual Leave</option>
<option value="11">Medical Leave</option>
<option value="14">Long Service</option>
<option value="17">Leave Without Pay</option>
</select>
Using a JavaScript function with the leaveCode number as a parameter, how do I select the appropriate option in the list?
You can use this function:
function selectElement(id, valueToSelect) {
let element = document.getElementById(id);
element.value = valueToSelect;
}
selectElement('leaveCode', '11');
<select id="leaveCode" name="leaveCode">
<option value="10">Annual Leave</option>
<option value="11">Medical Leave</option>
<option value="14">Long Service</option>
<option value="17">Leave Without Pay</option>
</select>
Optionally if you want to trigger onchange event also, you can use :
element.dispatchEvent(new Event('change'))
If you are using jQuery you can also do this:
$('#leaveCode').val('14');
This will select the <option> with the value of 14.
With plain Javascript, this can also be achieved with two Document methods:
With document.querySelector, you can select an element based on a CSS selector:
document.querySelector('#leaveCode').value = '14'
Using the more established approach with document.getElementById(), that will, as the name of the function implies, let you select an element based on its id:
document.getElementById('leaveCode').value = '14'
You can run the below code snipped to see these methods and the jQuery function in action:
const jQueryFunction = () => {
$('#leaveCode').val('14');
}
const querySelectorFunction = () => {
document.querySelector('#leaveCode').value = '14'
}
const getElementByIdFunction = () => {
document.getElementById('leaveCode').value='14'
}
input {
display:block;
margin: 10px;
padding: 10px
}
<select id="leaveCode" name="leaveCode">
<option value="10">Annual Leave</option>
<option value="11">Medical Leave</option>
<option value="14">Long Service</option>
<option value="17">Leave Without Pay</option>
</select>
<input type="button" value="$('#leaveCode').val('14');" onclick="jQueryFunction()" />
<input type="button" value="document.querySelector('#leaveCode').value = '14'" onclick="querySelectorFunction()" />
<input type="button" value="document.getElementById('leaveCode').value = '14'" onclick="getElementByIdFunction()" />
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
function setSelectValue (id, val) {
document.getElementById(id).value = val;
}
setSelectValue('leaveCode', 14);
Not answering the question, but you can also select by index, where i is the index of the item you wish to select:
var formObj = document.getElementById('myForm');
formObj.leaveCode[i].selected = true;
You can also loop through the items to select by display value with a loop:
for (var i = 0, len < formObj.leaveCode.length; i < len; i++)
if (formObj.leaveCode[i].value == 'xxx') formObj.leaveCode[i].selected = true;
I compared the different methods:
Comparison of the different ways on how to set a value of a select with JS or jQuery
code:
$(function() {
var oldT = new Date().getTime();
var element = document.getElementById('myId');
element.value = 4;
console.error(new Date().getTime() - oldT);
oldT = new Date().getTime();
$("#myId option").filter(function() {
return $(this).attr('value') == 4;
}).attr('selected', true);
console.error(new Date().getTime() - oldT);
oldT = new Date().getTime();
$("#myId").val("4");
console.error(new Date().getTime() - oldT);
});
Output on a select with ~4000 elements:
1 ms
58 ms
612 ms
With Firefox 10. Note: The only reason I did this test, was because jQuery performed super poorly on our list with ~2000 entries (they had longer texts between the options).
We had roughly 2 s delay after a val()
Note as well: I am setting value depending on the real value, not the text value.
document.getElementById('leaveCode').value = '10';
That should set the selection to "Annual Leave"
I tried the above JavaScript/jQuery-based solutions, such as:
$("#leaveCode").val("14");
and
var leaveCode = document.querySelector('#leaveCode');
leaveCode[i].selected = true;
in an AngularJS app, where there was a required <select> element.
None of them works, because the AngularJS form validation is not fired. Although the right option was selected (and is displayed in the form), the input remained invalid (ng-pristine and ng-invalid classes still present).
To force the AngularJS validation, call jQuery change() after selecting an option:
$("#leaveCode").val("14").change();
and
var leaveCode = document.querySelector('#leaveCode');
leaveCode[i].selected = true;
$(leaveCode).change();
Short
This is size improvement of William answer
leaveCode.value = '14';
leaveCode.value = '14';
<select id="leaveCode" name="leaveCode">
<option value="10">Annual Leave</option>
<option value="11">Medical Leave</option>
<option value="14">Long Service</option>
<option value="17">Leave Without Pay</option>
</select>
The easiest way if you need to:
1) Click a button which defines select option
2) Go to another page, where select option is
3) Have that option value selected on another page
1) your button links (say, on home page)
<a onclick="location.href='contact.php?option=1';" style="cursor:pointer;">Sales</a>
<a onclick="location.href='contact.php?option=2';" style="cursor:pointer;">IT</a>
(where contact.php is your page with select options. Note the page url has ?option=1 or 2)
2) put this code on your second page (my case contact.php)
<?
if (isset($_GET['option']) && $_GET['option'] != "") {
$pg = $_GET['option'];
} ?>
3) make the option value selected, depending on the button clicked
<select>
<option value="Sales" <? if ($pg == '1') { echo "selected"; } ?> >Sales</option>
<option value="IT" <? if ($pg == '2') { echo "selected"; } ?> >IT</option>
</select>
.. and so on.
So this is an easy way of passing the value to another page (with select option list) through GET in url. No forms, no IDs.. just 3 steps and it works perfect.
function foo(value)
{
var e = document.getElementById('leaveCode');
if(e) e.value = value;
}
Suppose your form is named form1:
function selectValue(val)
{
var lc = document.form1.leaveCode;
for (i=0; i<lc.length; i++)
{
if (lc.options[i].value == val)
{
lc.selectedIndex = i;
return;
}
}
}
Should be something along these lines:
function setValue(inVal){
var dl = document.getElementById('leaveCode');
var el =0;
for (var i=0; i<dl.options.length; i++){
if (dl.options[i].value == inVal){
el=i;
break;
}
}
dl.selectedIndex = el;
}
Why not add a variable for the element's Id and make it a reusable function?
function SelectElement(selectElementId, valueToSelect)
{
var element = document.getElementById(selectElementId);
element.value = valueToSelect;
}
Most of the code mentioned here didn't worked for me!
At last, this worked
window.addEventListener is important, otherwise, your JS code will run before values are fetched in the Options
window.addEventListener("load", function () {
// Selecting Element with ID - leaveCode //
var formObj = document.getElementById('leaveCode');
// Setting option as selected
let len;
for (let i = 0, len = formObj.length; i < len; i++){
if (formObj[i].value == '<value to show in Select>')
formObj.options[i].selected = true;
}
});
Hope, this helps!
You most likely want this:
$("._statusDDL").val('2');
OR
$('select').prop('selectedIndex', 3);
If using PHP you could try something like this:
$value = '11';
$first = '';
$second = '';
$third = '';
$fourth = '';
switch($value) {
case '10' :
$first = 'selected';
break;
case '11' :
$second = 'selected';
break;
case '14' :
$third = 'selected';
break;
case '17' :
$fourth = 'selected';
break;
}
echo'
<select id="leaveCode" name="leaveCode">
<option value="10" '. $first .'>Annual Leave</option>
<option value="11" '. $second .'>Medical Leave</option>
<option value="14" '. $third .'>Long Service</option>
<option value="17" '. $fourth .'>Leave Without Pay</option>
</select>';
I'm afraid I'm unable to test this at the moment, but in the past, I believe I had to give each option tag an ID, and then I did something like:
document.getElementById("optionID").select();
If that doesn't work, maybe it'll get you closer to a solution :P

Cancel select drop-down choice after window confirm

How can I cancel a select menu choice using a confirm dialog?
The idea is that when a user changes a select menu, they're prompted to confirm their choice. if they choose "cancel", the select menu goes back to its previously selected value. If they choose "OK", the select menu behaves as expected.
Here is the code I'm working on:
HTML:
<select class="selector" name="selector1">
<option value="yes">Yes</option>
<option value="no" selected="">No</option>
<option value="maybe">Maybe</option>
</select>
<select class="selector" name="selector2" >
<option value="yes">Yes</option>
<option value="no" selected="">No</option>
<option value="maybe">Maybe</option>
</select>
JavaScript
var selects = document.querySelectorAll('.selector');
var lastSelected = {};
for (i = 0; i < selects.length; i++) {
var select = selects[i];
lastSelected[select.name] = select.options[select.selectedIndex];
select.addEventListener('change', function (e) {
lastSelected = select.options[select.selectedIndex];
if (confirm("Are you want to choose this?") == true) {
return;
} else {
select.value = lastSelected[select.name];
}
});
}
I'm not entirely sure why this isn't working, any help is much appreciated.
Here is the fiddle I'm working on http://jsfiddle.net/je36eu78/2/
n.b I'd like to do this in native JavaScript (no jquery)
you overwrite lastSelected here:
lastSelected = select.options[select.selectedIndex];
you must also store the new value when the user hits OK
Another approach(stores the previous value as a property of the select)
var selects = document.querySelectorAll('.selector');
for (i = 0; i < selects.length; i++) {
var select = selects[i];
select.defaultValue=select.value;
select.addEventListener('change', function (e) {
if (confirm("Are you want to choose this?") == true) {
this.defaultValue=this.value;
} else {
this.value=this.defaultValue;
}
});
}
Try the snippet below
var select = document.querySelectorAll('.selector');
for (i = 0; i < select.length; i++) {
select[i]['last'] = select[i].options[select[i].selectedIndex].value;
(function(i){
select[i].onchange = function(){
if(confirm("Sure?")){
select[i]['last'] = this.value;
}else{
this.value = select[i]['last'];
}
};
})(i);
}
Working jsBin

Change Select tag value using JavaScript

I'm trying to change a value from a select tag using JavaScript. Let's say that I have this textbox, and if that textbox is null, no changes will be done and the value of the select tag options will be as is. But if that textbox is filled, then I have to assign a different value aside from the ones in the select tag options.
Here's what I'm trying to do:
HTML:
<input type="text" id="txtTest" />
<select name="rdoSelect" id="rdoSelect">
<option value="option1">Option 1</option>
<option value="option2">Option 2</option>
</select>
JavaScript:
if (document.getElementById('txtTest').value===null)
{
document.getElementById('rdoSelect').value;
}
else
{
document.getElementById('rdoSelect').value = "option 3";
}
I can't make it work. I've tried pointing it to an element/variable rather than to a value and it still doesn't work:
var test = document.getElementById('rdoSelect');
test.value = "option 3";
I need help, please. Thanks!
Try using SelectIndex method. Please refer the below code.
I added OnChange event to input text to test this sample.
<html>
<head>
<script language="javascript">
function test()
{
if (document.getElementById('txtTest').value=='')
{
document.getElementById("rdoSelect").selectedIndex = 0;
}
else
{
document.getElementById("rdoSelect").selectedIndex = 1;
}
}
</script>
</head>
<body>
<input type="text" id="txtTest" onchange="test();" />
<select name="rdoSelect" id="rdoSelect">
<option value="option1">Option 1</option>
<option value="option2">Option 2</option>
</select>
</body>
</html>
HTMLSelectElement doesn't let you set the value directly. It's possible to have many or zero <option>s with a particular value, so it's not a straightforward 1:1 mapping.
To select an option you can either set its selected property to true, or set the selectedIndex property of the select to the option number.
There is no option 3 in your select—are you trying to add a new option?
eg
function setOrCreateSelectValue(select, value) {
for (var i= select.options.length; i-->0;) {
if (select.options[i].value==value) {
select.selectedIndex= i;
return;
}
}
select.options[select.options.length]= new Option(value, value, true, true);
}
Is this happening on button click or onkeyup? Either way in the function you can add value to dropdownlist using this:
dropdownlist.append(
$("<option selected='selected'></option>").val(sValId).html(sVal)
);
Or you colud try this
var optn = document.createElement("OPTION");
optn.text = "--Select--";
optn.value = "0";
baseCurve.options.add(optn);`
if (document.getElementById('txtTest').value===null)
{
document.getElementById('rdoSelect').value;
}
else
{
var val = document.getElementById('txtTest').value
for(var i, j = 0; i = rdoSelect.options[j]; j++) {
if(i.value == val) {
rdoSelect.selectedIndex = j;
break;
}
}
}
Take a look at this jsfiddle, it's using jquery, which
is probably the most common solution. Hope it helps.
http://jsfiddle.net/GkLsZ/
$(function() {
$('#btnChange').on('click', function() {
var value = $.trim($('#txtTest').val());
if (!!value) {
$('#rdoSelect')
.append($("<option></option>")
.attr("value", value)
.attr("selected", "selected")
.text(value));
}
});
});

How can I replace all option labels of a select with their values?

If I have select element with values which are different from their labels, how can I replace all of the labels with the corresponding values?
Secondly, how can I sort the list alphabetically with the values, all without using any frameworks?
Input:
<select name="options" >
<option value="apple">Fruit</option>
<option value="rye">Bread</option>
<option value="beer">Beverage</option>
</select>
Output:
<select name="options" >
<option value="apple">apple</option>
<option value="beer">beer</option>
<option value="rye">rye</option>
</select>
Sure, using getElementsByTagName() and innerHTML:
var allOptions = document.getElementsByTagName("option");
for (var i=0; i<allOptions.length; i++) {
allOptions[i].innerHTML = allOptions[i].value;
}
Here it is in action.
To sort the options alphabetically, see: Javascript to sort contents of select element
If you would like them to be identical, you can simply omit the value attribute - the string inside the option tag will then be sent to the server as the value. Take a look here: http://www.w3schools.com/tags/att_option_value.asp.
You can do this:
<select name="options" >
<option value="apple">Fruit</option>
<option value="rye">Bread</option>
<option value="beer">Beverage</option>
</select>
<script>
var options = document.getElementsByName("options")[0].querySelectorAll("option");
Array.prototype.slice.call(options).map(function (option) {
option.innerHTML = option.value;
});
</script>
You can encapsulate this in a function to order your select, and order when you remove or add any element to your select.
The function would be something like this:
function sortSelect(selElem) {
var tmpAry = new Array();
for (var i=0;i<selElem.options.length;i++) {
tmpAry[i] = new Array();
tmpAry[i][0] = selElem.options[i].text;
tmpAry[i][1] = selElem.options[i].value;
}
tmpAry.sort();
while (selElem.options.length > 0) {
selElem.options[0] = null;
}
for (var i=0;i<tmpAry.length;i++) {
var op = new Option(tmpAry[i][0], tmpAry[i][1]);
selElem.options[i] = op;
}
return;
}
And you should call it like :
sortSelect(document.getElementsByName("options"));

check options in multiple select boxes

I'm trying to find a way to check my options in different select boxes (total: 4).
The boxes include the same data in value/text.
How do I avoid that the option select is the same? (I use it for an sorting feature).
And how can i integrate it in the current jquery script. (I use ajax-post to parse data).
This is how it should not be:
Select one:
<ul>
<li class="move-img">
<select style="width:150px;"id="modul1" onchange="$.modules.options(this,1);">
<option value="0"></option>
<option value="1">name</option>
<option value="2">name2</option>
</select>
</li>
Select two
<ul>
<li class="move-img">
<select style="width:150px;"id="modul2" onchange="$.modules.options(this,2);">
<option value="0"></option>
<option value="1">name</option>
<option value="2">name2</option>
</select>
</li>
jQuery
$.modules = {
/* Get price for option-modules */
options: function(module_id,show_divid){
var modul = $(module_id).val();
if(modul != 0){
//show price
$("#showprice"+show_divid).html('<div class="ajax_loader left"></div>').fadeTo(300,0.25,function(){
var $show_price = $(this); // div tag
$.post('/ajax/modules/get_prices/',{check_data:'send_data',get_module_prices_id:modul},function(data){
$show_price.fadeTo(200,100,function(){
$show_price.html(data.module_price);
});
},'json');
});
}
}
}
I wonder whether this is what you are after: http://jsfiddle.net/william/K7nTr/.
It checks whether the value has already been selected. If it has, revert to the first value and alert the user.
$.modules = {
/* Get price for option-modules */
options: function(module_id, show_divid) {
var modul = $(module_id).val();
if (modul != 0) {
var selector = ".move-img option:selected[value=" + modul + "]";
if ($(selector).length > 1) { // see if this value has been selected elsewhere
alert('The value has been selected. Try again');
$('option:eq(0)', module_id).attr('selected', 'selected');
return;
}
//show price
$("#showprice" + show_divid).html('<div class="ajax_loader left"></div>').fadeTo(300, 0.25, function() {
var $show_price = $(this); // div tag
$.post('/ajax/modules/get_prices/', {
check_data: 'send_data',
get_module_prices_id: modul
}, function(data) {
$show_price.fadeTo(200, 100, function() {
$show_price.html(data.module_price);
});
}, 'json');
});
}
}
}
In onchange="$.modules.options('modul1',1);" you dont have to pass modul1, you can just pass this which will point to the changing select box. This applies to both the select boxes. You have few js error in your code, try this.
$.modules = {
/* Get price for option-modules */
options: function(module_id,show_divid){
var modul = $(module_id).val();
if(modul != 0){
//show price
$("#showprice"+show_divid).html('<div class="ajax_loader left"></div>').fadeTo(300,0.25,function(){
var $show_price = $(this); // div tag
$.post('/ajax/modules/get_prices/',{check_data:'send_data',get_module_prices_id:modul},function(data){
$show_price.fadeTo(200,100,function(){
$show_price.html(data.module_price);
});
},'json');
});
}
}
I'm not sure I understand. in html, replace the onChange
onchange="$.modules.options(this);"
in jquery, replace:
options: function(module){
var modul = $("option:selected", module).val();
and replace too
if(modul.length == 0);
else{
by
if( modul.length > 0) {
try this
var inputs = document.getElementsByTagName("input"); //or document.forms[0].elements;
var cbs = []; //will contain all checkboxes
var checked = []; //will contain all checked checkboxes
for (var i = 0; i < inputs.length; i++) {
if (inputs[i].type == "checkbox") {
cbs.push(inputs[i]);
if (inputs[i].checked) {
checked.push(inputs[i]);
}
}
}
var nbCbs = cbs.length; //number of checkboxes
var nbChecked = checked.length; //number of checked checkboxes
for(var i=0;i<checked.length;i++)
{
if(checked[i].value=checked[i+1].value)
{
alert('Not allowed');
}
}
Not sure if i got you right here.
But my following example allows each option to be selected only once.
<script language="javascript" type="text/javascript">
var ValidateOptions = function (module) {
var selectedValue = $('option:selected', module).attr('value');
var collectionWithoutCurrent = $('.move-img select').not(module);
$('option').show();
collectionWithoutCurrent.each(function () {
$(this).children('option[value="' + selectedValue + '"]').toggle();
});
};
</script>
<ul>
<li class="move-img">
<select style="width: 150px;" id="modul1" onchange="ValidateOptions($(this))">
<option value="0"></option>
<option value="1">name</option>
<option value="2">name2</option>
</select>
</li>
</ul>
<ul>
<li class="move-img">
<select style="width: 150px;" id="modul2" onchange="ValidateOptions($(this))">
<option value="0"></option>
<option value="1">name</option>
<option value="2">name2</option>
</select>
</li>
</ul>

Categories