As a long time network engineer, Javascript has been a challenge to say the least. I am looking to use HTML & Javascript to create a template used to make network gear configurations. The HTML portion is very basic. Just a form with input fields and a button:
<body>
<form id="form1">
<label for="siteCode">Site Code: </label>
<input type="text" id="siteCode" name="name" placeholder="ex. HEN" required="required"/><br>
A button is used to call a Javascript function named "makeConfig"
I am running into an issue when it tries to get the "siteCode" ID from the HTML:
var siteCode = document.getElementById("siteCode");
function makeConfig() {
var myWindow = window.open("", "MsgWindow", "width=1000,height=850");
myWindow.document.write("service nagle<br>no service pad<br>service tcp-keepalives-in<br>service tcp-keepalives-out<br>");
myWindow.document.write("service timestamps debug datetime localtime show-timezone<br>service timestamps log datetime localtime show-timezone");
myWindow.document.write("service password-encryption<br>service compress-config<br>!<br>");
myWindow.document.write("hostname P" + siteCode + "A01M01UAA<br>!<br>");
}
The last line always generates a null value for siteCode. I would think this is simple, but I am drawing a blank. Thank you in advance for any help!
siteCode will be a reference to the DOM (Document Object Model) node of the element; which contains a bunch of objects and properties that you probably don't want to print.
Instead; you probably want the the text that the user has entered into it. For that; you could do something like
myWindow.document.write("hostname P" + siteCode.value + "A01M01UAA<br>!<br>");
Notice we are getting it's value (siteCode.value); rather than just the raw element.
For something like this; another common mistake is that the JavaScript may be running before the rest of the page has loaded; and therefore the element may simply not have loaded yet. However, since you've put it in a function; I'm assuming that's not what happening here; and you're running it only when the user presses a button; etc. If not; that may be something to check.
Related
Okay, so I am trying to make a quiz where you enter some code and the quiz executes the code to see if what you typed is the same as the answer.
Here is the code and this is how the webpage looks like:
questions = "PRINT HELLO"
document.getElementById("Question").innerHTML = questions
function check(){
document.getElementById("answertext").innerHTML = eval(document.getElementById("answerbox").value)
}
#answerbox{
width:100%;
height:500px;
font-size:25px;
}
<h1>QUIZZZ</h1>
<h2 id = Question>JAVASCRIPT CONSOLE AND EXERCISES</h1>
<h1 id = "hi"></h1>
<textarea rows="4" cols="50" id = "answerbox">
//put your answer here
</textarea>
<textarea rows= '4' cols = "50" id = "answertext">lol</h1>
</textarea>
<input type = "submit" onclick = "check()">
Run the code to see
I want the user to enter a document.write() statement inside the textbox, and have the evaluated code to be shown in the smaller multiline text box.
Try to put a document.write() statement in the textbox and run it. You should see a new page instead of the answer written in the text box.
I know that document.write is a bad practice to output things in javascript, and I know that you can edit raw HTML, but is there any other way a user can print a message without doing any of these choices?
Don't use eval.
Using eval is considered to be a bad practice. Read more for Why here. You can ask your user to just return the answer using a return statement as shown below, instead of asking them to do something complicated like document.write().
// Ask them to do this:
var codeFromTheAnswerBox = "var answer = 'HELLO'; return answer;"
// instead of this:
// var codeFromTheAnswerBox = "var answer = 'HELLO'; document.write(answer)";
// execute user's code
var code = new Function(codeFromTheAnswerBox);
var returnValue = code();
// Now do whatever you want to do with the answer like the following
alert("Your answer is " + returnValue);
You can use .append instead of document.write()
document.body.append("Hello World!", document.createElement('p'));
If you go to the Console tab of the DevTools in your browser, you can type javascript code and press enter to execute it. You will get helpful error messages that should help you with your project.
Ok. I realized your problem.
You can use iframe for this purpose. Add an iframe with an id similar 'answerIframe' instead of #answertext element.
Then move your #answertext element to a separated html and set address of iframe to it.
In iframe:
window.check=function(){
document.getElementById("answertext").innerHTML =
eval(document.answer);
}
And add a button to your iframe too. for iframe's button set this:
onclick="window.check()"
Add an Id to iframe's button similar: iframe_bt.
Now, when user clicks on button (in current page, no iframe) must call this (new check function in your main page):
function check(){
document.getElementById('#answerIframe').contentWindow.document.answer=document.getElementById("answerbox").value;
document.getElementById('#answerIframe').contentWindow.document.getElementById('#iframe_bt').click();
}
Also in your iframe, call a function in document's onload and add answertext dynamically if is not exists (because document.write) or reset the iframe before execute per answer.
Another way is replacing the document.write with other code similar: elem.insertAdjacentHtml(..) or etc before execute it.
Excuse me for any mistake, i typed with my cellphone.
I did not have a tool to test it, but the method and its generalities are correct.
I have an html element, (lets say for simplicity) a label, and it has a title, so that a tooltip appears when you hover over the label.
I would like the tooltip to show a snapshot of some associated 'current' data. In actuality, the current price of the object that the label points to, but an analogue of this could be any data that potentially changes with time.
In native JavaScript, how can I detect the activation of the tooltip, so that I can re-calc the data before the tooltip is shown?
I know that I could use setInterval() or something to keep the title string current, but it would be more efficient to only re-calculate the title string when the tooltip is shown.
Try using data-* attribute of element to store values, setting element.title to data-* of element , onmouseover , onmouseleave events
var elem = document.querySelector("div");
var interval = setInterval(function() {
elem.dataset.tooltip = 1+ +elem.dataset.tooltip;
}, 1000);
elem.onmouseover = elem.onmouseleave = function(e) {
console.log(e)
this.title = this.dataset.tooltip;
}
<div data-tooltip="0" title="0">hover</div>
Something like this may work, but you'll be at the mercy of the latency of the request for updating the data (assuming that the source of the updated price data is a http request or socket connection) and that probably won't be quicker than the browser will display the tooltip. It's certainly not going to be consistent or reliable.
<p id="text" title="initialtitle">Text</p>
<script>
var n = 0;
document.getElementById("text");
text.onmouseover = function() {
n++;
text.title = n;
};
</script>
Depending on the specifics of what you're doing and how much room for maneuver you have, another solution could be to open a WebSocket to a server which then updates all clients with the updated price information when it changes. That way the data is sent to the cleint as fast as possible without constant http polling, and timers aren't necessary.
Of course, if the source of the data is a calculation within the JavaScript itself without having to get information from a server, then a mere modification of the above for your needs could suit.
Here's a jsfiddle to play around with.
I think this code help you
<script src="//code.jquery.com/jquery-1.12.0.min.js"></script>
<div class="test" id="test" onChange="setTitle(this)" title="testing...">Test1</div>
<script type="text/javascript">
$('#test').bind("DOMSubtreeModified",function(){
$('#test').attr('title',$('#test').html());
});
// Run below code in your console to change your div value
//$(".test").html("test2");
</script>
First run above code in you browser. and check tooltip will be 'testing...'.
Then run
$(".test").html("test2");
In your browser console to change your div html and then check your tooltip again. you will see the exact text of div.
I am a beginner in HTML and I want to create a region on a HTML page where the values keep on changing. (For example, if the region showed "56" (integer) before, after pressing of some specific button on the page by the user, the value may change, say "60" (integer) ).
Please note that this integer is to be supplied by external JavaScript.
Efforts I have put:
I have discovered one way of doing this by using the <canvas> tag, defining a region, and then writing on the region. I learnt how to write text on canvas from http://diveintohtml5.info/canvas.html#text
To write again, clear the canvas, by using canvas.width=canvas.width and then write the text again.
My question is, Is there any other (easier) method of doing this apart from the one being mentioned here?
Thank You.
You can normally do it with a div. Here I use the button click function. You can do it with your action. I have use jquery for doing this.
$('.click').click(function() {
var tempText = your_random_value;
// replace the contents of the div with the above text
$('#content-container').html(tempText);
});
You can edit the DOM (Document Object Model) directly with JavaScript (without jQuery).
JavaScript:
var number = 1;
function IncrementNumber() {
document.getElementById('num').innerText = number;
number++;
}
HTML:
<span id="num">0</span>
<input type='button' onclick='IncrementNumber()' value='+'/>
Here is a jsfiddle with an example http://jsfiddle.net/G638z/
i'm having a problem on how should i implement/build my form. here's the overview.
the first step of the form is to fill up the "Responsibility Center". however, the user can add multiple responsibility center. then the next step would be - each responsibility center added should have one or many "account codes". at the end of the form, before submitting it, all the data should be editable.
the result should be like this:
|**responsibility center**||**account codes**|
| center 1 || account code 1 |
| || account code 2 |
| center 2 || account code 1 |
etc..
i just need some idea on how the form should be built/implemented.
EDIT 1
This is what i've tried
1st step
2nd step
result
EDIT 2
i already know how to add multiple rows (like on the 2nd step) and i can implement that already on the first to the 1st step. so here are my questions:
how can i add account codes per responsibility center?
if what i've tried is not a practical way to implement it, then how should i do it?
Unfortunately, I began writing this answer before you posted the pics of your app. The ideas are still relevant, but I would have tailored my example more to what you are doing. Sorry about that.
I would use jQuery and AJAX to get the job done. jQuery to handle insertion of new elements to the DOM, and for field validation; AJAX to verify that no account codes are duplicated between RCs, or what have you. Personally, I would also use AJAX to handle the form submission instead of using the more traditional <form action= method=> because it gives greater control over the process and doesn't whisk the user off to another page before I am ready. However, it is easiest to describe the <form> example, and you can first build that and then change it over to using AJAX if you want.
The example from here is assuming a blank slate (i.e. I had not seen your sample app before writing this):
First, in your jQuery/javascript, you need a counter to keep track of each RC added. This can be in the <head> tags of your HTML/PHP, or it can be stored in a separate file. If you click on my name and look at other AJAX answers I've given, you'll see many useful examples.
<script type="text/javascript">
$(document).ready(function() {
var ctr = 0;
});
</script>
In your HTML, you need a DIV into which you will append each RC DIV. You also need a link/button/whatever for user to initiate creation of a new RC. This would be a brief form, even just [RC Title] and [Account Code] with a link/button/whatever to create another [Account Code] field and a [Done/Submit] button.
HTML:
<div id="container">
<form action="yourprocessorfile.php" method="POST" id="myform"></form>
</div>
<input type="button" id="mybutt" value="Add New RC" />
JAVASCRIPT/jQuery (again, inside the (document).ready() section above):
$('#mybutt').click(function() {
ctr++;
var str = 'RC TITLE:<br><input id="RC-"'+ctr+' class="RC" type="text"><br>ACCOUNT CODE<br><input id="AC-"'+ctr+' class="AC" type="text"><br>';
$('#myform').append(str);
});
When user presses [Done], use jQuery again to check that each [Account Code] field has been completed.
$('#done').click(function() {
$('.RC').each(function() {
if ($(this).val() == '') {
alert('Please complete all fields');
$(this).focus();
return false;
}
});
$('.AC').each(function() {
if ($(this).val() == '') {
alert('Please complete all fields');
$(this).focus();
return false;
}
});
$('#myform').submit();
});
Edit 2 / Question 1:
You can add new account codes linked to an RC by:
You need to somehow assign a unique data element to the RC, such as an incrementing ID
have a link for adding the new AC
use jQuery to get the ID of the nearest RC element
use .split() to split-off the numerical portion (assign to a var)
use that number when creating your AC
$('.add_AC').click(function() { //Note I used a class, so you can have a link for each RC
var num = $(this).parent().attr('id').split('-')[1];
var str = '';
});
In the above example:
==> Because I used a class, it will fire whenever ANY element with that class is clicked. Of course, when you create the button, you must add that class to the button def, as:
<input type="button" class="add_AC" value="Add Account Code" />
num ==> uses chained jQuery methods to, one-after-another, get the number portion of the RC's id.
$(this) ==> whichever [Add Account Code] button/link/whatever was clicked on.
.parent() ==> This may or may not be correct for your situation. This is the part where we traverse the DOM to find the RC element's ID code, which would look like this: RC-3. You will need to experiment with:
.parent().parent()
.sibling()
.parent().sibling()
.closest()
.prev() or .next()
Play with these selectors, with Dev Tools window opened. It should only take a handful of minutes to find your RC element -- or ask another question and post your HTML.
.attr('id') ==> Obviously, returns the text of the ID, in our case RC-3
.split('-')[1] ==> Creates an array with RC on one side (zero), and 3 on the other (1)
Hopefully this all gives you some idea of where to begin...
I'm modifying a dynamically created input element by setting the innerHTML, when I view the element in the DOM Inspector I can see that the values I passed are in the input. However, I can't see it on the page? Is there a refresh() function that I should be calling after setting the value?
I have tried innerText, and value and gotten the same results.
Here is how I am setting it:
$("input[name='group']")[0].innerHTML = groups;
(as far as the JS set and the JQuery selector I have found chrome plugins to be fickle this way)
input elements don't contain HTML. They have values.
No, you don't need to refresh anything, the change should show up as soon as the JavaScript finishes running (e.g., the event handler completes) and the browser has a moment to update the display. If you're doing this in a tight loop or something, you won't see the results until the end of the loop, but I didn't immediately get the sense that was what you were doing — unless you're single-stepping through the code in the dev tools? You won't see the refresh as you're single-stepping.
If not that, could it be that the element doesn't exist (yet) when you're calling your code? Remember that if your code is in a script element that's in the HTML before the element you're trying to update, you have to be sure you make it wait to run until the rest of the page has been parsed (using a ready callback, for instance). Alternately, just do what the YUI folks recommend and put your script tag at the end of the body.
Here's a working example:
jQuery(function($) {
setInterval(function() {
$("input[name='group']")[0].value = "Updated " + new Date();
}, 500);
});
Live copy
Breakdown:
Waiting until the DOM is ready (by putting my code inside the function I pass into jQuery; this is a shorthand way of writing jQuery(document).ready(...)).
Set up an interval timer to update every 500ms.
Within the interval callback, look up the input element with the name "group" and update its value.
Update: Here's a simpler series of examples that demonstrate the whole "does the element exist yet?" thing:
Example 1:
<form>
<input type='text' name='group' value='original value' size='60'>
</form>
<script type='text/javascript'>
// This works, because it's _after_ the element
// it operates on
$("input[name='group']")[0].value = "Just one update: " + new Date();
</script>
Live copy
Example 2:
<script type='text/javascript'>
// This FAILS, because it's _before_ the element
// it operates on
$("input[name='group']")[0].value = "Just one update: " + new Date();
</script>
<form>
<input type='text' name='group' value='original value' size='60'>
</form>
Live copy
Example 3:
<script type='text/javascript'>
// This works, because although this script tag is before
// the element, we're using `ready` to wait until the DOM
// is ready
$(function() {
$("input[name='group']")[0].value = "Just one update: " + new Date();
});
</script>
<form>
<input type='text' name='group' value='original value' size='60'>
</form>
Live copy
Text box has no inner HTML. You need to set its value:
$("input[name='group']").val(groups);