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();
Related
I know this has been asked a lot on here, but all the answers work only with jQuery and I need a solution without it.
So after I do something, my Servlet leads me to a JSP page. My JS function should populate a drop down list when the page is loaded. It only works properly when the page is refreshed tho.
As I understand this is happening because I want to populate, using innerHTML and the JS function gets called faster then my HTML page.
I also get this error in my Browser:
Uncaught TypeError: Cannot read property 'innerHTML' of null
at XMLHttpRequest.xmlHttpRequest.onreadystatechange
I had a soulution for debugging but I can't leave it in there. What I did was, every time I opened that page I automatically refreshed the whole page. But my browser asked me every time if I wanted to do this. So that is not a solution that's pretty to say the least.
Is there something I could do to prevent this?
Edit:
document.addEventListener("DOMContentLoaded", pupulateDropDown);
function pupulateDropDown() {
var servletURL = "./KategorienHolen"
let xmlHttpRequest = new XMLHttpRequest();
xmlHttpRequest.onreadystatechange = function () {
if (xmlHttpRequest.readyState === 4 && xmlHttpRequest.status === 200) {
console.log(xmlHttpRequest.responseText);
let katGetter = JSON.parse(xmlHttpRequest.responseText);
JSON.stringify(katGetter);
var i;
for(i = 0; i <= katGetter.length -1; i++){
console.log(katGetter[i].id);
console.log(katGetter[i].kategorie);
console.log(katGetter[i].oberkategorie);
if (katGetter[i].oberkategorie === "B") {
document.getElementById("BKat").innerHTML += "" + katGetter[i].kategorie + "</br>";
} else if (katGetter[i].oberkategorie === "S") {
document.getElementById("SKat").innerHTML += "" + katGetter[i].kategorie + "</br>";
} else if (katGetter[i].oberkategorie ==="A") {
document.getElementById("ACat").innerHTML += "" + katGetter[i].kategorie + "</br>";
}
// document.getElementsByClassName("innerDiv").innerHTML = "" + katGetter.kategorie + "";
// document.getElementById("test123").innerHTML = "" + katGetter.kategorie + "";
}
}
};
xmlHttpRequest.open("GET", servletURL, true);
xmlHttpRequest.send();
}
It can depend on how + when you're executing the code.
<html>
<head>
<title>In Head Not Working</title>
<!-- WILL NOT WORK -->
<!--<script>
const p = document.querySelector('p');
p.innerHTML = 'Replaced!';
</script>-->
</head>
<body>
<p>Replace This</p>
<!-- Will work because the page has finished loading and this is the last thing to load on the page so it can find other elements -->
<script>
const p = document.querySelector('p');
p.innerHTML = 'Replaced!';
</script>
</body>
</html>
Additionally you could add an Event handler so when the window is fully loaded, you can then find the DOM element.
<html>
<head>
<title>In Head Working</title>
<script>
window.addEventListener('load', function () {
const p = document.querySelector('p');
p.innerHTML = 'Replaced!';
});
</script>
</head>
<body>
<p>Replace This</p>
</body>
</html>
Define your function and add an onload event to body:
<body onload="pupulateDropDown()">
<!-- ... -->
</body>
Script needs to be loaded again, I tried many options but <iframe/> works better in my case. You may try to npm import for library related to your script or you can use the following code.
<iframe
srcDoc={`
<!doctype html>
<html>
<head>
<style>[Style (If you want to)]</style>
</head>
<body>
<div>
[Your data]
<script type="text/javascript" src="[Script source]"></script>
</div>
</body>
</html>
`}
/>
Inside srcDoc, it's similar to normal HTML code.
You can load data by using ${[Your Data]} inside srcDoc.
It should work :
document.addEventListener("DOMContentLoaded", function(){
//....
});
You should be using the DOMContentLoaded event to run your code only when the document has been completely loaded and all elements have been parsed.
window.addEventListener("DOMContentLoaded", function(){
//your code here
});
Alternatively, place your script tag right before the ending body tag.
<body>
<!--body content...-->
<script>
//your code here
</script>
</body>
I am trying to retain data in a localstorage after reload but it is not working
this is my attempt
<script>
window.onbeforeunload = function() {
localStorage.setItem(name, $('#inputName').val());
}
window.onload = function() {
var name = localStorage.getItem(name);
if (name !== null) $('#inputName').val(name);
alert(name);
}
</script>
<html>
<body>
<input type="text" id="inputName" placeholder="Name" required>
</body>
</html>
on refreshing the page after entering data on the form it keeps alerting null. kindly assist
In your onbeforeunload, name is the name of the window (because you haven't given it any other value, and browsers have a global name property which is the name of the window — it's usually blank).
In this line:
var name = localStorage.getItem(name);
...it's undefined, because of the var name.
You need to use a proper name, for instance:
window.onbeforeunload = function() {
localStorage.setItem("your-setting-name", $('#inputName').val());
};
window.onload = function() {
var name = localStorage.getItem("your-setting-name");
if (name !== null) $('#inputName').val(name);
alert(name);
};
Also note charlietfl's oint that if you don't want to alert null on the first visit to the page, you need to put the alert in the body of the if:
window.onload = function() {
var name = localStorage.getItem("your-setting-name");
if (name !== null) {
$('#inputName').val(name);
alert(name);
}
};
Otherwise, it'll alert null on the first visit and then whatever the last value was otherwise.
(Also note that I've added some missing ;. Automatic Semicolon Insertion will add these particular ones, but it's an error-correction mechanism, so I'd advise not relying on it.)
Other issues:
You're using jQuery functions, but haven't shown any script tag including jQuery on the page.
You have the closing </html> tag before the <input ...> tag.
Here's a fiddle with the above fixed (can't use Stack Snippets with local storage): https://jsfiddle.net/un86not0/ Full working page:
<!doctype html>
<html>
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=Edge">
<title>Example</title>
</head>
<body>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
<script>
window.onbeforeunload = function() {
localStorage.setItem("your-setting-name", $('#inputName').val());
};
window.onload = function() {
var name = localStorage.getItem("your-setting-name");
if (name !== null) {
$('#inputName').val(name);
alert(name);
}
};
</script>
<input type="text" id="inputName" placeholder="Name" required>
</body>
</html>
The variable name haven't been initiated yet you already used it as a value reference. Maybe it wasn't working well because of that?
Here in this solution, you can separately reference the local storage item without using the variable name which might have caused it not to work.
<script>
window.onbeforeunload = function() {
localStorage.setItem('myItem', $('#inputName').val());
}
window.onload = function() {
var name = localStorage.getItem('myItem');
if (name !== null) $('#inputName').val(name);
alert(name);
}
</script>
So I'm trying to start on a to do list in html5 + jQuery using Local Storage, but for some odd reason I can't get the jQuery to make a local storage key.
Here is my code. I want it to collect the value of the input box, add it to local storage, and then print the code in the div named.
$('#taskEntryForm').submit(function () {
if ($('#taskInput').val() !== '') {
var input_value = $('#taskInput').val();
var stored_input = this.localStorage.setItem('task_',input_value);
var task = this.localStorage.getItem('task_');
$('#taskList').append("<br>"+task);
};
return false;
});
and then the HTML...
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
<script src="shit.js"></script>
</head>
<div id="cNew">
<form id="taskEntryForm">
<input id="taskInput" name="taskInput" autofocus></form>
</div>
<div id="taskList"></div>
</html>
In your code this stands for form. Local storage object is not part of the form, it is a part of window. You should change this (which represents form) to window, or remove this at all (because window.localStorage is identical to just localStorage):
$('#taskEntryForm').submit(function () {
if ($('#taskInput').val() !== '') {
var input_value = $('#taskInput').val();
var stored_input = localStorage.setItem('task_',input_value); // <- removed 'this'
var task = localStorage.getItem('task_'); // <- removed 'this'
$('#taskList').append("<br>"+task);
};
return false;
});
Here is a working jsFiddle
Is it possible to pass the totalScore var to another page onclick so that it can be displayed there? ex: click submit link it goes to yourscore.html and display the score on page
$("#process").click(function() {
var totalScore = 0;
$(".targetKeep").each( function(i, tK) {
if (typeof($(tK).raty('score')) != "undefined") {
totalScore += $(tK).raty('score');
}
});
alert("Total Score = "+totalScore);
});
Let we suppose that your HTML may be as follows:
<!DOCTYPE html>
<html>
<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.1/jquery.min.js"></script>
<script>
$(document).ready(function(){
$("#process").click(function() {
var totalScore = 0;
/*
Your code to calculate Total Score
Remove the next line in real code.
*/
totalScore = 55; //Remove this
alert("Total Score = "+totalScore);
$("#submit-link").attr('href',"http://example.com/yourscore.html?totalScore="+totalScore);
});
});
</script>
<meta charset=utf-8 />
<title>JS Bin</title>
</head>
<body>
<button id="process">Process</button>
<br />
Submit Total Score
</body>
</html>
Check out this DEMO
In yourscore.html you may able to know more in the following queation to extract the URL parameter from the URL:
Parse URL with jquery/ javascript?
This is generally done by changing the url of the page. i.e. if you are going go to a new page, just do:
http://example.com/new/page?param1=test
If the page already exists in a new window (like a popup that you own), set the url to something new:
http://example.com/new/page#param
Open a window:
var win = window.open('http://example.com/new/page?totalscore'+totalscore,'window');
Change the location:
win.location.href='http://example.com/new/page?totalscore'+totalscore;
Other ways of doing this could be websockets or cookies or localstorage in HTML5.
if you are aiming to support more modern browsers the elegant solution could be to use sessionStorage or localStorage! Its extremely simple and can be cleared and set as you need it. The maximum size at the low end is 2mb but if your only storing INTs then you should be okay.
DOCS:
http://www.html5rocks.com/en/features/storage
http://dev.w3.org/html5/webstorage/
DEMO:
http://html5demos.com/storage
EXAMPLE:
addEvent(document.querySelector('#local'), 'keyup', function () {
localStorage.setItem('value', this.value);
localStorage.setItem('timestamp', (new Date()).getTime());
//GO TO YOUR NEXT PAGEHERE
});
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