I am trying to create a HTML script that will pick a random number out of a list I have given when someone loads the page. This means if they refresh the page a new number will appear. I know how to generate a script that shows a random word/number when you press a button but it is necessary to make the number generate itself and also it can't be in a wordbox. If anyone can help me with this, I'd appreciate it.
I don't know much about coding but from the information I've gathered, here's what I have constructed:
<html>
<head>
<title></title>
<SCRIPT LANGUAGE="JavaScript">
<!--
// Use the following variable to specify
// the number of random words
var NumberOfWords = 32
var words = new BuildArray(NumberOfWords)
// Use the following variables to
// define your random words:
words[1] = "2,719"
words[2] = "2,718"
words[3] = "2,717"
words[4] = "2,715"
words[5] = "2,713"
words[6] = "2,711"
words[7] = "2,710"
words[8] = "2,709"
words[9] = "2,708"
words[10] = "2,706"
words[11] = "2,704"
words[12] = "2,702"
words[13] = "2,701"
words[14] = "2,700"
words[15] = "2,699"
words[16] = "2,698"
words[17] = "2,696"
words[18] = "2,694"
words[19] = "2,692"
words[20] = "2,690"
words[21] = "2,688"
words[22] = "2,686"
words[23] = "2,685"
words[24] = "2,683"
words[25] = "2,681"
words[26] = "2,678"
words[27] = "2,675"
words[28] = "2,673"
words[29] = "2,671"
words[30] = "2,669"
words[31] = "2,667"
words[32] = "2,664"
function BuildArray(size){
this.length = size
for (var i = 1; i <= size; i++){
this[i] = null}
return this
}
document.addEventListener("DOMContentLoaded",
function PickRandomWord(frm) {
// Generate a random number between 1 and NumberOfWords
var rnd = Math.ceil(Math.random() * NumberOfWords)
// Display the word inside the text box
frm.WordBox.value = words[rnd]
})
//-->
</SCRIPT>
<CENTER>
<FORM NAME="WordForm">
<INPUT TYPE=TEXT SIZE=50 NAME="WordBox"><BR>
</CENTER>
</FORM>
<body>
<big><big><span style="font-weight: bold;">
<br>
<br>
<br>
</span></big></big>
</body>
</html>
The problem is it doesn't work and I don't know why.
You should put your script inside the DOMContentLoaded listener:
document.addEventListener("DOMContentLoaded", function() {
//call your script here
});
Note: IE8 does not support addEventListener.
If you are using jquery, you can use $(document).ready
$(document).ready(function() {
//call your script here
});
Related
I keep getting an error for the last line in generatePassword()," document.getElementById(output).innerHTML = outHash;" Any ideas on how to display this variable?
<html>
<body>
<p>Enter your text here </p>
<input type="text" value="Enter password here" id="userInput">
<button onclick="generatePassword()">Generate</button>
<p>Hash output <span id="output"></span></p>
<script>
function generatePassword() {
var Input = document.getElementById("userInput");
var outHash = digestMessage(Input);
var displayHash = [];
document.getElementById(output).innerHTML = outHash;
}
async function digestMessage(message) {
var encoder = new TextEncoder();
var data = encoder.encode(message);
var hash = await crypto.subtle.digest('SHA-256', data);
return hash;
}
</script>
</body>
Change output in document.getElementById(output) to a string ("output") and it should work. Your javascript is trying to call a variable that doesn't exist.
I'm currently working on a simple flag guessing game, where the user sees a flag and input's the country it is, but I'm finding it hard to take a value from the text input and put it into logic. My function for the button does run but doesn't make it to the if statements, seemingly not reading the text in the input.
<!DOCTYPE html>
<html>
<head>
<title>The America's</title>
</head>
<body>
<img src = "Colombia.png">
</br>
<p><em>The flag shown above is which countries flag?</em></p>
<h1 id="flag">...</h1>
<h2 id = "guess">...</h2>
<h3 id = "result">...</h3>
<input id="guessfun" type ="text">
<!--
<button id="enter">Enter</button> -->
<button id = "button_enter" onclick="guess()">Enter</button>
<script>
function guess(){
alert("f")
flag.textContent = guess.value;
if (guessfun == "Colombia"){
result.textContent = ("Yes! That's the flag of" + guess.value);
alert("Yes")
}
else if (guessfun =! "Colombia") {
result.textContent = ("No! That's the Colombian Flag!");
alert("No")
}
}
onclick = guess();
</script>
</body>
</html>
Any help would be greatly appreciated!
Not gonna lie, your code is pretty messed up. You should probably clean it up. You're trying to access variables that you've never defined(flag, guess). To access the elements, use document.getElementById(). I'm also not seeing what flag.textContent is for. You should instead directly access the input when checking.
function guess(){
var guess = document.getElementById("guessfun").textContent;
var result = document.getElementById("result");
if (guess == "Colombia"){
result.textContent = ("Yes! That's the flag of" + guess.value);
}
else if (guessfun =! "Colombia") {
result.textContent = ("No! That's the Colombian Flag!");
}
}
Additionally, you should probably remove the onclick from the bottom.
Declaring an id in the HTML does not automatically create a corresponding variable accessible through JavaScript, you must first retrieve this element thanks to its id with document.getElementById()
In the example below I use it to retrieve the entered value, then I use it again to display the result:
function guess(){
var input = document.getElementById('guessfun').value
var result = "No! That's the Colombian Flag!"
if (input == "Colombia"){
result = (`Yes! That's the flag of ${input}`);
}
document.getElementById('result').innerHTML = result
}
<img height="36px" src = "https://upload.wikimedia.org/wikipedia/commons/thumb/2/21/Flag_of_Colombia.svg/1280px-Flag_of_Colombia.svg.png">
<br>
<p><em>The flag above is the flag of which country?</em></p>
<h3 id = "result">...</h3>
<input id="guessfun" type ="text">
<button onclick="guess()">Enter</button>
replace else if (guessfun =! "Colombia") { by else {, No need Of putting else if there. Because if guess == "Colombia" dosent match then its always not equal to "Colombia".
And You Haven't Defined flag, result and guessfun
You can define them like this
const flag = document.getElementById("flag");
const result = document.getElementById("result");
const guessfun = document.getElementById("guessfun");
You Can Apply More Than One Flag, Try Below Snippet
Snippet
var currFlag;
var currId;
const v = document.getElementById("guessfun");
const r = document.getElementById("result");
const flag = document.getElementById("flag");
setFlag();
function setFlag(pre = -1){
flag.src = "";
r.innerHTML = "...";
v.value = "";
document.getElementById("guess").innerHTML = "...";
var flags = [];
flags.push(
{"Name" : "Colombia", "Src":"https://upload.wikimedia.org/wikipedia/commons/thumb/2/21/Flag_of_Colombia.svg/255px-Flag_of_Colombia.svg.png"},
{"Name" : "USA", "Src":"https://upload.wikimedia.org/wikipedia/en/thumb/a/a4/Flag_of_the_United_States.svg/220px-Flag_of_the_United_States.svg.png"},
{"Name" : "Sri Lanka", "Src":"https://image.shutterstock.com/image-vector/flag-sri-lanka-lion-vector-260nw-195385355.jpg"},
{"Name" : "UK", "Src":"https://cdn.britannica.com/25/4825-004-F1975B92/Flag-United-Kingdom.jpg"}
);
currId = getRandomId(flags.length, pre);
currFlag = flags[currId];
flag.src = currFlag.Src;
}
function guess(){
document.getElementById("guess").innerHTML = v.value;
if(v.value.toLowerCase() == currFlag.Name.toLowerCase()){
r.innerHTML = "Hooray! You Won. <a href='#' onclick='setFlag("+currId+")'>Click to Guess again<a>";
}
else{
r.innerHTML = "The Correct Answer Is: "+currFlag.Name+". <a href='#' onclick='setFlag("+currId+")'>Click to try again<a>";
}
}
function getRandomId(max, pre = -1) {
var ret;
ret = Math.floor(Math.random()*max);
if(ret > max || ret < 0 || ret == pre){ ret = getRandomId(max, pre) }
return parseInt(ret);
}
<!DOCTYPE html>
<html>
<head>
<title>The America's</title>
</head>
<body>
<img id="flag" width="50px" />
<p><em>The flag shown above is which countries flag?</em></p>
<h1 id="flag">...</h1>
<h2 id = "guess">...</h2>
<h3 id = "result">...</h3>
<input id="guessfun" type ="text">
<button id = "button_enter" onclick="guess()">Enter</button>
</body>
</html>
I'm having trouble on putting Razor inside the HTML5.
I can't get the value of id.
I placed the Razor inside the body tag.
This is what it looked like:
#using ThisIsNamespace
#{
VBEncrypt enc = new VBEncrypt();
if(IsPost)
{
if(Request["txtUserID"] != null || Request["txtPassword"] != null)
{
Session["USER"] = Request["txtUserID"];
Session["PASSWORD"] = Request["txtPassword"];
Session["ID"] = enc.Encrypt("" + Session["USER"] + "]#USERID#[" + Session["Password"] + "");
}
}
}
and then assign the Session["ID"] to a variable: this is located in the head tag.
<script type="text/javascript">
var id = #Session["ID"];
</script>
I'm not getting any error but it seems that it fails to assign the session to the variable.
Please let me know if my question is not clear.
Everyones help would be very much appreciated.
Thank you in advance ;)
Simple test:
#{
Session["ID"] = 1;
}
Then:
<script type="text/javascript">
var id = #Session["ID"];
var id2 = #Session["ID2"];
</script>
Renders as:
<script type="text/javascript">
var id = 1;
var id2 = ;
</script>
One of the checks fails. IsPost is false OR Request["txtUserID"] and Request["txtPassword"] are null
I have a code which takes data from google custom search API, There is no wrong with the custom search API part, it retrieves data without any error
<html>
<head>
<title>JSON Custom Search API Example</title>
</head>
<body>
<div id="content"></div>
<script>
var pageName = new Array();
var pageLink = new Array();
var pageDetails = new Array();
function hndlr(response) {
for (var i = 0; i < response.items.length; i++) {
var item = response.items[i];
pageName[i] = item.title;
pageLink[i] = item.link;
pageDetails[i] = item.htmlSnippet;
}
}
// Some codes
var search_query = 'https://www.googleapis.com/customsearch/v1?key=MY_KEY&cx=XXXXXXXXX&q='+query+'&start=1&callback=hndlr';
s = document.createElement('script');
s.src = search_query;
document.getElementsByTagName('head')[0].appendChild(s);
</script>
</body>
</html>
Required data are saved in the pageName, pageLink and pageDetails arrays.
Now I want display them with chechboxes and allow user to select them.
I need to take the links of the selected sites(pageLink variable) and pass it to anothe file using POST method
I tried using bellow code just before end of the body tag()
<form action="b.php" method="post">
<script>
for (var j = 0; j < 5; j++) {
document.write("<input type='checkbox' name='formDoor[]' id='"+j+"' value= '' />"+pageName[j]+"<br />");
document.getElementById(j).value = pageLink[j];
}
</script>
<input type="submit" name="formSubmit" value="Submit" />
</form>
But in the other file, it says variables are undefined. seems like variables doesn't pass to the 'b.php' file
Can anyone please tell me how to do this?
Your current code for adding checkboxes would likely be executed before the search result arrives (i.e.: before hndlr is executed), so all arrays are still empty. The solution would be to move the checkbox creation code into the hndlr function.
Here's the fixed page.
<html>
<head>
<title>JSON Custom Search API Example</title>
</head>
<body>
<div id="content"></div>
<form id="bform" action="b.php" method="post">
<input type="submit" name="formSubmit" value="Submit" />
</form>
<script>
var pageName = new Array();
var pageLink = new Array();
var pageDetails = new Array();
function hndlr(response) {
var f=document.getElementById('bform'), prev=f.children[0];
for (var i = 0; i < response.items.length; i++) {
var ele, item = response.items[i];
pageName[i] = item.title;
pageLink[i] = item.link;
pageDetails[i] = item.htmlSnippet;
ele = document.createElement('BR');
f.insertBefore(ele, prev);
prev = ele;
ele = document.createTextNode(pageName[i]);
f.insertBefore(ele, prev);
prev = ele;
ele = document.createElement('INPUT');
ele.type = 'checkbox';
ele.name = 'formDoor[]';
ele.id = i;
ele.value = encodeURI(pageLink[i]);
f.insertBefore(ele, prev);
prev = ele;
}
}
// Some codes
var search_query = 'https://www.googleapis.com/customsearch/v1?key=MY_KEY&cx=XXXXXXXXX&q='+query+'&start=1&callback=hndlr';
s = document.createElement('script');
s.src = search_query;
document.getElementsByTagName('head')[0].appendChild(s);
</script>
</body>
</html>
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