0

I am trying to add the Degree Celsius ℉ value to an attribute using jQuery.

$("#degree-toggle").attr("value", ℉);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="button" id="degree-toggle" checked="checked">
Rory McCrossan
  • 331,213
  • 40
  • 305
  • 339
Gaurav Thantry
  • 753
  • 13
  • 30

4 Answers4

0

You need to decode the HTML entity first. It doesn't work in attributes:

$("#degree-toggle").attr("value", decodeHtml("&#8457;"));

function decodeHtml(html) {
    var txt = document.createElement("textarea");
    txt.innerHTML = html;
    return txt.value;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<input type="button" id="degree-toggle"  checked="checked">

The decodeHtml() function works by creating a hidden textarea. Then the data which needs to be decoded is injected into that textarea and once that happened it gets read out by grabbing the "rendered" value of it.

NullDev
  • 6,739
  • 4
  • 30
  • 54
  • Hi @NullDev. Thank you for your quick response. Can you please breakDown the decodeHTML function? I am not able to understand it. your answer worked – Gaurav Thantry Jan 23 '18 at 11:53
0
 $("#degree-toggle").attr("value", $("<div />").html('&amp;').text());

Working pen: https://codepen.io/todorutandrei/pen/OzGgmM

Andrei Todorut
  • 4,260
  • 2
  • 17
  • 28
0

Try this simple and raw implementation and starts from here:

$("#degree-toggle").keyup(function(){
  var newval = this.value.replace('°F',''); 
     this.value = newval + '°F';
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input id='degree-toggle' />
Mosè Raguzzini
  • 15,399
  • 1
  • 31
  • 43
-1

There's several issues here. Firstly, you're missing quotes around the value you're setting. Secondly you're using attr('value') instead of val().

However the bigger issue is that val() will not decode the entity you're setting. In order to achieve that you will need to use a <button> element then set its html(), like this:

$("#degree-toggle").html('&#8457;');
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button type="button" id="degree-toggle"></button>

Also note that neither <button> nor <input type="button"> elements have a checked attribute.

Rory McCrossan
  • 331,213
  • 40
  • 305
  • 339