loop for select box value - javascript

I want to create loop in select box. But I want one code for different select.
I am able create for one select but I want for multiple .
for single: with id
I want to change this code according class or for multiple select.
My code for this:
<select class="foo"></select><select class="foo"></select>
and:
$(document).ready(function() {
var elm = document.getElementByClass('foo'),
df = document.createDocumentFragment();
for (var i = 0; i <= 60; i++) {
var option = document.createElement('option');
option.value = i;
option.appendChild(document.createTextNode(" " + i));
df.appendChild(option);
}
elm.appendChild(df);
});

I think what you want is
document.getElementsByClassName('foo');
http://jsfiddle.net/5J29g/48/

Since you are using jQuery, so you could do like:
The demo.
$('.foo').each(function() {
for (var i = 0; i <= 60; i++) {
$('<option />').val(i).html('#option ' + i).appendTo($(this));
}
});

You can use class selector along with .append() and .clone()
$(document).ready(function () {
var df = document.createDocumentFragment();
for (var i = 0; i <= 60; i++) {
var option = document.createElement('option');
option.value = i;
option.appendChild(document.createTextNode(" " + i));
df.appendChild(option);
}
$('.foo').append(function () {
return $(df).clone()
})
});
Demo: Fiddle

I just updated your jsfiddle adding this:
(function() {
var foos=document.querySelectorAll(".foo");
for(var j=0;j<foos.length;j++){
var elm = foos[j],
df = document.createDocumentFragment();
for (var i = 1; i <= 42; i++) {
var option = document.createElement('option');
option.value = i;
option.appendChild(document.createTextNode("option #" + i));
df.appendChild(option);
}
elm.appendChild(df);
}
}());
sample check that out, DEMO

Try this:
$('.foo').each(function(){
// call your code create option element here with $(this).append()
});

Related

Concatenating text to options with a certain data attribute value

I have a select element:
function find() {
var schoolList = document.getElementByID("schoolList");
if (schoolList.hasAttributes("[data attribute value]") {
//modify text in found option
};
};
find();
<div id="SelectWrapper" class="menu">
<form>
<select id="schoolList">
<option value='student' data-tier="student" data->Student 1</option>
<option value="teacher" data-tier="faculty" data->Teacher</option>
</form>
</div>
Using pure Javascript, I want to create an if statement within a function that checks to see if an option has an appropriate data attribute value (for instance, "student" or "faculty") and then adds to or modifies the existing innerHTML/text.
You can use querySelectorAll() to find all the options with a particular data value, then loop over them.
function find() {
var options = document.querySelectorAll("#schoolList option[data-tier=student]");
for (var i = 0; i < options.length; i++) {
options[i].innerHTML += " (something)";
}
}
The example for you
function find() {
var schoolList = document.getElementById("schoolList");
if (schoolList.hasAttributes("[data attribute value]")) {
var opts = schoolList.getElementsByTagName("option");
for (var i = 0, len = opts.length; i < len; i++) {
var option = opts[i];
// modify
if (option["data-tier"] === "student") {
option.text = "new text content"
}
}
// add new
for (var i =0; i < 5; i++) {
var opt = document.createElement("option");
opt.value = i;
opt.innerHTML = "Option " + i;
schoolList.appendChild(opt);
}
};
};
find();

Selected attribute in option tag

I have a dropdown that's populated through a loop. The selected attribute should be added when <%if o.getNextPage()%> is equal to i.
<select id="dropDown" onchange="display(this.value)">
var start = 1;
var end = noOfPages;
var options = "";
for (var i = start; i <= end; i++) {
options += "<option>" + i + "</option>";
}
document.getElementById("dropDown").innerHTML = options;
function display(e) {
document.getElementById("hidden").value = e;
document.invoiceForm.submit();
}
You can add value attribute to the option tag.
As suggested by #3Dos in comments you can use ‘document.createElement‘ without needing to insert raw HTML like this:
var start = 1;
var end = noOfPages;
var options = "";
for (var i = start; i <= end; i++) {
var opt = document.createElement('option');
opt.value = i;
opt.innerHTML = i;
document.getElementById('dropDown').appendChild(opt);
}
This is the proper way of generating your dropdown list and preserve performance as you interact with the DOM only once thanks to the documentFragment
// These were not provided by OP but added to actually get this snippet running
var noOfPages = 5;
var start = 1;
var end = noOfPages;
var options = document.createDocumentFragment();
for (var i = start; i <= end; i++) {
var option = document.createElement('option');
option.value = i;
option.textContent = i;
options.appendChild(option);
}
document.getElementById("dropDown").appendChild(options);
<select id="dropDown" onchange="display(this.value)"></select>
I omitted the display function which is irrelevant as it refers to unprovided code.

populate number array with dropdown list

I have found several links to populate a dropdown list with an array but none of them work for me. Some links I have tried include:
This similar Stack Overflow question:
JavaScript - populate drop down list with array
This similar situation:
Javascript:
var cuisines = ["Chinese","Indian"];
var sel = document.getElementById('CuisineList');
for(var i = 0; i < cuisines.length; i++) {
var opt = document.createElement('option');
opt.innerHTML = cuisines[i];
opt.value = cuisines[i];
sel.appendChild(opt);
}
and the HTML:
<select id="CuisineList"></select>
But nothing is working. My goal is to populate a dropdown list from an external javascript array with values 0 to 255 so they can be used to come up with an RGB scheme. This is similar to the question that has been linked, but the linked question does not work when I copy and paste it into my text editor and preview it in Chrome.
try this:
i think your dom not ready when script executed
function ready() {
var cuisines = ["Chinese","Indian"];
var sel = document.getElementById('CuisineList');
for(var i = 0; i < cuisines.length; i++) {
var opt = document.createElement('option');
opt.innerHTML = cuisines[i];
opt.value = cuisines[i];
sel.appendChild(opt);
}
}
document.addEventListener("DOMContentLoaded", ready);
<select id="CuisineList"></select>
try this
var cuisines = ["Chinese","Indian"];
var innerData = '';
for(var i = 0; i < cuisines.length; i++) {
innerData += '<option value="' + 'cuisines[i]' + '">' + 'cuisines[i]' + '</option>';
}
document.getElementById('CuisineList').innerHTML = innerData;

How to display JSON objects as options of a dropdown in HTML, using a common JavaScript funciton for all objects

I have two sets of data in a JSON file (ACodes and BCodes), which I want to read and display as the options of two different dropdowns in an HTML file. I want to have one common JavaScript function that I can use to get along with the same (shown below) but I am not getting the desired output.
Help about where I am going wrong is much appreciated!
HTML
<script>
var select, option, arr, i;
function loadJSON(var x){
if(x.match == "A"){
array = JSON.parse(ACodes);
select = document.getElementById('dd1');
for (i = 0; i < array.length; i++) {
option = document.createElement('option');
option.text = array[i]["Code"];
select.add(option);
}
}
else if(x.match == "B"){
array = JSON.parse(BCodes);
select = document.getElementById('dd2');
for (i = 0; i < array.length; i++) {
option = document.createElement('option');
option.text = array[i]["Curr"];
select.add(option);
}
}
}
</script>
<body onload="loadJSON('A');laodJSON('B')">
<select id="dd1"></select>
<select id="dd2"></select>
</body>
JSON
ACodes = '[{"Code":"BHAT"}, {"Code":"MALY"}]';
BCodes = '[{"Curr":"CAC"},{"Curr":"CAD"}]';
remove var at loadJSON(var x) => loadJSON(x)
remove .match at x.match == "A", you seems to want to compare x with specific value, not testing it as regexp, so change to x === "A"
laodJSON('B'); at body onload is typo.
There's some reusable codes, you can attract the value depends on x and make the code shorter. This step is not a must do, as it won't cause your origin code unable to work.
<body onload=" loadJSON('A');loadJSON('B');">
<select id="dd1"></select>
<select id="dd2"></select>
<script>
var select, option, arr, i;
var ACodes = '[{"Code":"BHAT"}, {"Code":"MALY"}]';
var BCodes = '[{"Curr":"CAC"},{"Curr":"CAD"}]';
function loadJSON(x){
var array, select, target;
if (x === 'A') {
array = JSON.parse(ACodes);
select = document.getElementById('dd1');
target = 'Code';
} else if (x === 'B') {
array = JSON.parse(BCodes);
select = document.getElementById('dd2');
target = 'Curr';
}
for (i = 0; i < array.length; i++) {
option = document.createElement('option');
option.text = array[i][target];
select.add(option);
}
}
</script>
</body>
Edit: to create it more dynamically, you can make the function accept more params, so you can have more control over it. Demo is on jsfiddle.
// Append options to exist select
function loadJSON(jsonObj, key, selectId) {
var arr = JSON.parse(jsonObj);
// Get by Id
var select = document.querySelector('select#' + selectId);
// Loop through array
arr.forEach(function(item) {
var option = document.createElement('option');
option.text = item[key];
select.add(option);
});
}
// Append select with id to target.
function loadJSON2(jsonObj, key, selectId, appendTarget) {
// Get the target to append
appendTarget = appendTarget ? document.querySelector(appendTarget) : document.body;
var arr = JSON.parse(jsonObj);
// Create select and set id.
var select = document.createElement('select');
if (selectId != null) {
select.id = selectId;
}
// Loop through array
arr.forEach(function(item) {
var option = document.createElement('option');
option.text = item[key];
select.add(option);
});
appendTarget.appendChild(select);
}
<script>
var select, option, arr, i;
var ACodes = '[{"Code":"BHAT"}, {"Code":"MALY"}]';
var BCodes = '[{"Curr":"CAC"},{"Curr":"CAD"}]';
function loadJSON(x){
if(x == "A"){
array = JSON.parse(ACodes);
select = document.getElementById('dd1');
for (i = 0; i < array.length; i++) {
option = document.createElement('option');
option.text = array[i]["Code"];
select.add(option);
}
}
else if(x == "B"){
array = JSON.parse(BCodes);
select = document.getElementById('dd2');
for (i = 0; i < array.length; i++) {
option = document.createElement('option');
option.text = array[i]["Curr"];
select.add(option);
}
}
}
</script>
<body onload='loadJSON("A");loadJSON("B")'>
<select id="dd1"></select>
<select id="dd2"></select>
</body>
Now this code will work.
The match() method searches a string for a match against a regular expression. So match() function will not work here. You have to use equal operator for get this done.
I hope, This will help you.
You were well on your way, you just need to make it more dynamic :)
function loadOptions(json) {
json = JSON.parse(json);
var select = document.createElement('select'), option;
for (var i = 0; i < json.length; i++) {
for (var u in json[i]) {
if (json[i].hasOwnProperty(u)) {
option = document.createElement('option');
option.text = json[i][u];
select.add(option);
break;
}
}
}
return select;
}
And to use it:
document.body.appendChild(loadOptions(ACodes));
document.body.appendChild(loadOptions(BCodes));
FIDDLE
http://jsfiddle.net/owgt1v2w/
The answers above will help you, but im strongly recommend you to check some javascript's frameworks that can help you with that kind of situation.. The one im using is knockout.js (http://knockoutjs.com/)
Take a look in the documentation, also there a lot of topics related in stackoverflow http://knockoutjs.com/documentation/options-binding.html
Regards!

how to implement onchange function in dynamically generated select tag

var el_s = document.createElement('select');
for(var i=1;i<32;i++)
{
var j = i;
j = document.createElement('option');
j.text=i;
el_s.appendChild(j);
}
table.appendChild(el_s);
i have to generate dynamically select tag and onchange method
how to implement onchange function in select tag so that i get the selected value from the dropdown
How about:
el_s.onchange = function() {
alert("jey");
}
Demo: http://jsfiddle.net/tymeJV/kyfnc/
var el_s = document.createElement('select');
for(var i=1;i<32;i++)
{
var j = i;
j = document.createElement('option');
j.text=i;
el_s.appendChild(j);
}
$(el_s).change(function(){
//your function code
alert("hi");
});
table.appendChild(el_s);

Categories