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.
Related
I have javascript in page One :
<script>
var valueRm = noRm.value;
localStorage.setItem("noRm", valueRm);
</script>
And this is my javascript in second page :
<input id="noRmUser" name="noRmUser"/>
<script>
var valueRm = localStorage.noRm;
//i try with 3 ways, but i can't get that value
//-->> document.getElementById('noRmUser').value = valueRm;
//-->> document.getElementById('noRmUser').setAttribute('value',
localStorage.getItem('noRm'));
//-->> document.getElementById('noRmUser').setAttribute('value',
localStorage.getItem('valueRm'));
//but if i show in console, that value can show
//-->> console.log(valueRm);
i want show noRm from page one and show noRm in second page on tag input...
I start to learn javascript.. Can someone help me?
Very thankyou if someone want to help me :))
Your script must come after the input. Page rendering stops when a script tag is encountered and the JavaScript runs immediately.
There is no element in the dom when the script tries to assign it.
Put the script at the bottom of the page, right before the closing body tag
Jsfiddle
Before set some value in input.value .
<input id="noRmUser" name="noRmUser" value="hello"/>
For first thing element call was wrong
use
var valueRm = document.getElementById('noRmUser').value;
And localStorage.noRm; is one invalid call .get item only use localStorage.getItem('noRm')
For Page 1 : dont forget to add value="something" in input element
var valueRm = document.getElementById('noRmUser').value;
localStorage.setItem("noRm", valueRm);
For second Page 2
window.onload = function(){
document.getElementById('noRmUser').value =localStorage.getItem('noRm')
}
I have a form on sharepoint, that whenever a person fills that form, it will create a new page with the text added on the form.
I wanted to send an email using JavaScript and HTML with the copy of the various texts.
I have the id of the text and when i create the javascript code, it does not work.
HTML
<a onclick="javascript:sendEmailJobs()" class="mailto"></a>
JavaScript
function sendEmailJobs(){
var JobCodePost = document.getElementById("RichHtmlFieldJobPostCodeJob").body;
window.location.href = "mailto:?subject=Job Offer &body=" + body;
}
The id of said text is this:
<SharepointWebControls:NoteField ID="RichHtmlFieldJobPostCodeJob" FieldName="JobPostCode" runat="server"/>
Am i doing something wrong?
Document elements don't have a "body" attribute, they have innerHTML and innerText. So your function should look like this:
function sendEmailJobs(){
var JobCodePost = document.getElementById("RichHtmlFieldJobPostCodeJob").innerText;
window.location.href = "mailto:?subject=Job Offer &body=" + JobCodePost;
}
Second thing is to verify that you are indeed selecting the correct element. Third thing is to point out that you can't use innerHTML because even if you get everything else right, mailto: links don't support formatted text.
I'm new in javascript development and I want to ask how to set variable from text method.
Example: in this code have a text method
$('.phone').text(theRestaurant.phone);
$('.location').text(theRestaurant.location);
$('.info').text(theRestaurant.info);
in the Html file, when I create any class from these will print the value from JSON file.
Example :
<div class='phone'></div>
Output: (000)000-9999
source code:
<div class='phone'>(000)000-9999</div>
I try to set this in variable but it doesn't work.
My try:
var phone = theRestaurant.phone
I want to set it in variable because I need to put it inside href value like so:
<script>
var phone = 'tel:' + phone
document.getElementById("phone").href = phone;
</script>
I hope everything clear. and If have an other solution please tell about it.
Thanks
Have you wrapped your jQuery code in a document.ready() wrapper?
If not, then the javascript might run before the page has had time to create the elements in the DOM, and nothing will work.
<script>
$(document).ready(function(){
//all javascript/jQuery code goes in here
});
</script>
Also, see my comment above about mixing up "ByClassName" and "ByID"
Answer came from #itsgoingdown
this code in main javascript file:
var phone=document.getElementById('phone').innerHTML; document.getElementsByClassName("phone")[0].href = phone;
I am trying to update some old code that works correctly on all versions of IE except IE11. When an anchor tag is clicked a javascript function is run. The function . All that the function does is that it gets certain values from the DOM and then submits a form using the post action.
I understand that IE11 submit does not work if the input element does not have a name. Here, the submit is done by clicking on an anchor tag- I tried adding a name and id to the anchor tag but it is still not working.
Any idea on how to get it to work. Following is the anchor tag.
<a class="nohigh" href="javascript:getClassDetails('<%=Id%>');">
Following is the javascript function:
function getClassDetails(a){
var classId = document.getElementById(classIdRow ).value;
var courseId = document.getElementById(courseIdRow).value;
document.getElementById('val1').value = classId
document.getElementById('val2').value = courseId
document.getElementById('clasCourseForm').submit();
}
The function that you want should be:
function getClassDetails(a){
var classId = document.getElementById(classIdRow).value; // assuming classIdRow is defined
var courseId = document.getElementById(courseIdRow).value; // assuming courseIdRow is defined
document.getElementById('val1').value = classId;
document.getElementById('val2').value = courseId;
document.getElementById('clasCourseForm').submit();
}
That's at least assuming that all the JavaScript you have up there ^ is verbatim.
[edit: removed the original answer, as the question has been changed to correct the syntax]
In addition, the JS code has other weirdness, in that the function is accepting a parameter (a) but never uses it within the function. There's almost certainly some kind of logic mistake involved there which you'll want to look into.
fixed it - by adding both a name and id to the form.
I am attempting to grab text from a HTML text area, and call the create() method when a 'Submit' button is pressed. The method is trying to use the message from the text area, and post that to its own p tag with class, and post a date stamp in its own p tag, and its own class.
These will both be in the div 'comments'. The error I am getting (using developer tools in Chrome), is
Uncaught TypeError: Cannot call method 'appendChild' of null.
This is aimed at "cmt.appendChild(divTag);". I am very new to Javascript, and this is just practise for me to increase my skills. All help is greatly appreciated!
var cmt = document.getElementById('comments');
function create() {
var username = 'User',
message = document.getElementById("textBox").value,
divTag = document.createElement('div'),
p1 = document.createElement('p'),
p2 = document.createElement('p');
divTag.className = 'comment';
p1.className = 'date';
p1.innerHTML = new Date();
divTag.appendChild(p1);
p2.className = 'message';
p2.innerHTML = username + ': ' +message;
divTag.appendChild(p2);
cmt.appendChild(divTag);
}
The error you are getting suggests that there is no element with the ID "comments" on your page. document.getElementById will return null when no element with such an ID is found, and thus cmd.appendChild(divTag) will be executed as null.appendChild(divTag).
If you are certain that the element exists, you may be executing your JavaScript that assigns the cmt variable before that element is created by the browser. To prevent that, standard practice is to place the <script> tag which includes your external JavaScript just before the closing </body> tag.
If you can't move your script tag for some reason, try running the code that assigns the variable with $(document).ready() (jQuery) or equivalent.
Your code works if the required elements exist. As you can see in this Fiddle.
Works if HTML is similar to:
<div id="comments">
<input id="textBox" type="textBox" value="Hello" />
</div>
My guess is that one of the identifiers might be misspelled or the element as you expect it does not exist.
However, if you are running the script in an external file it might try to execute before the document is fully loaded, hence your script is referring to elements not yet ready in the DOM.
In jQuery you would wrap a $(document).ready(function(){// your code here..}) around.
There is some details on how to do this in just JavaScript in this SO post: Documen Ready equivalent without jQuery.
Actually, his code is fine. Its just that JavaScript runs BEFORE HTML. A simple fix is to nest all of your code inside of a function with any name. Then use window.onload to run the function after the HTML is loaded. so basically:
window.onload = function any_name()
{
//code to be executed
}
This is useful especially if you do not want to move your script tag. I generally like to leave the tag where it is.