JavaScript not showing any alert dialog - javascript

<html>
<head>
<title>BD Home page</title>
<style>
body { background-color:red; }
p { background-color:yellow; }
div { background-color:green; }
</style>
</head>
<body>
<script>
function mf() {
Var x = new Date();
alert("Today is: " + x);
}
</script>
<button onclick="mf()">Click</button>
<div>Hellllllooooo</div>
<p>Hello this is html</p>
</body>
</html>
Hello I am a beginner programmer. In the error code it says mf is not defined on line 1:1, cannot understand that. Is it important to enclose an alert dialog box under a function?

Use var instead of Var. Javascript var keyword must be simple letters

Remove Var before the x or replace it by var ("v" lowercase).

Related

How do i get input from body

I am trying to make a code that takes in input from the body directly and prints it in real-time on the body as well. But what happens is when I actualy type on the body (meaning in mid-air) it registers that i've typed something and the hello disappears but instead of showing what i've typed it gives me undefined in it's place. Here's the code:
<body id="bod" onkeypress="keypres()">
<h1 id="txt">hello</h1>
<script>
function keypres(){
var x = document.getElementById("bod").value;
document.getElementById("txt").innerHTML = x;
}
</script>
</body>
You have to follow code below
<body id="bod" onkeypress="keypres(event)">
<h1 id="txt">hello</h1>
</body>
<script>
function keypres(event){
if(event.charCode=='32'){
document.getElementById("txt").innerHTML = event.key;
}
else{
document.getElementById("txt").innerHTML += event.key;
}
}
</script>

How to add onfocus function to js instead of add it in textarea tag

Hello every one i have below code and i need to to add onfocus function in javascript instead of adding it in textarea tag because it is not secure if i add it in textarea tag
Also make js code work by class of textarea (class="limittext")
<html>
<head>
<title>Limit Textarea</title>
<style type="text/css">
textarea{
width:400px;
height:200px
}
</style>
<script type="text/javascript">
var alert_title='Input Restriction';
function limitTextarea(el,maxLines,maxChar){
if(!el.x){
el.x=uniqueInt();
el.onblur=function(){clearInterval(window['int'+el.x])}
}
window['int'+el.x]=setInterval(function(){
var lines=el.value.replace(/\r/g,'').split('\n'),
i=lines.length,
lines_removed,
char_removed;
if(maxLines&&i>maxLines){
alert('You can not enter\nmore than '+maxLines+' lines');
lines=lines.slice(0,maxLines);
lines_removed=1
}
if(maxChar){
i=lines.length;
while(i-->0)if(lines[i].length>maxChar){
lines[i]=lines[i].slice(0,maxChar);
char_removed=1
}
if(char_removed)alert('You can not enter more\nthan '+maxChar+' characters per line')
}
if(char_removed||lines_removed)el.value=lines.join('\n')
},50);
}
function uniqueInt(){
var num,maxNum=100000;
if(!uniqueInt.a||maxNum<=uniqueInt.a.length)uniqueInt.a=[];
do num=Math.ceil(Math.random()*maxNum);
while(uniqueInt.a.hasMember(num))
uniqueInt.a[uniqueInt.a.length]=num;
return num
}
Array.prototype.hasMember=function(testItem){
var i=this.length;
while(i-->0)if(testItem==this[i])return 1;
return 0
};
function set_ie_alert(){
window.alert=function(msg_str){
vb_alert(msg_str)
}
}
</script>
<script language="vbscript" type="text/vbs">
set_ie_alert()
Function vb_alert(msg_str)
MsgBox msg_str,vbOKOnly+vbInformation+vbApplicationModal,alert_title
End Function
</script>
</head>
<body>
<textarea class="limittext" onfocus="limitTextarea(this,2,0)" wrap="off">some text</textarea>
</body>
</html>
You can add the event listener in javascript with .addEventListener() and get all the elements with the class "limittext" with document.getElementsByClassName(). What you can do is to find all the elements with the class of interest, and then iterate through them and set an event listener to each of them. Something like this should work:
var elements = document.getElementsByClassName('limittext');
for (var i = 0; i < elements.length; i++) {
elements[i].addEventListener('focus', function() {
limitTextArea(elements[i],2,0);
});
}
I don't know if this the best solution or not. I failed to make it work by class but i enabled to make that code work by using ID and do some editions on js code
Thank you for all try to help me
https://jsfiddle.net/zf155z9y/3/
<html>
<head>
<title>Limit Textarea</title>
<style type="text/css">
textarea{
width:400px;
height:200px
}
</style>
<script language="vbscript" type="text/vbs">
set_ie_alert()
Function vb_alert(msg_str)
MsgBox msg_str,vbOKOnly+vbInformation+vbApplicationModal,alert_title
End Function
</script>
</head>
<body>
<textarea id="myForm" wrap="off">some text</textarea>
<script type="text/javascript">
var alert_title='Input Restriction';
var x = document.getElementById('myForm');
x.addEventListener("focusin", limitTextarea);
function limitTextarea(){
var el = this;
var maxLines = 5;
var maxChar = 0;
if(!el.x){
el.x=uniqueInt();
el.onblur=function(){clearInterval(window['int'+el.x])}
}
window['int'+el.x]=setInterval(function(){
var lines=el.value.replace(/\r/g,'').split('\n'),
i=lines.length,
lines_removed,
char_removed;
if(maxLines&&i>maxLines){
alert('You can not enter\nmore than '+maxLines+' lines');
lines=lines.slice(0,maxLines);
lines_removed=1
}
if(maxChar){
i=lines.length;
while(i-->0)if(lines[i].length>maxChar){
lines[i]=lines[i].slice(0,maxChar);
char_removed=1
}
if(char_removed)alert('You can not enter more\nthan '+maxChar+' characters per line')
}
if(char_removed||lines_removed)el.value=lines.join('\n')
},50);
}
function uniqueInt(){
var num,maxNum=100000;
if(!uniqueInt.a||maxNum<=uniqueInt.a.length)uniqueInt.a=[];
do num=Math.ceil(Math.random()*maxNum);
while(uniqueInt.a.hasMember(num))
uniqueInt.a[uniqueInt.a.length]=num;
return num
}
Array.prototype.hasMember=function(testItem){
var i=this.length;
while(i-->0)if(testItem==this[i])return 1;
return 0
};
function set_ie_alert(){
window.alert=function(msg_str){
vb_alert(msg_str)
}
}
</script>
</body>
</html>

Replacing inner HTML fails despite onload function

I rarely have to do any Javascript and I seem to fail doing the easiest tasks. I am trying to replace a string in two divs. The first div gets replaced, the second one is not found with the error message:
drawings.html:20 Uncaught TypeError: Cannot set property 'innerHTML' of null
However I tried the usual remedies of putting my code in an 'onload' function and putting the script at the end of the body tag. What else could possibly go wrong?
<!DOCTYPE html>
<html>
<head>
</head>
<body>
<div id="cell1">test<div>
<div id="cell2">test<div>
<script>
window.onload = function() {
replace();
}
function replace() {
console.log("replace");
document.getElementById("cell1").innerHTML = "cell1";
document.getElementById("cell2").innerHTML = "cell2";
}
</script>
</body>
</html>
just close your divs elements.
<html>
<head>
</head>
<body>
<div id="cell1">test</div>
<div id="cell2">test</div>
<script>
window.onload = function() {
replace();
}
function replace() {
console.log("replace");
document.getElementById("cell1").innerHTML = "cell1";
document.getElementById("cell2").innerHTML = "cell2";
}
</script>
</body>
</html>

not able to load contents in div using javascript

this is shan and i'm a javascript noob and i'm trying to work qa code as an example here. i'm trying to load a small javascript content to a div element but it is not working any help would be great and here is the code.
<html>
<head>
<title>
using d for statement
</title>
<script>
function displaytext () {
var loopindex=0;
var sum=0;
for (var loopindex=1; loopindex <=100; loopindex++) {
sum +=loopindex;
};
document.getElementById('targetdiv').innerhtml="adding 1 to 100 gives "+sum;
}
</script>
</head>
<body>
<div id="targetdiv">
</div>
</body>
</html>
You need to call the function. It's also a good idea to wait until the window is loaded (or you can use some more advanced JS to detect the DOM ready state.):
<html>
<head>
<title>
using d for statement
</title>
<script>
function displaytext() {
var loopindex=0;
var sum=0;
for (var loopindex=1; loopindex <=100; loopindex++) {
sum +=loopindex;
};
document.getElementById('targetdiv').innerHTML = "adding 1 to 100 gives "+sum;
}
window.onload = function(){
displaytext();
}
</script>
</head>
<body>
<div id="targetdiv">
</div>
</body>
</html>
3 problems:
You never actually call the function. It is only declared.
The property is innerHTML not innerhtml. Javascript is case-sensitive.
The script is above an element is is referencing. As scripts are executed as they are found (page construction is paused during execution) the element you are referring to is never found.
Also you declare the loopindex variable twice, which i think will cause a syntax error on ES5 strict.
<html>
<head>
<title>
using d for statement
</title>
</head>
<body>
<div id="targetdiv">
</div>
</body>
<script>
function displaytext () {
var sum=0;
for (var loopindex=1; loopindex <=100; loopindex++) {
sum +=loopindex;
};
document.getElementById('targetdiv').innerHTML="adding 1 to 100 gives "+sum;
}
displaytext();
</script>
</html>

Why does the browser modify the ID of an HTML element that contains &#x?

Say I've got this HTML page:
<html>
<head>
<script type="text/javascript">
function echoValue(){
var e = document.getElementById("/path/$whatever");
if(e) {
alert(e.innerHTML);
}
else {
alert("not found\n");
}
}
</script>
</head>
<body>
<p id="/path/$whatever">The Value</p>
<button onclick="echoValue()">Tell me</button>
</body>
</html>
I would assume that the browser treats the ID-string /path/$whatever as simple string. Actually, it converts the $ to it's rendered representation ($).
The javascript code however uses the literal string $ to search for the element. So, the call document.getElementById fails and I never get hands on the value of the paragraph.
Is there a way to force the browser into using the given ID string literally?
Edit:
Of course I know that I don't have to escape the $. But the web page gets generated and the generator does the escaping. So, I have to cope with what I've got.
In the <p id="...">, the $ sequence is interpreted as $, because it appears in an attribute and is treated as an HTML entity. Same goes for all other element attributes.
In the <script> element, HTML entities are not interpreted at all, so it shows up literally.
You could try decoding the javascript text without jQuery:
<html>
<head>
<script type="text/javascript">
function decodeEntity(text){
text = text.replace(/<(.*?)>/g,''); // strip out all HTML tags, to prevent possible XSS
var div = document.createElement('div');
div.innerHTML = text;
return div.textContent?div.textContent:div.innerText;
}
function echoValue(){
var e = document.getElementById(decodeEntity("/path/$whatever"));
if(e) {
alert(e.innerHTML);
}
else {
alert("not found\n");
}
}
</script>
</head>
<body>
<p id="/path/$whatever">The Value</p>
<button onclick="echoValue()">Tell me</button>
</body>
</html>
JSFiddle: http://jsfiddle.net/phTkC/
I'd suggest you to decode the HTML entity in your javascript code:
<html>
<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js"></script>
<script type="text/javascript">
function echoValue(){
var decoded_string = $('<div />').html("/path/$whatever").text();
var e = document.getElementById(decoded_string);
if(e) {
alert(e.innerHTML);
}
else {
alert("not found\n");
}
}
</script>
</head>
<body>
<p id="/path/$whatever">The Value</p>
<button onclick="echoValue()">Tell me</button>
</body>
</html>

Categories