What can I do to attain the below thing... The argument generated is bit weird!
function function1(argument1,argument2)
{
if argument1 = "
") do something;
}
"argument1" and "argument2" are generated by the CMS. I can't do anything with those contents.
Either it will generate:
<script type='text/javascript'>
document.write(function1("argument1","argument2"));
</script>
OR
<script type='text/javascript'>
document.write(function1("
","argument2"));
</script>
You can use String.prototype.trim():
function function1(argument1,argument2)
{
if(argument1.trim() == ''){
// do something
}
}
If you're worried about old browsers, you can implement the trim function yourself, see this question.
Related
So, I've found this JSFiddle example. In JSFiddle works well, the problem is that, even if I search any != from "advogados" (just testing), the browser goes to: http://www.site.com/index.html?procura=teste
No jQuery conflict, no html issue.
Here's JS
$("#procura").on("submit", function(event){
// prevent form from being truely submitted
event.preventDefault();
// get value of text box
name = $("#procura_texto").val();
// compare lower case, as you don't know what they will enter into the field.
if (name.toLowerCase() == "advogados")
{
//redirect the user..
window.location.href = "http://jornalexemplo.com.br/lista%20online/advogados.html";
}
else
{
alert("no redirect..(entered: " + name + ")");
}
});
If your javascript is somewhere in your HTML before your <form> your $("#procura") will be an empty set, so the submit-action won't be bound to anything. Try following code:
<html>
<head>
<script type="text/javascript" src="/path/to/your/jquery.js"></script>
<script type="text/javascript">
$(function() {
// This code will be run if your document is completely
// parsed by the browser, thus all below elements are
// accessible
$('#procura').on('submit', ....);
});
</script>
</head>
<body>
<form id="procura">...</form>
</body>
</html>
$(function() {}) is also known as $(document).ready(function() {}), (documentation)
You aren't defining the variable name. http://jsfiddle.net/zwbRa/59/
var name = $("#procura_texto").val();
Below is my html page:
<html>
<head>
<title>My Cat website</title>
</head>
<script type="text/javascript" src="script12.js"></script>
<body>
<h1>
My_first_cat_website
</h1>
</body>
</html>
Below is my JavaScript:
window.onload=initall;
function initall()
{
var ans=document.getElementsByTagName('a')[0].firstChild.data;
alert(ans);
if(ans<10)
{
alert(ans);
}
var newans=ans.subString(0,9)+"...";
}
Here my code is not going into if block. My requirement is if var "ans" length is above 10 then append it with ... else throw an alert directly. Can anyone help me?
Here is Solution using data property
window.onload=initall;
function initall()
{
var ans=document.getElementsByTagName('a')[0].firstChild.data;
if(ans.length<10)
{
alert("hmmm.. its less then 10!");
}
var newans= ans.substring(0,9)+"...";
document.getElementsByTagName('a')[0].firstChild.data = newans;
}
Here is it live view you wise to check example: http://jsbin.com/obeleh
I have never heard of the data property on a DOM element. Thanks to you, I learned it's a property on textNode elements (the same as nodeValue).
Also, using getElementsByTagName when the ID is available is unperformant.
subString doesn't work, it is substring. The case is important for methods as javascript is case sensitive (like most programming languages).
The other thing you're missing is an else. In your code, the var newans... will always be ran.
Here is something working:
window.onload = function() {
var ans = document.getElementById( 'message' ).textContent;
if ( ans.length < 10 ) {
alert( ans );
}
else {
var newans = ans.substring( 0, 9 ) + '...';
}
}
I would like to print the content of a script tag is that possible with jquery?
index.html
<script type="text/javascript">
function sendRequest(uri, handler)
{
}
</script>
Code
alert($("script")[0].???);
result
function sendRequest(uri, handler)
{
}
Just give your script tag an id:
<div></div>
<script id='script' type='text/javascript'>
$('div').html($('#script').html());
</script>
http://jsfiddle.net/UBw44/
You can use native Javascript to do this!
This will print the content of the first script in the document:
alert(document.getElementsByTagName("script")[0].innerHTML);
This will print the content of the script that has the id => "myscript":
alert(document.getElementById("myscript").innerHTML);
Try this:
console.log(($("script")[0]).innerHTML);
You may use document.getElementsByTagName("script") to get an HTMLCollection with all scripts, then iterate it to obtain the text of each script. Obviously you can get text only for local javascript. For external script (src=) you must use an ajax call to get the text.
Using jQuery something like this:
var scripts=document.getElementsByTagName("script");
for(var i=0; i<scripts.length; i++){
script_text=scripts[i].text;
if(script_text.trim()!==""){ // local script text
// so something with script_text ...
}
else{ // external script get with src=...
$.when($.get(scripts[i].src))
.done(function(script_text) {
// so something with script_text ...
});
}
}
The proper way to get access to current script is document.scripts (which is array like HTMLCollection), the last element is always current script because they are processed and added to that list in order of parsing and executing.
var len = document.scripts.length;
console.log(document.scripts[len - 1].innerHTML);
The only caveat is that you can't use any setTimeout or event handler that will delay the code execution (because next script in html can be parsed and added when your code will execute).
EDIT: Right now the proper way is to use document.currentScript. The only reason not to use this solution is IE. If you're force to support this browser use original solution.
Printing internal script:
var isIE = !document.currentScript;
function renderPRE( script, codeScriptName ){
if (isIE) return;
var jsCode = script.innerHTML.trim();
// escape angled brackets between two _ESCAPE_START_ and _ESCAPE_END_ comments
let textsToEscape = jsCode.match(new RegExp("// _ESCAPE_START_([^]*?)// _ESCAPE_END_", 'mg'));
if (textsToEscape) {
textsToEscape.forEach(textToEscape => {
jsCode = jsCode.replace(textToEscape, textToEscape.replace(/</g, "<")
.replace(/>/g, ">")
.replace("// _ESCAPE_START_", "")
.replace("// _ESCAPE_END_", "")
.trim());
});
}
script.insertAdjacentHTML('afterend', "<pre class='language-js'><code>" + jsCode + "</code></pre>");
}
<script>
// print this script:
let localScript = document.currentScript;
setTimeout(function(){
renderPRE(localScript)
}, 1000);
</script>
Printing external script using XHR (AJAX):
var src = "https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js";
// Exmaple from:
// https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest/Using_XMLHttpRequest
function reqListener(){
console.log( this.responseText );
}
var oReq = new XMLHttpRequest();
oReq.addEventListener("load", reqListener);
oReq.open("GET", src);
oReq.send();
*DEPRECATED*: Without XHR (AKA Ajax)
If you want to print the contents of an external script (file must reside on the same domain), then it's possible to use a <link> tag with the rel="import" attribute and then place the script's source in the href attribute. Here's a working example for this site:
<!DOCTYPE html>
<html lang="en">
<head>
...
<link rel="import" href="autobiographical-number.js">
...
</head>
<body>
<script>
var importedScriptElm = document.querySelector('link[rel="import"]'),
scriptText = scriptText.import.body.innerHTML;
document.currentScript.insertAdjacentHTML('afterend', "<pre>" + scriptText + "</pre>");
</script>
</body>
</html>
This is still experimental technology, part of web-components. read more on MDN
I have a javascript method which is receiving a UTF-8 encoded string (ViewBag.errorText), and uses this as a parameter to a new function.
The problem is that the text displayed in show_error_dialog is displaying the html escaped characters (æø etc') and not the intended ("æåø" etc.).
I presume the problem is the enclosed <text> tags but can't seem to get around this.
<script type="text/javascript" charset="utf-8">
function performLoadOperations() {
#if(ViewBag.errorText!= null) {
<text>show_error_dialog('#ViewBag.errorText');</text>
}
}
</script>
I think all Razor-inserted text is HTML-encoded by default. Use Html.Raw() to pass the string unencoded.
<script type="text/javascript" charset="utf-8">
function performLoadOperations() {
#if(ViewBag.errorText!= null) {
<text>show_error_dialog('#Html.Raw(ViewBag.errorText)');</text>
}
}
</script>
Use:
#Html.Raw(Ajax.JavaScriptStringEncode(Model))
to safely insert values into javascript
just use javascript escape function:
function encode_utf8( s )
{
return unescape( encodeURIComponent( s ) );
}
function decode_utf8( s )
{
return decodeURIComponent( escape( s ) );
}
I'm not sure but i think there was unescape() function with js. Try to pass your text with it. It might help
Classic javascript:
var myvar = document.getElementById("abc");
abc.value += "test";
abc.value += "another test";
Jquery:
$("#abc").val($("#abc").val()+"test");
$("#abc").val($("#abc").val()+"another test");
Is there a way to make my Jquery prettier, maybe with a hidden += function that I could use? I know that .val() is not an attribute, but I feel there must be a way to make this code more beautiful to look at...
Something like this would be great:
$("#abc").valueAttribute += "test"
$("#abc").val().content += "test"
$("#abc").val().add("test")
You could go back to the original DOM element.
$("#abc").get(0).value += "test";
Otherwise, you'd have to write a plugin
$.fn.appendVal = function (newPart) {
return this.each(function(){ $(this).val( $(this).val() + newPart); });
};
$("#abc").appendVal("test");
Since jQuery 1.4, it is possible to pass a function to .val() which gets the current value as second argument:
$("#abc").val(function(i, val) {
return val + "test";
});
I've never come across anything like that, doesn't mean it doesn't exist though.
I usually just store val() in a temporary variable and do the manipulation on that, then call val(temp) in a separate line. It spreads the operation out to three or more lines, but it's still more readable than .val(.val() + ""), IMO. It also scales better than +=, if you have a more complicated expression to do to the value.
var temp = $(".abc").val();
temp += "test";
$(".abc").val(temp);
$() returns a selection; it doesn't return the actual resulting object (although in practice, it simply returns a list of the actual objects). If you want to mutate the object's .value property, you can do this:
$('.abc').each(function(){ this.value += foo; });
If you like, you can create functions that operate on selections, such as .add(), which could be implemented like this:
jQuery.fn.extend({ add: function(k,v) { this[k](this[k]()+v); } });
which can then be used like this:
$('.abc').add('val', foo);
...but I don't think this is any better than using $().each()
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />
<title>Untitled Document</title>
<script type="text/javascript" src="jquery-1.3.2.min.js"></script>
<script type="text/javascript">
(function($){
$.fn.valInc = function(vadd)
{
var val = $(this).val() + '' + vadd;
$(this).val(val);
}
})(jQuery);
$(function(){
$("#tst").valInc('test 2');
});
</script>
</head>
<body>
<input id='tst' value="test" />
</body>
</html>