How do I use JavaScript in my <select> options list? - html

How do I use
<select>
<option>numbers1-100</option>
</select>
I have to use 1 to 100 numbers in my option list.Typing all the options takes time and makes code bigger.I guess we have to use javascript to make it work using for loop and document write.But I dont know how to put the code in the right way.How do i list the options list using java script? I mean the java script should be beside my label;example
number : 1-1oo \\ here the options list should be printed
and number can be anywhere but the script should print options list beside the number.How do i make it ? Unable to figure it out.Been trying from an hour or so.

Place this function in your <script> tags or include it within a script. Than call the function, createSelectOption() whenever you need the select box to be created.
Here is how you would have it loaded on page load with just javascript: `
function createSelectOption() {
var select_option = '<select>';
for(i = 1; i <= 100; i++) {
select_option += '<option value=' + i + '>' + i + '</option>';
}
select_option += '</select>';
document.getElementById('div').innerHTML = select_option;
}
I have included a jsfiddle demo to show you that it should be working/

You shouldn't really use javascript for this, it would usually be better using a server-side language such as php. You could use a for loop or a while loop to do this quite easily

Here's one way to do this.
http://jsfiddle.net/ryh7k/1/
var selectEle = document.getElementById('mySelect'),
optionEle = undefined;
for (var i=1;i<=100;i++) {
optionEle = document.createElement('option');
optionEle.setAttribute('value', i.toString());
optionEle.innerText = i.toString();
selectEle.appendChild(optionEle);
}

Simplest case:
<select>
<script>
for (var i = 1; i < 101; i++) {
document.write('<option value="'+i+'">'+i+'</option>');
}
</script>
</select>
But there are of course problems with this. First, people without JS will not see any options and having a SCRIPT tag inside a SELECT is not that nice either.
<select id="container"></select>
<script>
var s = document.getElementById('container');
var opts = '';
for (var i = 1; i < 101; i++) {
opts += '<option value="'+i+'">'+i+'</option>';
}
s.innerHTML = opts;
</script>

Related

No matter what selection, each selection produces the same value data as the global variable

I'm trying to execute this and be able to get a different value for "new_id", the data is correct when getting this API call and there are 7 different id's. However, no matter what I select produces 7 as the new_id value. Please help, sorry for my noob question in advance!
I've tried making data[0] instead of data[i] but I really don't know where to start
var new_id = "";
$(document).ready(function () {
$.ajax({
"url":api_base+"/endpoint",
"type":"GET",
"contentType":"application/json",
"success":function(data){
var s = '<option value="-1">Please Select</option>';
for (var i = 0; i < data.length; i++) {
s += '<option value="' + data[i].check_id + '">' + data[i].check + '</option>';
new_id = data[i].check_id
}
$("#check_list").html(s);
}
});
I'd like to get a different result each time I select a different value.
#Dan Winnick - So where ever the select tag is, add these attributes - id="mySelect" onchange="dropDownChangeEvent()" and in js file add - function dropDownChangeEvent() { new_id = document.getElementById("mySelect").value; }

Google html creating a list from spreadsheet

I am trying to get a list to populate from a spreadsheet based on the question posted here Previous questioe posted by #Kron011and I'm struggling somewhat. I added these lines to my .gs file:
function getMenuListOne(){
return SpreadsheetApp.openbyId('spreadsheet_key').getSheetByName('sheet1')
.getRange(row, column, numRows, numColumns).getValues();
}
and I added these lines to my HTML file:
<select id="menu">
<option></option>
<option>Google Chrome</option>
<option>Firefox</option>
</select>
<script
src="//ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js">
</script>
<script>
// The code in this function runs when the page is loaded.
$(function() {
google.script.run.withSuccessHandler(showThings)
.getMenuListFromSheet();
google.script.run.withSuccessHandler(showMenu)
.getMenuListFromSheet();
});
function showThings(things) {
var list = $('#things');
list.empty();
for (var i = 0; i < things.length; i++) {
list.append('<li>' + things[i] + '</li>');
}
}
function showMenu(menuItems) {
var list = $('#menu');
list.find('option').remove(); // remove existing contents
for (var i = 0; i < menuItems.length; i++) {
list.append('<option>' + menuItems[i] + '</option>');
}
}
</script>
As ever my painfully limited experience is hampering my efforts. I can get a new menu box to appear and show the correct results I want but I cannot get an existing box to show the same list. The existing boxes code is currently:
<input type="text" name="site" list="depotslist" id="site" class="form-control" placeholder="Select depot/site" required>
<datalist id="depotslist">
<option value="one">
<option value="two">
</datalist>
but can someone please point me in the right direction of which parts of my existing menu box I need to change to get the two bits to communicate?
UPDATE 23 JULY
I added the following code to get the another list to operate from another source:
$(function() {
google.script.run.withSuccessHandler(showThings2)
.getMenuListSources();
google.script.run.withSuccessHandler(showMenu2)
.getMenuListSources();
});
function showThings2(things2) {
var list2 = $('#things2');
list.empty();
for (var i = 0; i < things2.length; i++) {
list2.append('<li>' + things2[i] + '</li>');
}
}
function showMenu2(menuItems2) {
var list2 = $('#menu2');
var box2 = $('#sourcelist');
list2.find('option').remove(); // remove existing contents
for (var i = 0; i < menuItems2.length; i++) {
list2.append('<option>' + menuItems2[i] + '</option>');
box2.append('<option>' + menuItems2[i] + '</option>');
}
}
with these lines in the .gs file:
var Bvals = SpreadsheetApp.openById(ssKey).getSheetByName('SourceCodes').getRange("C3:C").getValues();
var Blast = Avals.filter(String).length;
return SpreadsheetApp.openById(ssKey).getSheetByName('SourceCodes').getRange(3,3,Blast,1).getValues();
It would be similar to what you are doing with the element "menu". with jquery you can select the element of the box that contains the options and then append the new values. in this case it's id is: depotslist.
function showMenu(menuItems) {
var list = $('#menu');
var box = $('#depotslist');
list.find('option').remove(); // remove existing contents
for (var i = 0; i < menuItems.length; i++) {
list.append('<option>' + menuItems[i] + '</option>');
box.append('<option>' + menuItems[i] + '</option>');
}
As a difference with the element "menu" in this case the content will remain. This means that in the box you will see the options "one, two" and whatever you added because we are not removing the content like with this line
list.find('option').remove();
I'm not sure if this is exactly what you wanted to do, let me know if this doesn't help.

Parse JSON File for Option in HTML select box

I'm doing PhoneGap project for my company.. Here goes on..
I have json file named city.json
[{"CityID":1,"CityName":"Magelang"},{"CityID":2,"CityName":"Jayapura"},{"CityID":3,"CityName":"Aceh"}]
I only want to get this city data for the option in my html select box named "city".. I had searched on the web, but couldn't find any solution for this JSON pattern.. I have tried this code, but it didn't work..
$(document).ready(function(){
$.getJSON('city.json',
function(data){
var html = '';
var len = data.length;
for (var i = 0; i< len; i++) {
html += '<option value="' + data[i].CityID + '">' + data[i].CityName + '</option>';
}
$('#city').appendTo(html);
});
});
I have imported the jquery javascript plugin too.. I really have no idea to make it works..
Please help me..
Use .append() not .appendTo(). The way you are doing it you are trying to append $("city") to your html variable.

How can I pre-populate html form input fields from url parameters?

I have a vanilla html page which has a form in it. A requirement has come in to be able to pre-populate the form via the url. Something like:
http://some.site.com/somePage.html?forename=Bob&surname=Jones
I can't seem to find any simple solution to this. Can someone point me in the right direction with some javascript to accomplish this? Happy to use a javascript solution, but I'd prefer to avoid pulling in an entire library just for this single use (none are currently used). Thanks.
Use a custom query string Javascript function.
function querySt(ji) {
hu = window.location.search.substring(1);
gy = hu.split("&");
for (i=0;i<gy.length;i++) {
ft = gy[i].split("=");
if (ft[0] == ji) {
return ft[1];
}
}
}
var koko = querySt("koko");
Then assign the retrieved value to the input control; something like:
document.getElementById('mytxt').value = koko;
Are you using PHP? If so, that makes things much easier. Assuming your link as above, you can use:
<?php
$forename = $_GET['forename'];
$surname = $_GET['surname'];
?>
----------
<input id='forename' type='text' value='<?php echo $forename; ?>' >
<input id='surname' type='text' value='<?php echo $surname; ?>' >
That should pre-populate for you.
function getUrlVars()
{
var vars = [], hash;
var hashes = window.location.href.slice(window.location.href.indexOf('?') + 1).split('&');
for(var i = 0; i < hashes.length; i++)
{
hash = hashes[i].split('=');
vars.push(hash[0]);
vars[hash[0]] = hash[1];
}
return vars;
}
var get = getUrlVars();
//returns get['forename'] == bob; surname == jones
Here is the builtin way, for reference:
https://developer.mozilla.org/en-US/docs/Web/API/URL/searchParams
You can instantiate the current address's parameters as a URL object without importing any libraries as shown here:
let params = (new URL(document.location)).searchParams;
Then you can reference them directly:
let name = params.get('name');
Or you can cycle through them with a loop such as:
for (const [key, value] of params.entries()) {}

Insert a Link Using CSS

I'm hand-maintaining an HTML document, and I'm looking for a way to automatically insert a link around text in a table. Let me illustrate:
<table><tr><td class="case">123456</td></tr></table>
I would like to automatically make every text in a TD with class "case" a link to that case in our bug tracking system (which, incidentally, is FogBugz).
So I'd like that "123456" to be changed to a link of this form:
123456
Is that possible? I've played with the :before and :after pseudo-elements, but there doesn't seem to be a way to repeat the case number.
Not in a manner that will work across browsers. You could, however, do that with some relatively trivial Javascript..
function makeCasesClickable(){
var cells = document.getElementsByTagName('td')
for (var i = 0, cell; cell = cells[i]; i++){
if (cell.className != 'case') continue
var caseId = cell.innerHTML
cell.innerHTML = ''
var link = document.createElement('a')
link.href = 'http://bugs.example.com/fogbugz/default.php?' + caseId
link.appendChild(document.createTextNode(caseId))
cell.appendChild(link)
}
}
You can apply it with something like onload = makeCasesClickable, or simply include it right at the end of the page.
here is a jQuery solution specific to your HTML posted:
$('.case').each(function() {
var link = $(this).html();
$(this).contents().wrap('');
});
in essence, over each .case element, will grab the contents of the element, and throw them into a link wrapped around it.
Not possible with CSS, plus that's not what CSS is for any way. Client-side Javascript or Server-side (insert language of choice) is the way to go.
I don't think it's possible with CSS. CSS is only supposed to affect the looks and layout of your content.
This seems like a job for a PHP script (or some other language). You didn't give enough information for me to know the best way to do it, but maybe something like this:
function case_link($id) {
return '' . $id . '';
}
Then later in your document:
<table><tr><td class="case"><?php echo case_link('123456'); ?></td></tr></table>
And if you want an .html file, just run the script from the command line and redirect the output to an .html file.
You could have something like this (using Javascript). Inside <head>, have
<script type="text/javascript" language="javascript">
function getElementsByClass (className) {
var all = document.all ? document.all :
document.getElementsByTagName('*');
var elements = new Array();
for (var i = 0; i < all.length; i++)
if (all[i].className == className)
elements[elements.length] = all[i];
return elements;
}
function makeLinks(className, url) {
nodes = getElementsByClass(className);
for(var i = 0; i < nodes.length; i++) {
node = nodes[i];
text = node.innerHTML
node.innerHTML = '' + text + '';
}
}
</script>
And then at the end of <body>
<script type="text/javascript" language="javascript">
makeLinks("case", "http://bugs.example.com/fogbugz/default.php?");
</script>
I've tested it, and it works fine.
I know this is an old question, but I stumbled upon this post looking for a solution for creating hyperlinks using CSS and ended up making my own, could be of interest for someone stumbling across this question like I did:
Here's a php function called 'linker();'that enables a fake CSS attribute
connect: 'url.com';
for an #id defined item.
just let the php call this on every item of HTML you deem link worthy.
the inputs are the .css file as a string, using:
$style_cont = file_get_contents($style_path);
and the #id of the corresponding item. Heres the whole thing:
function linker($style_cont, $id_html){
if (strpos($style_cont,'connect:') !== false) {
$url;
$id_final;
$id_outer = '#'.$id_html;
$id_loc = strpos($style_cont,$id_outer);
$connect_loc = strpos($style_cont,'connect:', $id_loc);
$next_single_quote = stripos($style_cont,"'", $connect_loc);
$next_double_quote = stripos($style_cont,'"', $connect_loc);
if($connect_loc < $next_single_quote)
{
$link_start = $next_single_quote +1;
$last_single_quote = stripos($style_cont, "'", $link_start);
$link_end = $last_single_quote;
$link_size = $link_end - $link_start;
$url = substr($style_cont, $link_start, $link_size);
}
else
{
$link_start = $next_double_quote +1;
$last_double_quote = stripos($style_cont, '"', $link_start);
$link_end = $last_double_quote;
$link_size = $link_end - $link_start;
$url = substr($style_cont, $link_start, $link_size); //link!
}
$connect_loc_rev = (strlen($style_cont) - $connect_loc) * -1;
$id_start = strrpos($style_cont, '#', $connect_loc_rev);
$id_end = strpos($style_cont,'{', $id_start);
$id_size = $id_end - $id_start;
$id_raw = substr($style_cont, $id_start, $id_size);
$id_clean = rtrim($id_raw); //id!
if (strpos($url,'http://') !== false)
{
$url_clean = $url;
}
else
{
$url_clean = 'http://'.$url;
};
if($id_clean[0] == '#')
{
$id_final = $id_clean;
if($id_outer == $id_final)
{
echo '<a href="';
echo $url_clean;
echo '" target="_blank">';
};
};
};
};
this could probably be improved/shortened using commands like .wrap() or getelementbyID()
because it only generates the <a href='blah'> portion, but seeing as </a> disappears anyway without a opening clause it still works if you just add them everywhere :D