Select options to be a for result - javascript

So, I basically have a for in javascript with the variable i that goes from 0 to 23
for($i=0; $i <= 23; $i++)
And I want to clear the current select options of the select that I have (only 1 and 2)
<select id="hour_interview_ini">
<option>1</option>
<option>2</option>
</select>
And add the for result in javascript as the new options (in this case, the options would be 0 to 23)

I primarily use jQuery, so this is what that would look like. I'll make a codepen too, for you. We've all be new to a language before so I totally get not being able to troubleshoot by yourself!
To clear the list you'll want to do something like this:
$('#hour_interview_ini')
.find('option')
.remove()
.end()
;
And then to add in a loop, you'll want to do this:
for(i = 0; i <= 23; i++){
$('#hour_interview_ini').append('<option value="' + i + '">' + i + '</option>')
}
However, If you want to do it in javascript, this will work too. I put these ones in as functions (although the jquery could be functions too). If you need to know how to call them, check the code pen. It'll show you how to use the function on a click, or how to access the jQuery ID and trigger a function:
Clearing list (not the best method, but works and is super small):
function clearList(){
document.getElementById("hour_interview_ini").innerHTML = "";
}
Adding through the loop
function addList(){
var select = document.getElementById("hour_interview_ini");
for (var i = 0; i<=23; i++){
var opt = document.createElement('option');
opt.value = i;
opt.innerHTML = i;
select.appendChild(opt);
}
}
https://codepen.io/humanhickory/pen/NWKQLyR

Related

Dynamically Add Select Options with Javascript

So I've been working on trying to populate a select tag options with JavaScript. I can't seem to figure out why my function isn't working any help would be greatly appreciated.
My HTML code:
<select name="options" id="options" style="width: 100px;" onchange="chooseOption(this);">
</select>
And my JavaScript function:
function chooseOption(){
var choices = {"Gym","Pool","Sports"};
var myChoice = "";
for(i=0; i<=choices.length; i++){
myChoice += "<option value='"+choices[i]+"'>"+choices[i]+"</option>";
document.getElementById("options").innerHTML = myChoice;
}
}
Thanks again
I would go with something like.
Is not really tested but am pretty sure is more reliable.
var option = document.createElement("option");
for(i=0; i<=choices.length; i++){
option.text = choices[i];
option.value = choices[i];
document.getElementById("options").appendChild = myChoice;
}
You're attempting to create an object instead of an array here:
var choices = {"Gym","Pool","Sports"}; // change {} to [] to create an array
Curly braces - {} are used to denote that you are creating an object.
Brackets - [] are used to denote an array.
Try populating your select element as it's being created with something like this:
<select name="options" id="options" style="width: 100px;">
<script>
var choices = ["Gym","Pool","Sports"];
var myChoice = "";
for(var i=0; i < choices.length; i++) {
myChoice += "<option value='"+choices[i]+"'>"+choices[i]+"</option>";
document.getElementById("options").innerHTML = myChoice;
}
</script>
</select>
Firstly, you have a huge error.
You don't use { and } in javascript to create arrays.
Use:
var choices = ["Gym","Pool","Sports"];
Here is your final code:
<script>
function chooseOption() {
var choices = ["Gym", "Pool", "Sports"];
var myChoice = "";
for (i = 0; i <= choices.length; i++) {
myChoice += "<option value='" + choices[i] + "'>" + choices[i] + "</option>";
document.getElementById("options").innerHTML = myChoice;
}
}
</script>
<select name="options" id="options" style="width: 100px;" onclick="javascript:chooseOption(this);">
</select>
Update
If you want it to work on JSFiddle firstly you need to make your function globally available because JSFiddle runs it at domready. To make it globally available just write it like this: window.choseOption = function() { /* code here */ };.
You should read a bit on DOM events. The change event on that select won't fire up until you have selected something. And since you have nothing to select the event will not fire.
You can run the function at onclick or just run it when the DOM is ready.
I have updated your fiddle.

get value in javascript from select tag

I am using a javascript function to get the id from a particular <select></select>.
<select name="no" id="dropdownlist" class="defaultvalue" style="width: 100%;">
<option value="">Select Option</option>
</select>
But the problem is I have 8 <select></select> for dropwdown and i want to get the value of these in the javascript like:
var list = document.getElementById('dropdownlist');
But this is only possible through using getElementByClass but this is not working for me. Any help would be appreciated.
Due you tagged your question with jquery I suggest you using it:
$('#dropdownlist').val();
UPDATE: But if you have 8 selects - just use same class for them and you can use next code:
$('.className').each(function(i,el){
console.log($(this).val());
})
There is no getElementByClass, it's getElementsByClassName, but you might as well use querySelectorAll, which has better support
var list = [];
var elems = document.querySelectorAll('.defaultvalue');
for (var i=0; i<elems.length; i++) {
list.push( elems[i].value );
}
FIDDLE
in jQuery you can do
var list = $.map($('.defaultvalue'), function(el) { return el.value});
FIDDLE
And ID's are unique, they can not be used for more than one element in the same document
If you want to go with pure javascript with multi select tag, then use below code
Update
function getAllValue(){
var allSelectTags = document.getElementsByClassName("defaultvalue");
var selVal = [];
for(var i=0; i<allSelectTags.length; i++){
var value = allSelectTags[i].options[allSelectTags[i].selectedIndex].value;
selVal.push(value);
}
var result = "";
for(var j=0; j<selVal.length; j++){
result += selVal[j] + "<br />";
}
document.getElementById("result").innerHTML = result;
}
DEMO

Onchange drop down menu

How can i take a value when a user choose an option from a drop down menu(select) and add it with another choice of another drop down menu and output the total of a mark? I want this total to change automatically with on-change method. I have wrote my code in JavaScript using DOM to write the form! Can you help me please?
I would personally recommend doing this with AngularJs. If you are using Angular, simply assigning the DOM element with a model (ng-model) name and you can dynamically change the items inside of your dropdown in your javascript. Check out this very simple example:
http://plnkr.co/edit/?p=preview
and here is documentation on how to use the ng-change utility that comes with AngularJs:
http://docs.angularjs.org/api/ng.directive:ngChange
(edit: I guess I should describe what is happening in the example in more detail. Basically, what is inside of <div ng-controller="Controller"> will be tied to the controller called "Controller" in the script.js. By assigning ng-model="confirmed" to the checkbox, it ties a variable of the same name to the checkbox. As you can see a couple lines down, simply calling {{confirmed}} can call the value from html. Also, assigning ng-change="change()" to the element basically tells the controller to call the function, change(), whenever there is changes made to the element in question. Hope this helps)
This is using regular javascript.
function Total()
{
var e1 = document.getElementById("ObjectsIDValue1");
var e2 = document.getElementById("ObjectsIDValue2");
if(e1.selectedIndex < 0||e2.selectedIndex < 0 )
return;//nothing is selected in 1 of the dropdowns
var ValueUserSelected1= new Number(e1.options[e1.selectedIndex].value);
var ValueUserSelected2= new Number(e2.options[e2.selectedIndex].value);
var e3 = document.getElementById("TotalsIDValue");
e3.value = ValueUserSelected1+ValueUserSelected2;//assuming it's an input:text
};
And just add this to your select objects.
<Select id = "ObjectsIDValue1" onchange="Total();">
<option>1</option>
<option>2</option>
<option>3</option>
<option>4</option>
<!-- more option objects -->
</Select>
<Select id = "ObjectsIDValue2" onchange="Total();">
<option>5</option>
<option>6</option>
<option>7</option>
<option>8</option>
<!-- more option objects -->
</Select>
Note: This doesn't validate whats in your select is a number.
Edit: As you appear to be new here on Stack Overflow I'd like to mention that if you found this solved your problem please mark it as the accepted answer by giving it a check mark. Also if you found this helpful and have enough points to up-vote please do that too.
Hope this helps.
Edit2: From the OP's comment I think you're looking for this,
document.getElementById("ObjectsIDValue1").onchange = function(){Total()};
document.getElementById("ObjectsIDValue2").onchange = function(){Total()};
just add that after you define Total();
Edit3: I want to be forthcoming and explain that what you're looking to do is VERY ugly in regular Javascript to do. I would recommend a JS library such as JQuery where doing this is much cleaner and easier to code.
Anyway here is ALL the code needed to do this.
<script type = "text/javascript">
//Create Selects from an Array
function CreateSelectFromArray (SelectID, ArrayOfValues)
{
var Code="";
Code += "<Select id='"+SelectID+"'>";
for(var x = 0; x < ArrayOfValues.length; x++)
{
Code += "<option>";
Code += ArrayOfValues[x];
Code += "</option>";
}
Code += "</Select>";
return Code;
};
//Repopulate a select from a start and end value
function ChangeSelectFromValues (SelectID, StartValue,EndValue)
{
var Code="";
var SelectObject = document.getElementById(SelectID);
for(var x = StartValue; x <= EndValue; x++)
{
Code += "<option>";
Code += x;
Code += "</option>";
}
SelectObject.innerHTML = Code;
};
//Add up the values of 2 Selects (currently hardcoded)
function Total()
{
var e1 = document.getElementById("ObjectsIDValue1");
var e2 = document.getElementById("ObjectsIDValue2");
if(e1.selectedIndex < 0||e2.selectedIndex < 0 )
return;//nothing is selected in 1 of the dropdowns
var ValueUserSelected1= new Number(e1.options[e1.selectedIndex].value);
var ValueUserSelected2= new Number(e2.options[e2.selectedIndex].value);
var e3 = document.getElementById("TotalsIDValue");
e3.value = ValueUserSelected1+ValueUserSelected2;//assuming it's an input:text
};
var yourArray = [5,10,15];
var SelectCode="";
SelectCode += CreateSelectFromArray ('FirstSelect', yourArray);//create select with array values
SelectCode += CreateSelectFromArray ('SecondSelect', yourArray);//create select with array values
SelectCode += CreateSelectFromArray ('ObjectsIDValue1', [1,2,3,4,5]);//create select with default array
SelectCode += CreateSelectFromArray ('ObjectsIDValue2', [1,2,3,4,5]);//create select with default array
SelectCode += "<input id='TotalsIDValue'/>";
var doc = document.open("text/html","replace");
doc.writeln(SelectCode);
doc.close()
//Add events to the Selects for desired functionality
document.getElementById("FirstSelect").onchange = function(){
var e0 = document.getElementById("FirstSelect");
ChangeSelectFromValues('ObjectsIDValue1',1,new Number(e0.options[e0.selectedIndex].value));
};
document.getElementById("SecondSelect").onchange = function(){
var e0 = document.getElementById("SecondSelect");
ChangeSelectFromValues('ObjectsIDValue2',1,new Number(e0.options[e0.selectedIndex].value));
};
document.getElementById("ObjectsIDValue1").onchange = function(){Total()};
document.getElementById("ObjectsIDValue2").onchange = function(){Total()};
</script>
That's about as clean as you can get this in regular JavaScript
Note:
var doc = document.open("text/html","replace");
doc.writeln(SelectCode);
doc.close()
Can be replace with,
document.getElementById("PlaceYouWantTheSelects").innerHTML =SelectCode;
If you have a specific place in mind to put the selects.

Trouble parsing a select element

I have a dropdown in a Grid. This is how it looks like. Now I am
trying to get the name of the select tag.
var x = document.getElementsByTagName('select');
I need to get the name and
parse it in such a way to get this value 13442111. What's the best way to go about getting this information?
<td class="cl">
<select name="ctrlvcol%3DId%3Bctrl%3DTabListView%3Brow%3D13442111%3Btype%3Dtxt" onchange="getTypeValue(this.value,13442111)">
<option value="1025">TEST-AAAA</option>
<option selected="" value="1026">TEST-BBBB</option>
<option value="1027">TEST-CCCC</option>
</select>
</td>
var selectElements = document.getElementsByTagName('select');
var selectElementsLen = selectElements.length;
for (var i = 0; i < selectElementsLen; i++) {
// split row parts
var rowID = unescape(selectElements[i].name).split(';');
if (rowID.length >= 3) {
// trim meta
rowID = rowID[2].replace(/^row=/, '');
// validate row ID
if (/^[0-9]+$/.test(rowID)) {
console.log('Valid Row ID: ' + rowID);
// do whatever needs to be done
}
}
}
http://jsfiddle.net/N4sJv/
Here's the approach with regular expression only:
var selectElements = document.getElementsByTagName('select');
var selectElementsLen = selectElements.length;
for (var i = 0; i < selectElementsLen; i++) {
// extract Row ID
var rowID = unescape(selectElements[i].name).match(/(?:row=)([0-9]+)/);
if (rowID && (rowID.length >= 2)) {
rowID = rowID[1];
console.log('Valid Row ID: ' + rowID);
// do whatever needs to be done
}
}
http://jsfiddle.net/N4sJv/1/
Keep in mind that document.getElementsByTagName() may not be the best choice as it selects all specified elements in the DOM tree. You might want to use a framework such as jQuery to consider browser compatibilities and performance.
Here is a bit of code that may help you. This little snippet will work if and only if this is the only select element on the page. As the comments above state, it would be better to identify this element with an id. However, for your use case the following should work:
// Get all select elements (in this case the one) on the page.
var elems = document.getElementsByTagName("select");
// Select the first "select" element and retrieve the "name" attribute from it
var nameAttr = decodeURIComponent(elems[0].getAttribute("name"));
// Split the decoded name attribute on the ";" and pull the second index (3rd part)
var nameProp = nameAttr .split(';')[2];
// Substr the name prop from the equal sign to the the end
nameProp = nameProp.substr(nameProp .indexOf('=') + 1);

Best way to create a dynamic Select (Dropdown) list?

I'm using jQuery and jqGrid.
I'm trying to populate a select list dynamically, one for each row and I need to add a click event to it. When the select list is being populated I grab the index of the item I want selected, and then after all items are add I'm trying to set the selected item.
I've tried
$("#taskList")[0].selectedIndex = taskIndex;
$("#taskList").selectOptions(taskIndex, true);
$("#taskList").val(1); //Tried to see if I could select any index and no luck.
$("#taskList option[value=" + taskIndex + "]").attr("selected", true);
So this means I'm probably populating the list incorrectly...
var taskList = document.createElement("select");
var taskIndex = 0;
for (var i = 0; i < result.TaskTypes.length; i++) {
$(taskList).addOption(result.TaskTypes[i].TaskId, result.TaskTypes[i].TaskName);
if (result.TaskTypes[i].TaskName == rowData.TaskType)
taskIndex = i;
}
Is there a better way?
I tried this but I couldn't add the click event to it. The proper item was selected though.
var taskList = "<select name='taskList' Enabled='true'>";
for (var i = 0; i < result.TaskTypes.length; i++) {
if (result.TaskTypes[i].TaskName == rowData.TaskType)
taskList += "<option selected> " + result.TaskTypes[i].TaskName + "</option>";
else
taskList += "<option>" + result.TaskTypes[i].TaskName + "</option>";
}
taskList += "</select>";
The way I would have done it, is in your first example - instead of using the jQuery API for addOption, use the DOM API, like this:
var option = document.createElement("option");
option.innerHTML = result.TaskTypes[i].TaskName;
option.value = result.TaskTypes[i].TaskId;
option.onclick = myClickHandler;
taskList.add(option, null);
Then after the loop you can just use:
taskList.selectedIndex = taskIndex;
to have the select list positioned to your required default selection.
I haven't used jQuery extensively, but I think its a good idea not to neglect the DOM API - its often not as convenient as the shortcuts that jQuery and other libraries offer, but these extend DOM capabilities and should not come instead of the DOM.
You can set the selected index like this:
$("#taskList").selectedIndex = taskIndex;
Falling under the "better way" category, JQuery lets you use an each loop instead of creating the for loops manually.
jQuery.each(result.TaskTypes, function(i, val) {
$("#" + i).append(document.createTextNode(" - " + val));
});
Got it- a good solid 8 hours later.
var taskList = "<select name='taskList' Enabled='true' onClick='$(\"#hoursBx\").valid()' >";
for (var i = 0; i < result.TaskTypes.length; i++) {
if (result.TaskTypes[i].TaskName == rowData.TaskType)
taskList += "<option selected> " + result.TaskTypes[i].TaskName + "</option>";
else
taskList += "<option>" + result.TaskTypes[i].TaskName + "</option>";
}
taskList += "</select>";
I'm using jQuery's Validator to verify the value in the $("#hoursBx") (a text box in the current row).
Adding the onClick works.

Categories