Inserting HTML character entities with JQuery - javascript

I'm trying to create a tool that allows me to insert different Spanish characters into a text box such as the inverted question mark. I've currently got the following, but this returns:
function (e){var n,r,i,o=this[0];{if(arguments.length)return i=x.isFunction(e),this.each(function(n){var o;1===this.nodeType&&(o=i?e.call(this,n,x(this).val()):e,null==o?o="":"number"==typeof o?o+="":x.isArray(o)&&(o=x.map(o,function(e){return null==e?"":e+""})),r=x.valHooks[this.type]||x.valHooks[this.nodeName.toLowerCase()],r&&"set"in r&&r.set(this,o,"value")!==t||(this.value=o))});if(o)return r=x.valHooks[o.type]||x.valHooks[o.nodeName.toLowerCase()],r&&"get"in r&&(n=r.get(o,"value"))!==t?n:(n=o.value,"string"==typeof n?n.replace(V,""):null==n?"":n)}}¿
HTML
<div class="container">
<textarea id="text"></textarea>
<div id="one">¿</div>
JS
$('document').ready(function() {
$('#one').click(function() {
$('#text').val($('#text').val + '¿');
});
});
Any ideas on why I'm receiving this output? Also do HTML entities work within textboxes, if not how would I do so? No errors appear in the console.
JSFiddle

$("#text").val is a function, which you are supposed to call.
That said, jQuery is massive overkill for such a trivial task:
document.getElementById('one').onclick = function() {
document.getElementById('text').value += "\u00bf";
}
Note that \u00bf is the appropriate JavaScript escape sequence for ¿ - bf being 191 in hexadecimal.
EDIT: Alternatively, just hold Alt and type 0191 on your keypad. This will produce ¿ directly where you are typing, instead of at the end of the input which is what your JS does.

Try this one. Worked in your fiddle.
$(function() {
$('#one').on('click', function() {
$('#text').val($('#text').val() + "¿");
});
});
Update: I posted spanish sign of question instead of its ASCII, changed $(document).ready to a shorter way $(function(), and added brackets after val().

Related

why is ® not working when used with jquery

I am having a problem I want to attach the registered trademark symbol a button and I want it to be done with jquery because there are lots and lots of buttons that require the sign when I used it with html for example(below) it worked.
<input type="button" class="button_a" value="Value ®" />
But when I used jquery as below it returns as plain text:
$('.button_a').each(function(){
$(this).attr("value",$(this).attr("value")+" ®");
});
I don't want to waste my time and space by putting ® in all the button's values so I want it to be done in jquery but what am I doing incorrect.
I know it's a sluggish question but please someone help out me in this question
Javascript may be also used.
For more info please comment and ask
Thanks....
® is being rendered as a text string, but you can use unicode \u00AE
$('.button_a').each(function(){
this.value = this.value +" \u00AE";
});
http://jsfiddle.net/fbuohvm1/
or just ®:
$('.button_a').each(function(){
this.value = this.value +" ®";
});
http://jsfiddle.net/fbuohvm1/1/
Because, while the DOM you are manipulating was initialised from an HTML document, you are now dealing with DOM and not HTML. You are writing the value as text not as HTML.
You need to use either a literal character ("®") or a JavaScript escape sequence ("\u00AE").
You have to encode it first before setting the value of textbox.
$('.button_a').each(function () {
$(this).val("value " + $("<div/>").html('®').text());
});
$("<div/>").html('®').text() will return the encoded value.
Demo: https://jsfiddle.net/tusharj/t2gwptys/
you need to process content by html(), because html entities is manipulate by html() function, try this code.
$('.button_a').each(function(){
$(this).val($("<p/>").html($(this).val()+" ®").html());
});
Use a hidden div.
$('.button_a').each(function(){
var decoded = $('<div/>').html('®').text();
$(this).val($(this).val() + ' ' + decoded);
});
See Sample
In your case plain js is more straightforward:
$('.button_a').each(function(){
this.value += " ®";
});
-- EDIT --
Unfortunately this is still escaped, in fact you need
this.value += " \u00AE";

How to escape single quotes or double quotes within jquery's append(), onclick(), alert() at one time?

I have a question when i develop my html with javascript.
What finally I want in html is:
<div id="test">
<div onclick="alert("it's a test.")">Show</div>
</div>
But in code I want it be realized like this:
<div id="test"></div>
<script>
var tmp="it's a test.";//be careful, there must be a single quote in this variable
$('#test').append("<div onclick='alert(\" "+tmp+" \")'>Show</div>");
</script>
In firebug it shows:
<div id="test">
<div ")'="" test.="" a="" s="" onclick="alert(" it">Show</div>
</div>
So i think it's an escaping problem. But I think it has minimum 3 levels of depth.
Anyone can help me? Thanks!
Don't use jQuery to write inlined script. Replace
$('#test').append("<div onclick='alert(\" "+tmp+" \")'>Show</div>");
with
$('<div>').click(function(){ alert(" "+tmp+" ") }).text('Show').appendTo('#test');
This way
you don't eval the code on click
syntax errors are direcly detected
you won't have quote escaping problem
the code is more readable
you'll have a direct binding, without useless selector resolution
when you need a variable (for example temp), you don't need to put it in the global scope, it can be in the scope of the element addition
To answer your question in comment, you can either
use an intermediate closure to enclose the value at the time of looping (example here)
or use the eventData argument of jQuery's click function.
Example of using jQuery's eventData argument :
var names = ['A', 'B'];
for (var i=0; i<names.length; i++) {
$('<div>').text('link '+(i+1)).click(names[i], function(e) {
alert('Name : ' + e.data);
}).appendTo(document.body);
}
Demonstration
Backslashes can be used to escape special characters
<div id="test"></div>
<script>
var tmp=\"it's a test.\";//be careful, there must be a single quote in this variable
$('#test').append("<div onclick='alert(\" "+tmp+" \")'>Show</div>");
</script>
That should work hopefully, if not it should help you get started
An easier way is to append new div to your #test then use event delegation to bind click event for your newly added div like this:
$('#test').append("<div class='newDiv'>Show</div>");
$('#test').on('click','.newDiv',function() {
alert("it's a test.");
});

How to stop jQuery converting html entities into valid HTML?

Weeding out a few issues with my site when I found this curious issue.
<img src=".." width="1200" height="1200" alt="<script>alert("foo");</script>" />
The CMS appears to have done it's jobs and converted <script>alert('foo')</script> into what you see above. I display the caption with the following code.
site.caption = {
container : $('#caption'),
set : function(str) {
if (str && str.length) {
this.container.html('<span>'+str+'</span>').show(); console.log(str);
} else {
this.container.hide();
}
}
};
The function is called like this.
site.caption.set($(nextSlideElement).find('img').attr('alt'));
When this line runs an alert box pop's up with the text 'foo'. When I do the following in the site.caption.set function it shows the valid html.
console.log(str);
I am using jQuery 1.8.3. Does anyone know why this is happening? How do I show the text <script>alert('foo')</script> without it being run?
jQuery isn't converting it, the browser is when it parses the HTML.
If you want to treat a string as text instead of HTML, then use jQuery('foo').text(value) instead of jQuery('foo').html(value).
this.container.html('<span>'+str+'</span>')
Never concatenate HTML strings. Let jQuery do it for you. Get into this habit and you won't run into this problem.
this.container.empty().append($('<span/>').text(str));

String manipulation using jQuery

I am wondering how I would remove the vowels from a word on a button click?
Here is what I am trying to do - http://www.marcia.bnmla.com/~marcia/project0.html
I need to use jQuery to remove the vowels in the second box so it displays only consonants when you click the button. I have it where it displays "MRC" as text when the button is clicked and I need to redo it using string manipulation so I can change the word to anything in my code and it will remove the vowels in that word. I am obviously new at this. Please help me!
Here is my code:
<div id="marcia_box">
<p id="marciatext">marcia</p>
<div id="marcia_boxBtn"><button id="marciaBtn">Marcia</button></div>
</div>
$("#marciaBtn").click(function() {
$("#marcia_box").css("background-color","#999");
$("#marciatext").html('mrc');
});
Do you really need jQuery? What about plain old JavaScript?
"abcdef".replace(/[aeiou]/gi, "") // => "bcdf"
How's that?
jQuery allows you to pass a function to .html, which should return a new HTML string. jQuery will pass the old HTML, so you can do something like this:
$("#marciatext").html(function(i, current) {
return current.replace(/[aeiou]/g, "");
});
demo
This one will help you now and in the future for other transformations
specially for toggling between two array keys
var c=0, text=['marcia', 'mrc'];
$("#marciaBtn").click(function() {
$("#marciatext").html( text[ ++c%2 ] );
});
As shown by Jarrett Meyer, removing the vowels has nothing with the jQuery part. But just to show you how to put it together with jQuery (since you said you is really new in it), here is a sample:
$("#marciatext").text($("#marciatext").text().replace(/[aeiou]/gi, ""));

Why JavaScript converts my < into >

JavaScript converts my < into >. I want to alert it but my message is with encoded marks like ##&*()}{>?>? - how to display it normally but prevent from executing as HTML code?
<span id="ID" onClick="alertIt(this.id);">
<p>Some string with special chars: ~!##&*()}{>?>?>|{">##$#^#$</p>
<p>Why when clicked it gives something like this:</p>
<p>'<br>
Some string with special chars: ~!##&*()}{>?>?>|... and so on
<br>'</p>
</span>
<script type="text/javascript">
function alertIt(ID)
{
var ID = ID;
var content = document.getElementById(ID).innerHTML;
alert(content);
}
</script>
Use innerText instead of innerHTML. http://jsfiddle.net/WVf95/
Your problem is that you use the wrong approach to get the text to display with alert().
Some characters are illegal in HTML text (they are used for HTML tags and entities). innerHTML will make sure that text is properly escaped (i.e. you can see tags and escaped text).
If you want to see tag and text in alert(), there is no solution.
If you want only the text, then you will have to extract it yourself. There is no built-in support for that. It's also not really trivial to implement. I suggest to include jQuery in your page; then you can get the text with:
function alertIt(ID) {
alert($(ID).text());
}
Using textContent instaed of innerHTML or innerText is a solution.

Categories

Resources