Backslash escape not working in HTML attributes - javascript

I tried below code for checking whether backslashes in HTML attribute value makes the character next to it escape:
<button id="b1" onclick="$('body').append('<button onclick=alert(\'something\');>')">test</button>
Here, if backslash works, then when we click over #b1 , a new button should have appended to and when we click over that new button, a new alert should have popped up. But it didn't. This means backslash escape won't work in HTML attributes.
Is it correct?
Then how do I escape things ?
When I tried opening that webpage with view-source: prefix, I saw code like below one:
<!DOCTYPE html>
<html lang="en">
<head>
<title>
Hi there!
</title>
<meta name="viewport" content="width=device-width">
<script src="jQuery.js"></script>
<style>
.red{color: red;}
</style>
</head>
<body>
<button id="b1" onclick="$('body').append('<button onclick=alert(+AFw'something+AFw');>test</button>')">
test
</button>
<script src="question.js"></script>
</body>
</html>
Here, backslashes are replaced to +AFW. Is it wrong ?
Also, if I try changing the onclick attribute value to doIt(); and add below code into question.js file, it works perfectly:
function doIt(){
alert("<button onclick=\"alert('hi');\"> ");
}
But as the question says, we have to find out why backslash escape not working in HTML attribute values. Also, I wants to define what will happen when button clicked, right in the attribute.
Thanks in advance for giving informations.....

Seems working. Here's the runnable script/example
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button id="b1" onclick="$('body').append('<button onclick=alert(\'something\');>test</button>')">test</button>

Related

I need help understanding event handlers and functions in JavaScript?

I wrote HTML document and linked to my JS document.
when I execute the HTML file on my browser it only shows the "Click me!" button, but what I expected it to do was to show the result of my math function when clicked. But .. nothing happens. I'm very new to JavaScript so I'm sure this is a simple answer, but Googling isn't helping ... I appreciate any insight to what I'm doing wrong here.
Here's the code from HTML file:
<!DOCTYPE html>
<html lang=""en">
<head>
<meta charset="UTF-8">
<script src="JS/main.js"></script>
</head>
<body>
<p id="Math">
<button onclick="myFunction()">Click me!</button>
</p>
</body>
</html>
Here's the JS file:
function myFunction(a, b) {return a * b;}
document.getElementById("Math") .innerHTML = myFunction(13, 4);
Not sure what are you trying to do, but if you want to change the content of the "Math" element, you must call the function with parameters (eg: onclick="myFunction(1,3)") and that function should replace the content:
function myFunction(a, b) {
document.getElementById("Math").innerHTML = a * b;
}
<p id="Math">
<button onclick="myFunction(3,4)">Click me!</button>
</p>
Also if you want to preserve the button after clicking, this should be located outside the "Math" element to avoid being removed when replacing innerHTML
You’re including you script file in the header, so it runs before the dom is available. When it executes, it won’t be able to find your id, so nothing will happen. You likely will see an error in the console that your document.getElementById call is returning undefined. Either include it at the end of the body, or add a defer tag:
<script src="JS/main.js" defer></script>
Also, as soon as the code runs, it overwrites the content of the p tag, including the button. Make the p and the button siblings.
One error in your html appears to be caused by an extra " in your lang attribute for your opening html tag. Try deleting it.
<html lang="en">

Why doesn't innerHTML work with white spaces?

In the below html, the front button doesn't respond while the back button changes the content of the tag.
<!DOCTYPE html>
<html>
<body>
<p id ="para">Initial text. </p>
<button onClick=document.getElementById('para').innerHTML="move front">
front
</button>
<button onClick=document.getElementById('para').innerHTML="back">
back
</button>
</body>
</html>
In the below, both the buttons change the content of the tag.
<!DOCTYPE html>
<html>
<body>
<p id ="para">Initial text. </p>
<button onClick=document.getElementById('para').innerHTML="movefront">
front
</button>
<button onClick=document.getElementById('para').innerHTML="back">
back
</button>
</body>
</html>
Why does a bank space make a button unresponsive?
That is just invalid HTML.
You have to put quotes around your whole onclick attribute value, otherwise it will end at the space.
onClick = document.getElementById('para').innerHTML="move // cut off here
front" // a second (meaningless) attribute for your button tag.
Please consider this syntax:
<button onclick="document.getElementById('para').innerHTML='move front'">front</button>
You are probably having issues if you are using this technique.
I am sorry but this is not how you attach a click event to elements in modern javascript, at least if you want to work with what's called "good practices".
The better method would be to attach a click event to a desired element using javascript.
I will give you a short code example.
First the HTML - I will use your original HTML (modified a bit):
<!DOCTYPE html>
<html>
<body>
<p id ="para">Initial text. </p>
<button id="frontBtn"> front </button>
<button id="backBtn"> back </button>
</body>
</html>
As you can see, I have removed your "onclick" events from the buttons, and assigned an id to each button.
Second, we will write some javascript to properly attach a click event to each one of the buttons, and of course execute the change of text as you originally was intending to do:
if you are familiar with jQuery then this will do:
$('#frontBtn').on('click',function(){
$('#para').html('move front');
});
$('#backBtn').on('click',function(){
$('#para').html('back');
});
This can also be done with vanilla (native) javascript:
document.getElementById("frontBtn").addEventListener("click", function(){
document.getElementById("para").innerHTML = "move front";
});
document.getElementById("backBtn").addEventListener("click", function(){
document.getElementById("para").innerHTML = "back";
});
Now we have a nicely structured event handler for each button, more code can be easily added.
As for where to insert your javascript ?
You can add the javascript to your html document by using script tags in your html document head like this:
<!DOCTYPE html>
<html>
<head>
<script type="text/javascript">
// your code here..
</script>
</head>
<body>
....
....
Or even better - create a separate script file and load it at the bottom of your html page like this:
<!DOCTYPE html>
<html>
<head>
....
</head>
<body>
....
....
<script type="text/javascript" src="scripts.js"></script>
</body>
</html>
This is the better way to attach events to elements, using javascript.
Imagine if you try to write 50-100 lines of code inline ? impossible! but with an event handler function you can do it easily.
Things will basically work better and your project will be much easier for you to maintain.
Hope it helps a bit!

Delete whole anchor tag in contenteditable div on one keypress

I have following HTML:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<title>Document</title>
</head>
<body>
<div id="edit" contenteditable>
This is link that is editable.
</div>
</body>
</html>
What I'm trying to do is a very simple text editor where you can put in links (they would get turned into html via JS) but when you hit backspace in the back or delete in front of them, I want it to disappear at once (not deleting anchor text letter by letter).
How would one go about it? My steps with Javascript would be sth like this:
When pressing Backspace key, detect if </a> is before the cursor, if so run regex on the section before cursor, pick a first match and replace it with blank space.
The opposite, detect if Delete key is pressed, check if <a ... > is in front of it and remove it as well.
I'm just not quite sure how to put this in code and also if I can run regex and have it recognize the text in contenteditable area. I'd like to avoid any heavy external libraries because the text editor will not really do much more besides this.
If anybody wants to fork my Codepen here it is.
Thanks for any advice.
There is a clean way to solve this:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<title>Document</title>
</head>
<body>
<div id="edit" contenteditable>
This is link that is editable.
</div>
</body>
</html>
Adding a contenteditable="false" will register the anchor as a whole and not letter by letter.
If you've already got the method down to pass in the string and re-assign the value of the contenteditable section, here's an example of how to structure the regex.
var textblock = document.getElementById('edit')
function testContent(deletetype) { // deletetype == "delete" || "backspace"
var txt = textblock.innerHTML.toString().trim(),
rgxstring = "<a[^<]+<\\/a>",
rgx
if (deletetype == "delete") {
rgxstring = "^" + rgxstring
} else {
rgxstring += "$"
}
rgx = new RegExp(rgxstring, "i")
console.log(txt, txt.match(rgx))
textblock.innerHTML = txt.replace(rgx, "")
}
testContent("backspace")
<div id="edit" contenteditable>
This is link
</div>

Display path with backslash (javascript)

I try to display a path on an simple javascript alert command :
<html xmlns="http://www.w3.org/1999/xhtml" lang="fr" xml:lang="fr">
<head>
</head>
<body>
<div onClick=myFunction('D:\user\myself\dos')>
clic here
</div>
<SCRIPT LANGUAGE = "JAVASCRIPT">
function myFunction(p) {
alert(p);
}
</SCRIPT>
But it does not display the backslash..
I suppose I should replace all "\" by "\" but I don't find a way to do it.
(I tried p = p.replace(/\\/g, '\\\\'); and a lot of other syntaxes but none of those worked.
Do you have any idea of how to deal with that ?
EDIT :
The path comes out from a function and I can't edit it directly in "onClick"
The backslash '\' itself is used as the escape character.
So add one more backslash before every backslash you are going to display.
In case if you cannot modify url try to add new attribute and access that attribute within onClick handler.
Try working snippet below:
function myFunction(elem) {
alert(elem.getAttribute('data-url'));
}
<html xmlns="http://www.w3.org/1999/xhtml" lang="fr" xml:lang="fr">
<head>
</head>
<body>
<div data-url="D:\user\myself\dos" onClick=myFunction(this)>
clic here
</div>
Update: Code snippet updated to allow displaying url without modifying string.
You just need to call your function with double the backslashes to escape the escape character:
myFunction('D:\\user\\myself\\dos')
Will this work in your case?

Why can't I get this entity code to display correctly in a browser?

I'm trying to code a UK Pound symbol to be written to a document by JavaScript, but it's code is not being translated and is instead displayed as entered.
See this JSBin http://jsbin.com/orocox/1/edit
This is the JavaScript:
$("#price").text('£ 1.99');
This is the html:
<!DOCTYPE html>
<html>
<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.8/jquery.min.js"></script>
<meta charset=utf-8 />
<title>JS Bin</title>
</head>
<body>
<span id="price"></span>
</body>
</html>
This is the result:
'&pound(;) 1.99'
*Note that the parenthesis around the ';' are added by me to prevent the entity code from being translated on StackOverflow, but they do not exist in the actual output.
The result I want is:
'£ 1.99'.
use unicode instead: jsbin
$("#price").text('\u00A3 1.99');
explanation: the £ is an html entity and is not processed as normal text. but unicode works for any text. since you are using text it is processed as a string not an html.
check this page's encoding reference : here
Try $("#price").html('£ 1.99'); instead.
Use the character itself:
$("#price").text('£ 1.99');
This is good for the readability of your code. How you type “£” depends on your editing environment. E.g., on Windows, you can produce it by typing Alt 0163 if you cannot find any more convenient way (depending on keyboard, keyboard layout, and editor being used).

Categories

Resources