Placeholder for double and single quotes - javascript

I have a function which returns a table of given size containing given content in each cell displaying it in the div with the given ID.
generate_table(4,4,'Cell Content','display')
To test this function I have used onload on my body tag. The function does work. However i wish to have an input of type number inside the cells so
<body onload="generate_table(4,4,'<input type='number'>','display')">
The problem, if you did not see it is that the string that I am passing as the content of the cells gets cut at the ' before number.

Escape the characters:
<body onload="generate_table(4,4,'<input type=\"number\">','display')">
Or call the function from a JavaScript file or even embed it in your HTML file:
<html>
...
<script>
document.querySelector('body').addEventListener('load', function() {
generate_table(4,4,'<input type="number">','display')
}, false);
</script>

Don't use inline handlers. Add a listener properly using JavaScript instead, and you won't have to worry about any escaping issues.
<body>
and, in the JavaScript:
document.body.addEventListener('load', () => generate_table(4,4,'Cell Content','display'));

Related

remove element <script> in body

I got a script converter like this
var currency_data='USD,0.712497,0.01|AUD,0.5576,0.05|AED,0.194009,0.25|BRL,0.248647,0.01|JPY,0.00594888,1|GBP,1.09482,0.01|CAD,0.572195,0.01|CNY,0.115772,0.5|EUR,0.795717,0.01|INR,0.0115219,0.1|ILS,0.178705,0.01|QAR,0.195741,1|RUB,0.0114246,0.01|SAR,0.189999,1|SGD,0.522129,0.01|THB,0.0220219,0.25';
var currency_sdrPer=new Array(),currency_Unit=new Array();currency_make_arrays();function currency_make_arrays(){var d=currency_data.split("|");for(var e=0;e<d.length;e++){var b=d[e].split(","),f=b[0];currency_sdrPer[f]=b[1];currency_Unit[f]=b[2]}};
function currency_rnd(h,e){h=Math.round(h/e)*e+".";var g=(e+".").split("."),c=h.split("."),b=c[1],a=g[1].length,d=b.length;if(d>a){b=b.substring(0,a)}for(var f=0;f<a-d;f++){b+="0"}return c[0]+(a==0?"":"."+b)}function currency_convert(f,d,c){var e=currency_sdrPer;if(!e[d]||!e[c]){return""}return currency_format(f*(e[d]/e[c]),currency_Unit[c])}function currency_format(c,f){var g=typeof currency_thousandsSeparator=="string"?currency_thousandsSeparator:",",b=typeof currency_decimalSeparator=="string"?currency_decimalSeparator:".",f=(typeof currency_decimalDigits=="number")?(1/Math.pow(10,currency_decimalDigits)):(typeof f=="number"?f:0.01),j=typeof currency_thousandsSeparatorMin=="number"?currency_thousandsSeparatorMin:3;if(typeof currency_round=="boolean"&&currency_round){c=currency_rnd(c,f)}var i=(""+c).split("."),h=i[0],e=i.length>1?b+i[1]:"",a=/(\d+)(\d{3})/;if(g!=""){while(a.test(h)&&h.length>j){h=h.replace(a,"$1"+g+"$2")}}return h+e};
function conversion(e,d,c){document.write(currency_convert(e,d,c))}function currency_getRateHTML(d,c){var g=currency_convert(1,d,c);if(g==""){return""}var f=d+"_"+c+".html";if(c<d){f=c+"_"+d+".html"}f="http://coinmill.com/"+f;var e=unescape("%3Ca+href%3D%22%24link%22%3E%24from_the_name+is+worth+%3Cb%3E%24rate%3C/b%3E+%24to_plural_name%3C/a%3E%3Cbr%3E");if(typeof currency_template!="undefined"){e=currency_template}return e.replace("$link",f).replace("$rate",g).replace("$from_abbrev",d).replace("$from_name",d).replace("$from_plural_name",d+"s").replace("$from_the_name","the "+d).replace("$to_abbrev",c).replace("$to_name",c).replace("$to_plural_name",c+"s").replace("$to_the_name","the "+c)}function currency_showRate(d,c){document.write(currency_getRateHTML(d,c))}function currency_showRates(){for(var e=0;e<currency_rate_list.length;e++){var d=currency_rate_list[e];e++;if(e<currency_rate_list.length){var c=currency_rate_list[e];currency_showRate(d,c)}}}if(typeof currency_rate_list!="undefined"){currency_showRates()};
after element <head>
<script>
var currency_round=true;
</script>
and the calling inside after <body>:
<div>USD 60.61 = GBP <script>conversion(60.61,"USD","GBP");</script></div>
however, I really mind that there are <script> and </script> element inside body where as it's not good for html validation.
Is there any way to change it to be or element?
If you really want to move it out of the body (and there doesn't seem to be any point in doing so, it isn't invalid to have a script there) then you will need to:
Create an element in the body to put the content in
Replace all the document.write statements with DOM methods
Call the conversion function after the element becomes available (e.g. with an load event handler)
I think there is no other way to use.
so use script within body.

Using one onchange javascript function for all div

I have multiple <textarea>, sometime they are blank and sometime they are filled with text.
I want to insert a simple text code such as "<check>" which will automatically change to a check (\u2713).
Presently, my code is like this:
<textarea name="1-S" onchange="check(this.value)">
<check> //an input written by a user
</textarea>
<textarea name="1-NI" onchange="check(this.value)">
<check> //an input written by a user
</textarea>
<textarea name="1-C" onchange="check(this.value)">
<check> //an input written by a user
</textarea>
(This block of <textarea> gets repeated, but of course, with different name in each one.)
<script type="text/javascript">
function check(str){
var res = str.replace("<check>", "\u2713");
????
}
</script>
The output will then replace <check> into actual check symbol (\u2713)
The challenge is, I don't want to have to add ID to every <textarea> and then write a script for each one. So is there a way for me to use this one script to apply to all <textarea>???
Many thanks in advance!
You could use the getElementsByTagName method to create an array of your text area tags.
Since you're using jQuery:
$("textarea").each(function(index, textarea) {
// do replacement here
});
Note that you need to use HTML entities to put <check> into a textarea: <check>
Also, you can put a checkmark in without any Javascript like this: ✓
Yes. You can bind an event handler to all elements of a type using jquery.
$('textarea').on('change', function() {
var text = $(this).val();
if (text.match(/\<check\>/)) {
$(this).val(text.replace(/\<check\>/, "\u2713"));
}
});
The benefit of doing it this way is that you can remove your inline 'onchange' handlers from the html and consolidate your validation logic strictly to JavaScript.
To replace the actual textarea content you need to update the value of the textarea with the result of your String-replace regexp. var text = $(this).val() is just assigning the content of the textarea to the variable text, it's not a reference to the innerHTML portion of your textarea.
On a sidenote if you'd like to allow users to use shortcodes in a form, prefer square bracket syntax, e.g., [check].

jQuery "add" Only Evaluated When "appendTo" Called

this has been driving me crazy since yesterday afternoon. I am trying to concatenate two bodies of selected HTML using jQuery's "add" method. I am obviously missing something fundamental. Here's some sample code that illustrated the problem:
<html>
<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>
</head>
<body>
<p id="para1">This is a test.</p>
<p id="para2">This is also a test.</p>
<script>
var para1 = $("#para1").clone();
var para2 = $("#para2").clone();
var para3 = para1.add(para2);
alert("Joined para: " + para3.html());
para3.appendTo('body');
</script>
</body>
</html>
I need to do some more manipulation to "para3" before the append, but the alert above displays only the contents of "para1." However, the "appendTo appends the correct, "added" content of para1 and para2 (which subsequently appears on the page).
Any ideas what's going on here?
As per the $.add,
Create a new jQuery object with elements added to the set of matched elements.
Thus, after the add, $para3 represents a jQuery result set of two elements ~> [$para1, $para2]. Then, per $.html,
Get the HTML contents of the first element in the set of matched elements or set the HTML contents of every matched element.
So the HTML content of the first item in the jQuery result ($para1) is returned and subsequent elements (including $para2) are ignored. This behavior is consistent across jQuery "value reading" functions.
Reading $.appendTo will explain how it works differently from $.html.
A simple map and array-concat can be used to get the HTML of "all items in the result set":
$.map($para3, function (e) { return $(e).html() }).join("")
Array.prototype.map.call($para3, function (e) { return $(e).html() }).join("")
Or in this case, just:
$para1.html() + $para2.html()
Another approach would be to get the inner HTML of a parent Element, after the children have been added.

Find and replace occurrence of string in whole html itself

Assume
<html>
<head>....</head>
<body>
.
. // Occurrences are here
.
</body>
</html>
I do
$(function()
{
$('html').html() = $('html').html().replace(/strToFind/g,'somethingElse');
});
in head, but it does't work. How I do to find and replace all occurrence of string in html document itself (not store in variable)?
Thanks
.html() is a function that returns the HTML, you can't assign to it. If you want to change the HTML of an object in jQuery, you put the new HTML as a parameter to the function:
$('html').html($('html').html().replace(/strToFind/g,'somethingElse'));
$('html').html() would return the html string , but won't set it.
You can use this function
function rep_all()
{
var str = $('html').html();
str.replace('strtofind','strtoreplace');
$('html').html(str);
}
.html() is something which writes on the html page it is not like variable so you can't assign anythig to it. you need to put the value inside it.like this:
$('html').html( $('html').html().replace(/strToFind/g,'somethingElse'));
see here:http://api.jquery.com/html/
It's been answered that the .html() is not assignable, you would have to pass the replaced content as a parameter.
Just to point out, it is very uncommon to replace the whole page's html content.
As you defined that the contents to be replaced are inside the body, you should at least (still not good) target only the body:
$('body').html($('body').html().replace(/strToFind/g,'somethingElse'))

Passing HTML string to JavaScript function

I have a value that I'm currently accessing and passing to a JavaScript function through an onclick.
Text
An example value that I'd receive from the getText method is shown below.
<h1>My Header</h1><br />My text
This value is then passed to my openTextWindow method.
function openTextWindow(inText) {
myWindow = window.open('','','width=500, height=300');
myWindow.document.write(inText);
myWindow.focus();
}
For some reason, the value stored in inText doesn't match the string with HTML tags that I showed above. It ends up looking like this.
"<lt/>h1<gt/>My Header<lt/>/h1<gt/><lt/>br /<gt/>My text
When inText is written to myWindow, I want that new window to render with the text My Header within a styled header and My text on a line below that. I've tried replacing and escaping characters with no luck. Any ideas on how to fix this or a better way to accomplish what I'm trying to do? Thanks!
You can stash your HTML in a hidden DIV or textarea, then grab that from your function instead of trying to pass it inline.
Text
<div id="DIV1" style="display:none"><%=myVar.varDefinition.getText()%></div>
JS:
function openTextWindow(divName) {
var inText = document.getElemenyById(divName).innerHTML;
myWindow = window.open('','','width=500, height=300');
myWindow.document.write(inText);
myWindow.focus();
}

Categories

Resources