Robert
Robert

Reputation: 841

How can I use HTML symbols like arrows in javascript?

I have a script that generates a list of <form> tags with multiple inputs and buttons inside. I want to use an arrow (↑) on a button but when I write

buttonUp.value="&#x2191;";

it doesn't work.
Instead of showing ↑, the button shows the raw code on the page. How can I make the arrow display on the button?

Upvotes: 3

Views: 10890

Answers (4)

Skyleter
Skyleter

Reputation: 118

I don't recommend you do this with JavaScript (for newbies like me it's harder). It's very easy, using only html.

Example:

<input type="submit" value="&#x2191; HELLO" style="border-radius:50px;" />
<button>&#x2191; HELLO</button>

If you still want to use js, the reply from guest271314 is working.

Here is the list of symbols on HTML(click)

PS. I also recommend you use Font Awesome , very nice icons.

Make sure to tell me if worked for you.

I know this doesn't answer your question but I hope this will be useful for newbies

Upvotes: 2

George Reith
George Reith

Reputation: 13476

Use a Unicode escape sequence.

buttonUp.value = "\u2191";

Upvotes: 3

guest271314
guest271314

Reputation: 1

Use button element, which has .innerHTML property

document.querySelector("button").innerHTML = "&#x2191;"
<button></button>

alternatively, use the actual "upwards arrow" or "up arrow" character

document.querySelector("input[type=button]").value = "↑";
<input type="button" value="" />

Upvotes: 1

Punit Gajjar
Punit Gajjar

Reputation: 4997

There is a problem with your solution code--it will only escape the first occurrence of each special character. For example:

escapeHtml('Kip\'s <b>evil</b> "test" code\'s here');
Actual:   Kip&#039;s &lt;b&gt;evil</b> &quot;test" code's here
Expected: Kip&#039;s &lt;b&gt;evil&lt;/b&gt; &quot;test&quot; code&#039;s here

Here is code that works properly:

function escapeHtml(text) {
  return text
      .replace(/&/g, "&amp;")
      .replace(/</g, "&lt;")
      .replace(/>/g, "&gt;")
      .replace(/"/g, "&quot;")
      .replace(/'/g, "&#039;");
}

also u can use below code

function escapeHtml(text) {
  var map = {
    '&': '&amp;',
    '<': '&lt;',
    '>': '&gt;',
    '"': '&quot;',
    "'": '&#039;'
  };

  return text.replace(/[&<>"']/g, function(m) { return map[m]; });
}

Upvotes: 0

Related Questions