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?
Related
I have the following code
<select class="needsclick" id="country" name="order[country]">
<option value="USA" selected="selected">USA</option>
<option value="CANADA">CANADA</option>
</select>
I could do the following javascript command to change the option value
document.getElementById("country").value = 'CANADA'
however, this does not change the selected value and does not change the state box to province.
When I physically click this dropdown menu and change to CANADA, the effects of the change take place (the state box changes to province)
I am using Swift iOS to parse HTML and wondering what line of javascript code is needed to click a option value rather than changing the option value?
If I do the following after changing the value
document.getElementById("country").click()
it just clicks the menu but still does not change the state box to province (happens when physically clicking the option value)
How can I achieve this using a javascript command like the two above?
The state/province box is irrelevant to the code just relevant to the fact it changes when the dropdown is physically clicked and not when programmatically changed.
I can do the following code but it still does not change the state box to province (only if physically clicked)
document.getElementById("country")[1].selected = true
To work with the option elements within a select, you must access the options node list and then select one to work with.
Setting the value is separate from setting the selected flag.
var countries = document.getElementById("country");
var states = document.getElementById("provincesUSA");
var territories = document.getElementById("provincesCanada");
countries.addEventListener("change", function(e) { update(e); });
function update(e){
// show the correct sub-list based on the selected option
var country = countries[countries.selectedIndex];
if(country.value === "USA"){
states.classList.remove("hidden");
territories.classList.add("hidden");
} else if(country.value === "CANADA") {
territories.classList.remove("hidden");
states.classList.add("hidden");
} else {
territories.classList.add("hidden");
states.classList.add("hidden");
}
}
// To dynamically choose
document.querySelector("button").addEventListener("click", function(){
countries.options[2].selected = "selected"; // Canada
// Simulate the change event
update(countries);
});
#provincesUSA.hidden, #provincesCanada.hidden { display:none; }
<select class="needsclick" id="country" name="order[country]">
<option value="" selected="selected">Choose A Country</option>
<option value="USA">USA</option>
<option value="CANADA">CANADA</option>
</select>
<select id="provincesUSA" class="hidden" name="states">
<option value="al">Alabama</option>
<option value="ar">Arkansas</option>
</select>
<select id="provincesCanada" class="hidden" name="territories">
<option value="on">Ontario</option>
<option value="qu">Quebec</option>
</select>
<button>Force A Selection (click me whe CANADA is NOT selected)</button>
document.getElementById("country").selectedIndex = 2;
I'm pretty much brand new to JS, and working on a small web page to teach myself a little bit. I feel like this would have been answered before, but I don't know how to word it better to find it.. sorry!
basically, I have two templates set up in HTML, for two select boxes, which will be re-used quite a few times across the form. then I have a function that is called Onchange for select 1, and will change what is visible in select 2, I managed to reference select 1 with (this), but I'm completely at a loss as to how to reference the second one.
function myFunction(selectObject)
{
if (selectObject.value == 'option1')
{
//code to reference Select2 here
option3.disabled = true;
option3.style.display = "none";
}
}
<template id="Select1">
<select name="Select1" onchange="myFunction(this)">
<option value="option">option</option>
<option value="option1">option1</option>
<option value="option2">option2</option>
</select>
</template>
<template id="Select2">
<select name="Select2" >
<option value="option3">option</option>
<option value="option4">option1</option>
<option value="option5">option2</option>
</select>
</template>
thanks for any help!
Something like this? I am not sure why are you using template tags.
function myFunction()
{
var select1 = document.querySelector("#Select1>select");
var select2 = document.querySelector("#Select2>select");
var option3Visible = select1.value != 'option1';
var option3 = select2.querySelector("option[value='option3']");
option3.disabled = !option3Visible;
option3.style.display = option3Visible ? "inline" : "none";
}
<div id="Select1">
<select name="Select1" onchange="myFunction()">
<option value="option0">option0</option>
<option value="option1">option1</option>
<option value="option2">option2</option>
</select>
</div>
<div id="Select2">
<select name="Select2" >
<option value="option3">option3</option>
<option value="option4">option4</option>
<option value="option5">option5</option>
</select>
</div>
Basically you need to get familiar with events, dom query API and possibly CSS selectors.
If you're using templates, you need to search inside content property of the corresponding template:
let t1 = document.querySelector('#Select1');
let t2 = document.querySelector('#Select2');
// there are many ways how to select an element, here simple element selector is used
let select1 = t1.content.querySelector('select');
let select2 = t2.content.querySelector('select');
let option3 = t1.content.querySelector('[value=option3]');
// add event listener is preferred to your `onchange` attribute binding
select1.addEventListener('change', function() {
// modify select2 here
option3.disabled = true;
option3.style.display = "none";
});
I have two different select elements in a form
When I select an option in the first list, I want a corresponding option to be automatically set in the second list. I have made a few attempts, and I am close to getting it working using reactive-var but I need some help.
My template looks like this
<template name="inputForm">
<div class="section">
<form action="#">
<div class="row">
<div class="input-field col m4">
<select id="list-one">
<option value="" disabled selected>Choose your option</option>
<option value="1">100</option>
<option value="2">75</option>
<option value="3">50</option>
<option value="4">25</option>
<option value="5">25</option>
</select>
<label>Select List 1</label>
</div>
{{{secondListVar}}}
</div>
</form>
</div>
</template>
Then in the template helper file I have
var secondListVar = new ReactiveVar("<div class='input-field col m4'><select id='list-two'><option value='' selected>Choose your option</option></select><label>Select List 2</label></div>");
Template.inputForm.helpers({
secondListVar: function() {
return secondListVar.get();
}
});
Template.inputForm.events({
'change #list-one' : function() {
var listOneChoice = $('#list-one option:selected').text();
switch (listOneChoice) {
case "100":
secondListVar.set("<div class='input-field col m4'><select id='list-two'><option value='' selected>1.5</option></select><label>Select List 2</label></div>");
break;
case "75":
break;
case "50":
break;
case "25":
break;
case "25":
break;
}
}
});
If I select an option from the 1st list, the 2nd list seems to get cleared
but then if I click a radio button that causes the template to be hidden/shown I get this
So I have two issues
The rendering doesn't seem to be dynamic, in that I need to manually force it
When I get the 2nd list option shown, the corresponding state of the 1st list is lost
I would suggest creating the second list as html, and set its selection inside an autorun if you want to use a ReactiveVar.
Here's a working example :
http://meteorpad.com/pad/JLkM8ftKQuKhBvF3r/Lists
<template name="Main">
<label>Select List 1</label>
<select id="list-one">
<option value="" disabled selected>Choose your option</option>
<option value="1">100</option>
<option value="2">75</option>
<option value="3">50</option>
<option value="4">25</option>
<option value="5">25</option>
</select>
<label>Select List 2</label>
<select id="list-two">
<option value="" disabled selected>Choose your option</option>
<option value="1">100</option>
<option value="2">75</option>
<option value="3">50</option>
<option value="4">25</option>
<option value="5">25</option>
</select>
</template>
var SelectedItem = new ReactiveVar();
Template.Main.events({
'change #list-one' : function() {
var selected = $('#list-one option:selected').val();
SelectedItem.set(selected);
}
});
Template.Main.onCreated(function(){
this.autorun(function(){
var selected = SelectedItem.get();
$('#list-two option').eq(selected).prop('selected', true);
});
})
However, you may not even need a ReactiveVar, in this case you can set the second list directly via jquery if you wanted.
#looshi answer is the correct one, but I was also encountering issues due to the materialize package which are now sorted in my meteorpad example in light of the workaround posted here
I'm having a similar problem using Materialize. Your form select dropdowns are being created by Materialize based on values when the page is originally rendered. You will need to rerun the initialization code each time:
$('select').material_select();
Here's an example based on taking values from iron routers data function:
Tracker.autorun(function(e){
var data = Router.current().data();
Tracker.afterFlush(function(){
//dom is now created.
$('select').material_select();
});
});
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];
I've got a select list like this:
<select id="selectlist" name="selectproduct" >
<option value=""> --- Select product --- </option>
<option value="1">Product 1</option>
<option value="2">Product 2</option>
<option value="3">Product 3</option>
<option value="4">Product 4</option>
</select>
Unfortunately I can't edit it.
Is there any method which let me hide the "Product 4" option by default?
I'm trying with CSS, but it doesn't work with IE.
To hide it, wrap it with a span tag.
$( "#selectlist option[value=4]" ).wrap( "<span>" );
To show it, unwrap the span tag if it has one.
if ( $( "#selectlist option[value=4]" ).parent().is( "span" ) ){
$( "#selectlist option[value=4]" ).unwrap();
}
using css to hide options is not supported in IE, so you need to update the options list itself.
Try something like
$('#selectlist option[value=4]').remove();
Demo: Fiddle
or if you want to enable it later
var sel = $('#selectlist');
var opts = sel.find('option');
$(':checkbox').click(function(){
sel.empty().append(this.checked ? opts : opts.filter('[value!=4]'));
}).click()
Demo: Fiddle
You can hide option using following line include in scripting.
$("#selectlist option[value='4']").hide();
And if you want to again show this option use following line.
$("#selectlist option[value='4']").show();
To save your time, please read the following answer.
OK, I searched for a few hours and I noticed that there is NO WORKING WAY to "hide" (what I mean is make the option temporally disappeared from the drop-down list) for all browsers, such as set the visibility to be hidden or style="display: none".
My final approach is:
1. Create an array to store all the options for the dropdown list.
2. Use a method to dynamically update the drop-down list according what you want to be shown.
That's it, if you want to use a drop down list without using any library
You can "hide" the option by moving it to a hidden select element or cached document fragment, then move it back when you want to show it:
var selectTool = (function() {
var frag = document.createDocumentFragment();
return {
hideOpt: function (selectId, optIndex) {
var sel = document.getElementById(selectId);
var opt = sel && sel[optIndex];
console.log(opt);
if (opt) {
frag.appendChild(opt);
}
},
showOpt: function (selectId) {
var sel = document.getElementById(selectId);
var opt = frag.firstChild;
if (sel && opt) {
sel.appendChild(opt);
}
}
}
}());
Then you can hide the 4th option like:
<input type="button" value="Hide option" onclick="
selectTool.hideOpt('selectlist',4);
">
and show it again using:
<input type="button" value="Show option" onclick="
selectTool.showOpt('selectlist');
">
All play code of course, but you should get some ideas. If you want to store many options, you'll need a way of referencing them so maybe store them in an object with some form of referencing scheme.
Try to disable that option with disabled attribute.
<select id="selectlist" name="selectproduct" >
<option value=""> --- Select product --- </option>
<option value="1">Product 1</option>
<option value="2">Product 2</option>
<option value="3">Product 3</option>
<option value="4" disabled="disabled">Product 4</option>
</select>
Check demo
see this link
http://jsfiddle.net/DKKMN/
<select id="selectlist" name="selectproduct" >
<option value=""> --- Select product --- </option>
<option value="1">Product 1</option>
<option value="2">Product 2</option>
<option value="3">Product 3</option>
<option value="4" id="i">Product 4</option>
</select>
#i{display:none;}
create an id and in style make it invisble
I suppose you are using JQuery as well.
$("#selectlist option[value='option4']").remove();
to append the child below the list of option using java script.
`var option = document.createElement("option");
option.text = "All Users";
option.value = "all_user";
var select = document.getElementById("log_user_type");
select.appendChild(option);`
if you want to remove some option from select list you can use this code:
<script type="text/javascript">
$(window).bind("load", function() {
$('#select_list_id option[value="AB"],option[value="SK"]').remove();
});
</script>
<option value="4" style="display:none">Product 4</option>
hides the 4th option by default.