Programmatically select dropdown option - javascript

Is it possible to fire option click programmatically with pure Javascript?
HTML:
<select id="racetype" class="select-menu" name="race-type">
<option value="value" class="select-option js-select-option racetype-all" data-filter-value=".js-find-race-item">Race Types</option>
<option value="value" class="select-option js-select-option racetype-sprint" data-filter-value=".js-type-sprint">Sprint</option>
<option value="value" class="select-option js-select-option racetype-super" data-filter-value=".js-type-super">Super</option>
<option value="value" class="select-option js-select-option racetype-beast" data-filter-value=".js-type-beast">Beast</option>
</select>
Click to select the second option (Sprint)
JAVASCRIPT:
function SOsprint() {
var select = document.getElementById("racetype");
select.selectedIndex = 1;
return false;
}

You don't need [0]. getElementById() returns just a single element and not a NodeList
Do this:
var select = document.getElementById("racetype");

There is no need to use [0] as document.getElementById returns a reference to the element by its ID not an array.
Use
var select = document.getElementById("racetype");
instead of
var select = document.getElementById("racetype")[0];

Related

Dynamically append multiple options selected into one select jquery

I'm trying to add the options selected from one select element into another. I'm guessing it'll be something like this.
var selected = $("#selectWithOptions").append("<option'>" +
options[selectedIndex].value + "</option>");
This does not work.
The logic is pretty straight-forward and you can follow the inline comments in the JS function:
// Fire this function when a dropdown item is selected
$('#dd1').change(function() {
// Grab the text of the selected item
var selectedOption = $('#dd1 :selected').text();
// If it is not already in the second dropdown list, then append it
if( $('#dd2 option').filter(function () { return $(this).text() == selectedOption; }).length <= 0 ) {
$('#dd2').append('<option>'+selectedOption);
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div>Dropdown 1:
<select id="dd1">
<option selected disabled>Select option</option>
<option>foo</option>
<option>bar</option>
<option>baz</option>
<option>xiyar</option>
</select>
</div>
<div>Dropdown 2:
<select id="dd2">
</select>
</div>
In Javascript(and jQuery), everything is an object. Get the selected option elements using the jquery :selected selector and then append them to the second select element.
I'm using clone() but if you don't want to copy, rather you want to move the elements from one select to the other, then get rid of clone() and that same object will be moved to the other select element.
$('button').on('click',function(e){
var opt = $('#first option:selected').clone();
$('#second').append(opt);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select id="first">
<option value="hello">Hello</option>
<option value="world">World</option>
</select>
<select id="second">
</select>
<button>
Copy
</button>

bootstrap class not applied when set programmatically

I add a select tag to a div "dataColumnBuilder" programmatically when user chooses a table name from dropdown list I have
<select class="dataTableSelect form-control" onchange="addFields();" onfocus="this.selectedIndex=-1;">
<option value="">--</option>
<option value="tableName">tableName</option>
</select>
through calling this js function:
function addFields($datasetNm){
var myDiv=document.getElementsByClassName("dataColumnBuilder");
var selectList = document.createElement("select");
selectList.setAttribute('data-placeholder', 'Choose Columns');
selectList.setAttribute('class', 'chosen-select');
selectList.setAttribute('tabindex', '4');
selectList.setAttribute('multiple','');
myDiv[0].appendChild(selectList);
for (var i = 0; i <dataCols.length; i++) {
var option = document.createElement("option");
option.value = dataCols[i];
option.text = dataCols[i];
selectList.appendChild(option);
}
}
and
$(function() {
$('.chosen-select').chosen();
});
it successfully adds a select tag to the div:
<select data-placeholder="Choose Columns" class="chosen-select" tabindex="4" multiple="">
<option value="pgm_id">pgm_id</option>
<option value="title">title</option>
<option value="description">description</option>
<option value="status">status</option>
<option value="approved_date">approved_date</option>
</select>
The problem is I can't see the class "chosen-select" which is bootstrap class applied on the select list added programmatically.
Whereas if I add it to the html file directly I will see the class applied so I don't know what I am missing.
You can check the problem here: https://jsfiddle.net/Natalie77/96eds8vz/
Thanks in advance
You call $.fn.chosen on DOM ready, but never call it again on newly created <select> elements.
Call $(selectList).chosen() after adding the node to the DOM.
Also, avoid mixing inline-javascript and jQuery, otherwise what's the point of adding jQuery at all?

Get selected value of dropdown

I'm having a rather different structure of HTML and I am trying to get the selected value of a dropdown list as seen in the below code:
<div class="quantityDropdown quantityDropdown-cartItem">
<select id="qtySelect-61224b70-7b26-11e6-91d5-6921d6fe7421" class="cart-quantity-picker"
data-orderitem="61224b70-7b26-11e6-91d5-6921d6fe7421">
<option value="1">1</option>
<option value="2" selected="">2</option>
<option value="3">3</option>
<option value="4">4</option>
</select>
</div>
My code returns null.
I want to get 2 as my value. As you can see, there's no value in the selected attribute.
var quantity = document.querySelector(".quantityDropdown select").getAttribute("selected");
How do I get the value 2 that's outside the option tag?
You should get the option tag, like this:
var quantity = document.querySelector(".quantityDropdown select option:checked");
You could use checked also for checkbox and radio.
This will give you the value of the selected item:
quantity = document.querySelector(".quantityDropdown select").value;
However if you want the actual content of the selected item (i.e. the text shown) outside of the option tag, use:
var quantity = document.querySelector(".quantityDropdown select")[document.querySelector(".quantityDropdown select").selectedIndex].innerHTML;
Use document.querySelector(".quantityDropdown select").selectedIndex
To get the selected option value you need to use two properties on the select element: options and selectedIndex to get the html option element, then you can get the value.
const dropdown = document.querySelector('.cart-quantity-picker')
console.log('selectedIndex', dropdown.selectedIndex)
console.log('options', dropdown.options)
console.log('selected', dropdown.options[dropdown.selectedIndex].value)
<div class="quantityDropdown quantityDropdown-cartItem">
<select id="qtySelect-61224b70-7b26-11e6-91d5-6921d6fe7421" class="cart-quantity-picker" data-orderitem="61224b70-7b26-11e6-91d5-6921d6fe7421">
<option value="1">1</option>
<option value="2" selected>2</option>
<option value="3">3</option>
<option value="4">4</option>
</select>
</div>
in case you need the get the 'value' :
var dropdown = document.getElementById("qtySelect-61224b70-7b26-11e6-91d5-6921d6fe7421");
var selValue = dropdown.options[dropdown.selectedIndex].value;
But if you want to get the text ΝΟΤ the value , you do:
var dropdown = document.getElementById("qtySelect-61224b70-7b26-11e6-91d5-6921d6fe7421");
var selText = dropdown.options[dropdown.selectedIndex].text;
<select id="ddlViewBy">
<option value="1">test1</option>
<option value="2" selected="selected">test2</option>
<option value="3">test3</option>
</select>
For getting the value you can use
document.querySelector('#qtySelect option:checked').value;
For getting the actual text inside the option you can use
document.querySelector('#qtySelect option:checked').text;

Make textbox required if a certain value is selected in dropdown box

On a form, I have the following required drop down box:
<select id="SelectBox" name="SelectBox" required>
<option value="">Please Select ...</option>
<option value="val1">val1</option>
<option value="val2">val2</option>
<option value="val3">val3</option>
<option value="val4">val4</option>
</select>
I also have the following textbox:
<input type="text" name="textbox" id="textbox">
I am trying to make the textbox required only if val4 is selected from the dropdown box using the required attribute (red border around textbox). I have done this with a radio button group, but need to do the same with this dropdown box.
Any help would be greatly appreciated. Thanks.
This should work to make text input attribute required and add some red border if you select the val4 option from the select box only.
var select = document.getElementById("SelectBox");
var textBoxElement = document.getElementById("textbox");
select.onchange = function(){
var selectedString = select.options[select.selectedIndex].value;
if(selectedString == 'val4'){
textBoxElement.required = true;
textBoxElement.style.border="1px solid red";
}else{
textBoxElement.required = false;
textBoxElement.style.border="";
}
}
See working fiddle : https://jsfiddle.net/nwk1tkb7/5/
One approach I'd suggest is the following:
// use of a named function, to be called via Elememt.addEventListener:
function elementRequiredIf(event) {
// 'this' will be the <select> element in this example, however
// the 'this' is automatically passed from Element.addEventListener
// (as is the 'event' object, though we don't use that here):
var changed = this,
// here we find the conditionally-required element, using
// the id of the element stored in the custom data-* attribute
// of the <select> element, here we retrieve that attribute-
// value from the dataset object, stored as a property of the
// Element:
requiredElement = document.getElementById(changed.dataset.required_elem_id),
// as above, we use the same approach to retrieve the
// value that makes the other element required:
ifRequiredValueIs = changed.dataset.required_if_value;
// here we set the required property of the element to
// true (if the <select> value is equal to the required
// value, or false if they are unequal:
requiredElement.required = changed.value === ifRequiredValueIs;
}
// here we find the <select> element via its id,
// and bind an event-listener for the 'change' event,
// which, upon a change event being fired, calls the
// named function (note the deliberate, required, lack
// of parentheses following the function name):
document.getElementById('SelectBox').addEventListener('change', elementRequiredIf);
function elementRequiredIf() {
var changed = this,
requiredElement = document.getElementById(changed.dataset.required_elem_id),
ifRequiredValueIs = changed.dataset.required_if_value;
requiredElement.required = changed.value === ifRequiredValueIs;
}
document.getElementById('SelectBox').addEventListener('change', elementRequiredIf);
input:required {
box-shadow: 0 0 0.5em #f00;
}
<form>
<select id="SelectBox" name="SelectBox" data-required_elem_id="textbox" data-required_if_value="val4" required>
<option value="">Please Select ...</option>
<option value="val1">val1</option>
<option value="val2">val2</option>
<option value="val3">val3</option>
<option value="val4">val4</option>
</select>
<input type="text" name="textbox" id="textbox">
<button type="submit">Submit</button>
</form>
JS Fiddle demo.
References:
document.getElementById().
EventTarget.addEventListener().
HTMLElement.dataset.

Remove the first select option

I'd like to remove the first option of an select tag when I click on the select tag. Is this possible?
I don't want to see the first option after that click.
Thanks for any help.
You can remove the first option on click with jQuery.
$(document).on('click', 'select', function() {
$(this).find('option').get(0).remove();
});
This simply removes the first option of a select tag on click. You need to add an if statement to check if it was already removed.
There's also a simple no-javascript solution:
<select>
<option style="display: none">--Choose--</option>
<option>Cheese Cake</option>
<option>Hot Pockets</option>
<option>Sausage</option>
<option>Cookies</option>
<option>Bacon</option>
</select>
(Copied from the comments from #chipChocolate.py)
If you use bootstrap add placeholder attribute in your select.
If your not
<select required>
<option value="" disabled selected>Select your option</option>
<option value="1">1</option>
</select>
// to remove first...
document.getElementById("element_id_str").options[0].remove();
//to remove the lot...
document.getElementById("element_id_str").options.length = 0;
<select required>
<option value="" disabled selected hidden>Select your option</option>
<option value="1">1</option>
</select>
Probably you just want this:
<select required>
<option value="" hidden>Select your option</option>
<option value="1">1</option>
</select>
A very naive way of doing this:
$("#selector").change(function(evt) { //listen to changes of selection
var theElement = $(this);
if (!theElement.data("selected")) { //check if flag is not set
theElement.children("option")[0].remove(); //remove 1st child
theElement.data("selected", true); //set flag, so it doesn't continue removing items for every change
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select id="selector">
<option>--Choose--</option>
<option>Apple</option>
<option>Banana</option>
<option>Papaya</option>
</select>
If you want to remove the first option use this
$(document).ready(function()
{
$("select").children().first().remove();
});
If you want to remove the first option after clicking on the select box use this
$(document).ready(function()
{
var removed=false;
$(document).on("click","select",function()
{
if(!removed)
{
$(this).children().first().remove();
removed=true;
}
});
});
Javascript:
document.getElementById("SelectId")[0].remove();
Get the first option in the select and remove it.
I had the same problem, but the solutions above just work with one form, not with many. I added some extra code in order to validate it for many in your form:
$(document).ready(function()
{
$(document).on("change","select",function()
{
var x = $(this).children().first().attr("name");
var n = x.localeCompare("todelete");
if (n == 0)
$(this).children().first().remove();
});
});
Where "todelete" is the name for all first elements [0] defined inside the
Please select value //all first elem must have the same name
"> //the others another name (can be the same BUT not "todelete")
You need the id or class to remove the item. While testing and debugging I found 'option:first' fails to remove the item. But 'option:first-of-type' always does the work. You can get more info about 'first-of-type' here :first-of-type
$("#ID_or_.CLASS option:first-of-type").remove();

Categories

Resources