I'm feeling my way around using JavaScript to populate a HTML5 page - ultimately to link into a Delphi / Datasnap page.
On my page I have a tag setup to provide a listbox as below:
<select id="FirmList" size="10"></select>
I then have a JavaScript script linked to a button that fires on the OnClick
function getJobFirms()
{
var sel = $("#FirmList");
//var sel = document.getElementByID("FirmList");
for (var i=0; i<10; i++) {
var opt = document.createElement('option');
opt.value = i;
opt.text = i+1;
sel.add(opt);
}
}
The above seems to work - in that Chrome reports no errors and loops through 10 times. However nothing appears in the listbox on the web page, and the length property of sel.option does not increment
I've tried to use other options such as addressing sel.opt directly with no luck
Any suggestions?
You need to use .append()
Insert content, specified by the parameter, to the end of each element in the set of matched elements.
Use
sel.append(opt);
instead of
sel.add(opt);
DEMO
The reason it doesn't work is because sel is a jQuery object, and you're trying to use the native select.add() method, which only works on the native element.
The easy way to fix that would be to do what you seem to have to tried, use getElementById, but you've typed it wrong.
function getJobFirms() {
var sel = document.getElementById("FirmList");
for (var i=0; i<10; i++) {
var opt = document.createElement('option');
opt.value = i;
opt.text = i+1;
sel.add(opt);
}
}
as you're already using jQuery, you could just do something like this
function getJobFirms() {
$("#FirmList").append(function() {
return $.map(' (. Y .) '.split(''), function(_,i) {
return $('<option />', {text : (i+1), value : i});
});
});
}
Use below jQuery script
function getJobFirms()
{
var sel = $("#FirmList");
//var sel = document.getElementByID("FirmList");
for (var i=0; i<10; i++) {
sel.append('<option value="'+i+'">'+(i+1)+'</option>');
}
}
Here is working JSFiddle
Since you're already using jQuery, you can use the following to make it more readable. As noted in the other questions, add is not a jQuery method and you need to use any variation of append.
function getJobFirms()
{
var sel = $("#FirmList");
for (var i=0; i<10; i++) {
$('<option/>', {text: i + 1, value: i})
.appendTo(sel);
}
}
Demo
Use append();
var sel = $("#FirmList");
for (var i=0; i<10; i++) {
var opt = document.createElement('option');
opt.value = i;
opt.text = i+1;
sel.append(opt);
}
OR DEMO JQUERY
var sel = $("#FirmList");
for (var i=0; i<10; i++) {
sel.append($('<option/>',{'text' : i+1},{"value":i}));
//OR
sel.append("<option value='"+i+"'>"+(i+1)+"</option>")
}
Related
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;
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!
var test = document.body.getElementsByTagName("a");
for (var i=0; i<test.length; i++)
if(test[i].innerHTML().indexOf("search string") != -1){test[i].style.color="black";}
Hopefully it's obvious what I'm trying to do - if there is a link on the page that contains the search phrase, change it's color to black. This isn't working though. Any ideas?
Thanks.
innerHTML is a property not a function, so don't use ().
innerHTML is not a function, it is a property. Try doing this instead:
var test = document.body.getElementsByTagName("a");
for (var i=0; i<test.length; i++)
if(test[i].innerHTML.indexOf("search string") != -1){test[i].style.color="black";}
A cleaner way of doing it would be to use jQuery:
var searchTerm = 'term1';
$('a').filter(function (a) {
if (this.innerHTML.indexOf(searchTerm) != -1)
return true;
return false;
}).css('color','red')
var test = document.body.getElementsByTagName("a");
for (var i=0; i<test.length; i++) {
var newElem = test[i].innerHTML;
if(newElem.indexOf("searchString") != -1){
test[i].style.color="black";
}
}
​innerHTML is no function! It's a property!
I'm writing a script for CasperJS. I need to click on the link that contains a span with "1". In jQuery can be used :contains('1'), but what the solution is for selectors in pure Javascript?
HTML: <a class="swchItem"><span>1</span></a><a class="swchItem"><span>2</span></a>
jQuery variant: $('a .swchItem span:contains("1")')
UPD CasperJS code:
casper.then(function () {
this.click('a .swchItem *select span with 1*')
})
Since 0.6.8, CasperJS offers XPath support, so you can write something like this:
var x = require('casper').selectXPath;
casper.then(function() {
this.click(x('//span[text()="1"]'))
})
Hope this helps.
Try the following. The difference between mine and gillesc's answer is I'm only getting a tags with the classname you specified, so if you have more a tags on the page without that class, you could have unexpected results with his answer. Here's mine:
var aTags = document.getElementsByTagName("a");
var matchingTag;
for (var i = 0; i < aTags.length; i++) {
if (aTags[i].className == "swchItem") {
for (var j = 0; j < aTags[i].childNodes.length; j++) {
if (aTags[i].childNodes[j].innerHTML == "1") {
matchingTag = aTags[i].childNodes[j];
}
}
}
}
var spans = document.getElementsByTagName('span'),
len = spans.length,
i = 0,
res = [];
for (; i < len; i++) {
if (spans.innerHTML == 1) res.push(spans[i]);
}
Is what you have to do unless the browser support native css queries.
jQuery is javascript. There are also a number of selector engines available as alternatives.
If you want to do it from scratch, you can use querySelectorAll and then look for appropriate content (assuming the content selector isn't implemented) and if that's not available, implement your own.
That would mean getting elements by tag name, filtering on the class, then looking for internal spans with matching content, so:
// Some helper functions
function hasClass(el, className) {
var re = new RegExp('(^|\\s)' + className + '(\\s|$)');
return re.test(el.className);
}
function toArray(o) {
var a = [];
for (var i=0, iLen=o.length; i<iLen; i++) {
a[i] = o[i];
}
return a;
}
// Main function
function getEls() {
var result = [], node, nodes;
// Collect spans inside A elements with class swchItem
// Test for qsA support
if (document.querySelectorAll) {
nodes = document.querySelectorAll('a.swchItem span');
// Otherwise...
} else {
var as = document.getElementsByTagName('a');
nodes = [];
for (var i=0, iLen=as.length; i<iLen; i++) {
a = as[i];
if (hasClass(a, 'swchItem')) {
nodes = nodes.concat(toArray(a.getElementsByTagName('span')));
}
}
}
// Filter spans on content
for (var j=0, jLen=nodes.length; j<jLen; j++) {
node = nodes[j];
if ((node.textContent || node.innerHTML).match('1')) {
result.push(node);
}
}
return result;
}
Given an HTML form element like:
<select id='mydropdown'>
<option value='foo'>Spam</option>
<option value='bar'>Eggs</option>
</select>
I know I can select the first option with
document.getElementById("mydropdown").value='foo'
However, say I have a variable with the value "Spam"; can I select a dropdown item by its text rather than by its value?
var desiredValue = "eggs"
var el = document.getElementById("mydropdown");
for(var i=0; i<el.options.length; i++) {
if ( el.options[i].text == desiredValue ) {
el.selectedIndex = i;
break;
}
}
I'd use the selectedIndex or a loop to select the option by text, the code below doesn't work.
document.getElementById("mydropdown").text = 'Eggs';
If you want to get an option by its innertext and not by the value you can do this:
function go(){
var dropdown = document.getElementById('mydropdown');
var textSelected = 'Spam';
for(var i=0, max=dropdown.children.length; i<max; i++) {
if(textSelected == dropdown.children[i].innerHTML){
alert(textSelected);
return;
}
}
}
Older IE does not handle options of a select as child nodes, but all browsers implement the text property of a select's option collection.
function selectbytext(sel, txt){
if(typeof sel== 'string'){
sel= document.getELementById(sel) || document.getELementsByName(sel)[0];
}
var opts= sel.options;
for(var i= 0, L= opts.length; i<L; i++){
if(opts[i].text== txt){
sel.selectedIndex= i;
break;
}
}
return i;
}