Get selected option's value in Javascript - javascript

I am using Javascript in back-end (Odoo, it's Python web framework) and i want to get selected option to save object.
i have consider event like this
events: {
'click .GenderClass': 'clickPill',
},
and then i have code where i build selected option to show in page
_renderEdit: function () {
this.$el.empty();
var array = ['', 'Male', 'Female'];
var selectList = document.createElement("select");
selectList.className = "GenderClass";
for (var i = 0; i < array.length; i++) {
var option = document.createElement("option");
option.value = array[i];
option.text = array[i];
selectList.appendChild(option);}
this.$el.append(selectList);
},
and when user click Male or Female i want to call clickPill and it's working but when i want to get selected option value then it's undefined
clickPill: function (ev) {
var target = $(ev.currentTarget);
var selected_data = $(ev.currentTarget).find(':selected').attr("text") <- here i want selected value;
console.log(selected_data);
}

Related

Issue changing value of dropdown with js [duplicate]

I want to create a function in order to programmatically add some elements on a page.
Lets say I want to add a drop-down list with four options:
<select name="drop1" id="Select1">
<option value="volvo">Volvo</option>
<option value="saab">Saab</option>
<option value="mercedes">Mercedes</option>
<option value="audi">Audi</option>
</select>
How can I do that?
This will work (pure JS, appending to a div of id myDiv):
Demo: http://jsfiddle.net/4pwvg/
var myParent = document.body;
//Create array of options to be added
var array = ["Volvo","Saab","Mercades","Audi"];
//Create and append select list
var selectList = document.createElement("select");
selectList.id = "mySelect";
myParent.appendChild(selectList);
//Create and append the options
for (var i = 0; i < array.length; i++) {
var option = document.createElement("option");
option.value = array[i];
option.text = array[i];
selectList.appendChild(option);
}
var sel = document.createElement('select');
sel.name = 'drop1';
sel.id = 'Select1';
var cars = [
"volvo",
"saab",
"mercedes",
"audi"
];
var options_str = "";
cars.forEach( function(car) {
options_str += '<option value="' + car + '">' + car + '</option>';
});
sel.innerHTML = options_str;
window.onload = function() {
document.body.appendChild(sel);
};
I have quickly made a function that can achieve this, it may not be the best way to do this but it simply works and should be cross browser, please also know that i am NOT a expert in JavaScript so any tips are great :)
Pure Javascript Create Element Solution
function createElement(){
var element = document.createElement(arguments[0]),
text = arguments[1],
attr = arguments[2],
append = arguments[3],
appendTo = arguments[4];
for(var key = 0; key < Object.keys(attr).length ; key++){
var name = Object.keys(attr)[key],
value = attr[name],
tempAttr = document.createAttribute(name);
tempAttr.value = value;
element.setAttributeNode(tempAttr)
}
if(append){
for(var _key = 0; _key < append.length; _key++) {
element.appendChild(append[_key]);
}
}
if(text) element.appendChild(document.createTextNode(text));
if(appendTo){
var target = appendTo === 'body' ? document.body : document.getElementById(appendTo);
target.appendChild(element)
}
return element;
}
lets see how we make this
<select name="drop1" id="Select1">
<option value="volvo">Volvo</option>
<option value="saab">Saab</option>
<option value="mercedes">Mercedes</option>
<option value="audi">Audi</option>
</select>
here's how it works
var options = [
createElement('option', 'Volvo', {value: 'volvo'}),
createElement('option', 'Saab', {value: 'saab'}),
createElement('option', 'Mercedes', {value: 'mercedes'}),
createElement('option', 'Audi', {value: 'audi'})
];
createElement('select', null, // 'select' = name of element to create, null = no text to insert
{id: 'Select1', name: 'drop1'}, // Attributes to attach
[options[0], options[1], options[2], options[3]], // append all 4 elements
'body' // append final element to body - this also takes a element by id without the #
);
this is the params
createElement('tagName', 'Text to Insert', {any: 'attribute', here: 'like', id: 'mainContainer'}, [elements, to, append, to, this, element], 'body || container = where to append this element');
This function would suit if you have to append many element, if there is any way to improve this answer please let me know.
edit:
Here is a working demo
JSFiddle Demo
This can be highly customized to suit your project!
This code would create a select list dynamically. First I create an array with the car names. Second, I create a select element dynamically and assign it to a variable "sEle" and append it to the body of the html document. Then I use a for loop to loop through the array. Third, I dynamically create the option element and assign it to a variable "oEle". Using an if statement, I assign the attributes 'disabled' and 'selected' to the first option element [0] so that it would be selected always and is disabled. I then create a text node array "oTxt" to append the array names and then append the text node to the option element which is later appended to the select element.
var array = ['Select Car', 'Volvo', 'Saab', 'Mervedes', 'Audi'];
var sEle = document.createElement('select');
document.getElementsByTagName('body')[0].appendChild(sEle);
for (var i = 0; i < array.length; ++i) {
var oEle = document.createElement('option');
if (i == 0) {
oEle.setAttribute('disabled', 'disabled');
oEle.setAttribute('selected', 'selected');
} // end of if loop
var oTxt = document.createTextNode(array[i]);
oEle.appendChild(oTxt);
document.getElementsByTagName('select')[0].appendChild(oEle);
} // end of for loop
Here's an ES6 version of the answer provided by 7stud.
const sel = document.createElement('select');
sel.name = 'drop1';
sel.id = 'Select1';
const cars = [
"Volvo",
"Saab",
"Mercedes",
"Audi",
];
const options = cars.map(car => {
const value = car.toLowerCase();
return `<option value="${value}">${car}</option>`;
});
sel.innerHTML = options;
window.onload = () => document.body.appendChild(sel);
const countryResolver = (data = [{}]) => {
const countrySelecter = document.createElement('select');
countrySelecter.className = `custom-select`;
countrySelecter.id = `countrySelect`;
countrySelecter.setAttribute("aria-label", "Example select with button addon");
let opt = document.createElement("option");
opt.text = "Select language";
opt.disabled = true;
countrySelecter.add(opt, null);
let i = 0;
for (let item of data) {
let opt = document.createElement("option");
opt.value = item.Id;
opt.text = `${i++}. ${item.Id} - ${item.Value}(${item.Comment})`;
countrySelecter.add(opt, null);
}
return countrySelecter;
};
Here's an ES6 version, conversion to vanilla JS shouldn't be too hard but I already have jQuery anyways:
function select(options, selected) {
return Object.entries(options).reduce((r, [k, v]) => r.append($('<option>').val(k).text(v)), $('<select>')).val(selected);
}
$('body').append(select({'option1': 'label 1', 'option2': 'label 2'}, 'option2'));
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/1.9.0/jquery.min.js"></script>
const cars = ['Volvo', 'Saab', 'Mervedes', 'Audi'];
let domSelect = document.createElement('select');
domSelect.multiple = true;
document.getElementsByTagName('body')[0].appendChild(domSelect);
for (const i in cars) {
let optionSelect = document.createElement('option');
let optText = document.createTextNode(cars[i]);
optionSelect.appendChild(optText);
document.getElementsByTagName('select')[0].appendChild(optionSelect);
}
it's very simple yet tricky but here is what you wanted, hope it's helpful :
this function generates a select list from 1990 to 2018
i think this example can help ya, if you want to add any other value just
change value of x and y ;)
function dropDown(){
var start = 1990;
var today = 2019;
document.write("<select>");
for (var i = start ; i <= today; i++)
document.write("<option>" + i + "</option>");
}
document.write("</select>");
dropDown();

Javascript. Change a form option based on a previous one

I'm trying to change the options that appear in my select box named session when a certain option is picked in my select box named movie.
Here's the script I've got so far.
<script>
var optionList = document.getElementsByName("movie")[0];
var movieList = ["AC", "CH", "AF", "RC"];
for(var i = 0; i < movieList.length; i++){
var movie = movieList[i];
var option = document.createElement("option");
option.textContent = movie;
option.value = movie;
optionList.appendChild(option);
}
</script>
<script>
var sessionList = document.getElementsByName("session")[0];
var actionSession = ["WED-09", "THU-09", "FRI-09", "SAT-09", "SUN-09"];
var childrenSession = ["MON-01", "TUE-01", "WED-06", "THU-06", "FRI-06", "SAT-12", "SUN-12"];
var foreignSession = ["MON-06", "TUE-06", "SAT-06", "SUN-06"];
var romanticSession = ["MON-09", "TUE-09", "WED-01", "THU-01", "FRI-01", "SAT-06", "SUN-06"];
if(document.getElementsByName("movie")[0].value === movieList[0])
{
for(var i = 0; i < actionSession.length; i++){
var session = actionSession[i];
var option = document.createElement("option");
option.textContent = session;
option.value = session;
sessionList.appendChild(option);
}
}
</script>
Consider changing the Sessions to an object, like so:
var sessions = {
"AC": ["WED-09", "THU-09", "FRI-09", "SAT-09", "SUN-09"],
"CH": ["MON-01", "TUE-01", "WED-06", "THU-06", "FRI-06", "SAT-12", "SUN-12"],
"AF": ["MON-06", "TUE-06", "SAT-06", "SUN-06"],
"RC": ["MON-09", "TUE-09", "WED-01", "THU-01", "FRI-01", "SAT-06", "SUN-06"]
}
This way, you can use the onchange of your select tag to get the value of the selected option and reference the list of sessions for the appropriate movie list as such:
var category = document.getElementByName("movie").value;
var currentSession = sessions[category];
for(var i = 0; i < currentSession.length; i++){
var session = currentSession[i];
var option = document.createElement("option");
option.textContent = session;
option.value = session;
sessionList.appendChild(option);
}
Objects in javascript can be referenced as "key" => "value" pairs simply by following the syntax:
object = { "key": value }, and value's type can be anything - even another Object!
You can even declare object keys like such:
var sessions = {};
sessions['AC'] = [...];
sessions['CH'] = [...];
sessions.AF = [...];
sessions.RC = [...];
That's right - all of the above declarations can be referenced as sessions['xx']
Hope this simplifies things a bit.
You could create a dictionary mapping elements of movieList to lists of <option> elements, maybe?
You might call the dictionary sessionOptions. You would then change all the children of #session at once - so this would go in your onchange handler for sessionList:
var sessionList = document.getElementsByName("session")[0];
var chosenMovie = "..."; // "AC", for instance
// Remove all elements from sessionList
while(sessionList.firstChild) {
sessionList.removeChild(sessionList.firstChild);
}
// Add the chosen movie options
var chosenMovieOptions = sessionOptions[chosenMovie];
for(var i = 0; i < chosenMovieOptions.length; i++) {
sessionList.appendChild(chosenMovieOptions[i]);
}
You would also want to make a mapping of movie codes to session lists:
var SESSION_LISTS = {
"AC": ["WED-09", "THU-09", "FRI-09", "SAT-09", "SUN-09"],
"CH": ["MON-01", "TUE-01", "WED-06", "THU-06", "FRI-06", "SAT-12", "SUN-12"],
"AF": ["MON-06", "TUE-06", "SAT-06", "SUN-06"],
"RC": ["MON-09", "TUE-09", "WED-01", "THU-01", "FRI-01", "SAT-06", "SUN-06"]
};
Then, to build sessionOptions, for each "session string list" (such as actionSession), you would loop through the session list and create elements:
var currentSession = "..."; // currentSession is the current session list - "AC", for instance
var currentSessionOptions = SESSION_LISTS[currentSession];
sessionOptions[currentSession] = [];
for(var i = 0; i < currentSessionOptions.length; i++){
var session = currentSessionOptions[i];
var option = document.createElement("option");
option.textContent = session;
option.value = session;
sessionOptions[currentSession].append(option);
}
But then you would do this for every sublist in SESSION_LISTS, so you would put this code in some initializer function:
var sessions = Object.keys(SESSION_LISTS);
for(var i = 0; i < sessions.length; i++) {
currentSession = sessions[i];
// the code snippet above
}

Add onclick event to options in select drop down dynamically

I have a drop down list created from an array in JavaScript. I want to do something with the selected value when I change the dropdown value.
var newArray = [3,5,4,6]
var container = document.getElementById('container')
var dropdown = creatSelectDropDown('thisDropdown', newArray)
container.appendChild(dropdown)
function creatSelectDropDown(id, array) {
var dropdown = document.createElement("select");
dropdown.id = id;
for (var i = 0; i < array.length; i++) {
var option = document.createElement("option");
option.text = array[i];
option.value = array[i];
dropdown.options.add(option);
}
return dropdown;
}
So in the above code I would either have :
option.onclick = dosomething();
Or
dropdown.onchange = dosomething(getvalueofoptiontag);
I'm obviously missing something simple here ...
Fiddle to play with : https://jsfiddle.net/reko91/hnLxt4xh/1/
Can bind a function to change with this syntax:
dropdown.onchange = function(event) {
console.log(event);
}
or using eventListener:
dropdown.addEventListener("change", function(event) {
console.log(event);
}, false);
What you are doing wrong is that you have to pass a function to the onchange event, like:
var dosomething = function() { /* do something */}
dropdown.onchange = dosomething;

Populating a form with names from a .txt file

I am trying to populate a dropdown list with a bunch of names that are stored in a .txt in the same directory as the HTML code. Each name is on a new line of this file and"names" is the id of the dropdown that will store the names.
Upon loading the page, the list is not populated at all. Any guidance would be awesome.
<script type = "text/javascript">
window.onload = function () {
var select = document.getElementById("names");
var textFile = "/names.txt";
jQuery.get(textFile, function(textFileData) {
var EachLineInTextFile = textFileData.responseText.split(",");
for (var i = 0, len = EachLineInTextFile.length; i < len; i++) {
var option = document.createElement('option');
option.text = option.value = EachLineInTextFile[i];
select.add(option, 0);
};
};
};
</script>
Thanks!
It looks like the major issue was that I needed a better version of jquery. Thank you everyone for your help!
<script type = "text/javascript">
window.onload = function () {
var select = document.getElementById("names");
var textFile = "/names.txt";
jQuery.get(textFile, function(textFileData) {
window.alert(textFileData);
var EachName= textFileData.split("\n");
for (var i = 0, len = EachName.length; i < len; i++) {
var option = document.createElement('option');
option.text = option.value = EachName[i];
select.add(option, 0);
};
});
};
</script>

Dynamically Change Option Set Values in CRM

I am using CRM Online 2013.
I am trying to remove 3 values from an optionset under a certain condition.
The optionset has six options by default: they are listed at the top of my JS code below.
When I run my code, the correct amount of options appear; but they all say undefined.
Here is what I have at the moment:
var customer = 100000000;
var partner = 100000001;
var partnerCustomer = 100000002;
var customerAndBeta = 100000003;
var partnerAndBeta = 100000004;
var partnerCustomerAndBeta = 100000005;
function populateBetaOptionSet(beta) {
var options = Xrm.Page.getAttribute("intip_websiteaccess").getOptions();
var pickListField = Xrm.Page.getControl("intip_websiteaccess");
for(i = 0; i < options.length; i++)
{
pickListField.removeOption(options[i].value);
}
if (beta == false) {
pickListField.addOption(customer);
pickListField.addOption(partner);
pickListField.addOption(partnerCustomer);
}
pickListField.addOption(customerAndBeta);
pickListField.addOption(partnerAndBeta);
pickListField.addOption(partnerCustomerAndBeta);
}
This is being called from another function which is wired up to a separate field's onchange event. I am sure this is working correctly as I am getting the correct beta value through when it is called.
I am removing all the options before re-adding them to avoid duplicates.
Any idea what I am doing wrong here/or know of a better way of doing this?
Re-wrote your function to match the criterion. The option is an object with both text and value. This is why you see undefined (missing text);
So instead of
var customer = 100000000
it needs to be
var customer = { value : 100000000 , text : "Customer" };
The code below saves each option in global scope and uses it each time you call populateBetaOptionSet
function populateBetaOptionSet(beta) {
var xrmPage = Xrm.Page;
var pickListField = xrmPage.getControl("intip_websiteaccess");
var options = pickListField.getOptions();
//save all options
if (!window.wsOptions)
{
window.wsOptions = {};
wsOptions.customer = pickListField.getOption(100000000);
wsOptions.partner = pickListField.getOption(100000001);
wsOptions.partnerCustomer = pickListField.getOption(100000002);
wsOptions.customerAndBeta = pickListField.getOption(100000003);
wsOptions.partnerAndBeta = pickListField.getOption(100000004);
wsOptions.partnerCustomerAndBeta = pickListField.getOption(100000005);
}
//clear all items
for(var i = 0; i < options.length; i++)
{
pickListField.removeOption(options[i].value);
}
if (beta == false) {
pickListField.addOption(wsOptions.customer);
pickListField.addOption(wsOptions.partner);
pickListField.addOption(wsOptions.partnerCustomer);
}
pickListField.addOption(wsOptions.customerAndBeta);
pickListField.addOption(wsOptions.partnerAndBeta);
pickListField.addOption(wsOptions.partnerCustomerAndBeta);
}
Example use Xrm.Page.getControl(..).addOption :
var low = {value : 100000000, text : "Low"};
var medium = {value : 100000001, text : "Medium"};
var high = {value : 100000002, text : "High"};
var pickList = Xrm.Page.getControl("control_name");
var options = pickList.getOptions();
for (var i = 0; i < options.length; i++)
pickList.removeOption(options[i].value);
pickList.addOption(low);
pickList.addOption(medium);
pickList.addOption(high);

Categories