How to stop an automatic refresh using JS - javascript

I'm using javascript to create a file explorer in my website.
I have a function wich read each file from my website and change them into a caracters chain with a chain.split() for each file.
Then, in the array created, I search words that I take from a form. And then, with an innerHTML, I rewrite my HTML page with the answers.
It works, but, when the page is rewrite, it automaticly refresh, and I lose all my search reults...
I tried to stop refresh with window.stop(), document.execCommand('stop'), and it's still refresh...
Here my form :
<form name="recherche" onsubmit="javascript:maFonction()">
<INPUT class="finder" type="text" name="maRecherche" placeholder="Enter your search"/>
<input class="press" type="submit" name="search" value="Search"/>
<p style="margin-left:5%">It may take five secondes...</p>
</form>
And here, the writing part of my JS function :
var mesResultats = "";
if (bin > 0)
{
a = 0;
mesResultats += 'your search <u><b>' + words + '</u></b> can be found here : <BR><BR>';
for (var i = 0; i < mesLiens.length; i++)
{
if (mesLiens[i] != mesLiens[i-1] )
{
var monLien = '<div style="margin-left:5%; margin-right:5%; text-align:justify;">' + mesTitres[a] + '' + '<BR></div>';
mesResultats += monLien + '<hr>';
}
a++;
}
}
else
{
var monLien = 'Homepage';
mesResultats += 'No answer corresponding to your search <u><b>' + words + '</u></b>... ' + monLien + '</div>';
}
elemnt = document.getElementById("result");
elemnt.innerHTML = mesResultats;
If anyone have an idea of how to keep my search results, thank you !
(PS : I can't show you with a link...)

Add return false into the onsubmit event, to don't refresh the page.
HTML :
<form name="recherche" onsubmit="return myFunction();">
Javascript :
function myFunction(){
return false;
}

In case someone has the same situation as me, the application was using <meta http-equiv="refresh" content="3"> and was refreshing the content every 3 seconds. The solution for me was to execute window.stop(); directly from the console.

Related

Submit a text string plus file - edited

I am trying to submit a text string (downloadstr) and 1 second later to submit a file.
I have to do this in plain JS/HTML (microcontroller webserver)
I submit the text using 'GET' to avoid the 'name=' in the string.
I submit the file using POST.
I need to access the file locally first to get the file size which is needed in the text string.
I can get it partially working - BUT
I cannot seem to change the <input id="DN" .value to the variable 'downloadstr' in JS.
NOTE ***** - There seems to be a problem with the JS variable 'downloadstr'.
I can give it any sort of textual value and it will upload fine, but the string ' LOAD(NAND,"EXT/tu480a.ppf?size=641&useack=1"); ' will upload a corrupted string. I cannot see what is wrong with this string.
It displays correctly, but will not upload.
This is the string that it tries to upload:
LOAD NAND � 2.186360E-77XT0.000000tu480a.ppf0.000000size134219621641 2779096485seack6039898721 %29 B
Can some kind person tell me whats wrong? Thanks. Chris
(I've updated via the comments - thanks)
<!DOCTYPE html>
<html>
<body>
<form id="predataform" method="get" action="/index.shtml" accept-charset="utf-8">
<input id="DN" type="hidden" name="DNDATA" value="xxx">
<script>
console.log("downloadstr");
</script>
</form>
<form id="uploadform" action="/index.shtml" enctype="multipart/form-data" method="post">
<p>Please specify a ppt file to upload :
<br>
<input type="file" name="datafilemnu" size="40" onchange="checkFile()">
<input type="button" value="UPLOAD" name="dnip" onclick="submitboth()">
</p>
</form>
<div>
<p id="downstring"></p>
<p id="fsize"></p>
</div>
<script>
var downloadstr = "";
document.getElementById("DN").value = downloadstr;
function checkFile() {
var sFileName = "";
var sFileExtension = "";
var iFileSize = 0;
var iConvert = "";
var node = "";
var node_list = document.getElementsByName("datafilemnu");
for (var i = 0; i < node_list.length; i++) {
node = node_list[i];
if (node.getAttribute("type") == "file" && node.files.length > 0) {
console.log(node.files[0]);
sFileName = node.value;
sFileExtension = sFileName.split(".")[sFileName.split(".").length - 1];
iFileSize = node.files[0].size;
iConvert = node.files[0].size.toFixed(0);
}
if (sFileExtension == "ppf" && iFileSize > 0) {
document.getElementById("fsize").innerHTML =
"Size=" +
iConvert +
" bytes. Estimated time to download = " +
((iConvert * 10) / 115200 / 60).toFixed(1) +
" minutes ";
downloadstr =
'LOAD(NAND,"EXT/' +
node.files.item(0).name +
'?size=' +
iFileSize +
'&useack=1")';
document.getElementById("downstring").innerHTML = downloadstr;
document.getElementById("DN").value = downloadstr;
console.log(downloadstr);
}
}
}
function submitboth() {
document.getElementById("predataform").submit();
setTimeout(function () {
document.getElementById("uploadform").submit();
window.location.reload();
}, 1000);
}
</script>
</body>
</html>
Thanks everybody.
I have found the answer to the main problem of corruption.
The webserver itself was converting the '(' to %28 - hex value (and some of the other characters) for some reason when it was being received.
I will have to check the webserver code. Sorry to cause so much confusion!
However, I have learnt to watch out for miss-spelling in my javascript!!

JavaScript returning null on a function for a simple guessing game

I created a guessing game using JavaScript. Initially, I wrote it in codepen where it ran fine, and when I moved it over to sublime to test it in the browsers as a standalone, the code did not work. I am getting this error: "Uncaught TypeError: Cannot read property 'value' of null at guess" which is line 14 var guessValue = parseInt(guessIn.value); and links back to the HTML of line 20 which is Guess
I can't figure out where the null is coming from. What am I doing wrong or haven't defined properly that is causing the null? I removed the CSS to blank slate it and make sure that wasn't screwing anything up.
//Generate random number between 1 and 500
var randomNumber = Math.floor((Math.random() * 500) + 1);
//Create variables to store info for loops and displaying info back to user
var guessIn = document.getElementById('userGuess');
var guessOut = document.getElementById('guessesMade');
var counter = 0;
//function runs when the guess button is hit
function guess() {
//declare temp local var and store as an integer for conditional testing
var guessValue = parseInt(guessIn.value);
//if statement for finding the value and reporting to the user
//check if the counter is less than 10 and guessValue is not empty
if (counter < 10 && guessValue) {
counter++;
}
//the guess is correct
if (guessValue == randomNumber) {
guessOut.value = guessOut.value + '\n' + "Guess " + counter + " is " + guessIn.value + ':' + ' You have correctly guessed the number. You may escape.';
}
// the guess is greater
if (guessValue > randomNumber) {
guessOut.value = guessOut.value + '\n' +"Guess " + counter + " is " + guessIn.value + ':' + ' Your guess is incorrect. The number I am thinking of is lower.';
}
//the guess is lower
if (guessValue < randomNumber) {
guessOut.value = guessOut.value + '\n' + "Guess " + counter + " is " + guessIn.value + ':' + ' Your guess is incorrect. The number I am thinking of is higher.';
}
//when all 10 guesses are used
else if (counter == 10) {
guessOut.value = guessOut.value + '\n' + "You did not guess the number I was thinking, " + randomNumber + "." + " You have met your end. Goodbye.";
}
return false;
}
//Show the number to guess upon clicking the checkbox for Cheat
function cheat() {
if (document.getElementById('cheat').checked) { document.getElementById('cheatNumber').value = randomNumber;
document.getElementById('cheatShow').style.display = 'inline';
}
else { document.getElementById('cheatNumber').value = '';
document.getElementById('cheatShow').style.display = 'none';
}
}
//function to reset the game
function reset() {
//reset guess value
userGuess.value = "";
//reset text area
guessesMade.value = "";
//reset counter
counter = 0;
//set new random number for play
randomNumber = Math.floor((Math.random() * 500) + 1);
return false;
}
<html>
<head>
<title>Do You Wanna Play A Game?</title>
<script src="game.js"></script>
</head>
<body>
<h1>Do You Wanna Play A Game?</h1>
<h3>A Guessing Game</h3>
<fieldset>
<legend>The Game Starts Now</legend>
<p>Welcome. You have stumbled upon this page. As a consequence, you have been trapped. To get out, the objective is simple.</p>
<p>I am thinking of a number. This number is between 1 and 500. You get ten guesses.</p>
<p>Good luck.</p>
<div id="guessingarea">
<input type="text" id="userGuess" value="394" /><br />
<button onClick="guess();">Guess</button>
<button onClick="reset();">Reset</button>
<br />
<input id="cheat" type="checkbox" value="cheat" onClick="cheat();" />
<label for="cheat">Cheat</label>
<div id="cheatShow" style="display: none;">
<input id="cheatNumber" type="text"/>
</div>
</div>
</fieldset>
<p></p>
<fieldset>
<legend>Let's examine your guess, shall we?</legend>
<textarea id="guessesMade" rows="14" style="width: 100%;"></textarea>
</fieldset>
</body>
</html>
It looks like you are including the script before your html document.
document.getElementById('userGuess');
is called before the element 'userGuess' exists.
I can think of two solutions to this, either include the script at the end of the document, or access this element only when you need it, rather than declaring it at the beginning like so:
var guessValue = parseInt(document.getElementById('userGuess').value);
You have included the script, before the element is available. As soon as the parser, hits the JS file, it will stop the rendering of the page and try to parse javascript. When the script is encountered, the element is still not available.
You have 2 options to make this work.
Move the script tag to before the close of the body element. This will make sure the page has the available elements before manipulating them.
<fieldset>
<legend>Let's examine your guess, shall we?</legend>
<textarea id="guessesMade" rows="14" style="width: 100%;"></textarea>
</fieldset>
<script src="game.js"></script>
</body>
Query the elements every single time inside the guess method since it is only invoked on a click action, which happens only after page is rendered.
function guess() {
var guessIn = document.getElementById('userGuess');
var guessOut = document.getElementById('guessesMade');
//declare temp local var and store as an integer for conditional testing
var guessValue = parseInt(guessIn.value);
......
......
The reason it works on code pen is because, the scripts are executed are deferred to onLoad which makes sure the elements are available on the page.
If you move the variable declarations inside the function it will work. The issue is that the JavaScript code is executed before the document is ready so the guessIn and guessOut variables are initialised to null.
Alternatively you can wrap your JavaScript code in a function that will execute when the DOM is complete.
document.onreadystatechange = function () {
if (document.readyState === "complete") {
// your code goes in here
}
}
See MDN for more details.

Require Specific First Characters from Form Post

I'm just putting this out there to see if anyone can catch my drift and give a hand..
I work for a public library and am in the process of making a "Self Checkin" machine.
Here's some code from it - There's a form called "checkin" with an input called "barcode" - the result of "barcode" is posted to a php file which the sends the data to the Library System and receives a message which is then passed into a table "completed-checkins".
It's all working fine but - I need to put some conditions on what data is accepted from the form.. The conditions are the first two characters need to be t00 .
I've been searching the web and trying to borrow/adapt code from others to make this work, which is where i got this from;
<script type="text/javascript">
function checkCode() {
var form = document.getElementById('checkin');
var x = form.elements.barcode.value.substring(0, 2);
// var x = this.value.substring(0, 2);
if (x == 't00') document.getElementById('#barcode').style.display = 'none';
}
</script>
I'm no real coder but am wondering if anyone who is can see how I could get this to work? (it doesn't at the moment).
Thanks much for looking,
Jordan.
And here's the html with all the scripts;
<body OnLoad="$('#barcode').focus();" style="padding:40px;">
<center>
<p>
<img src="selfchecklogo.png" />
</p>
<div class="formbarwrapper">
<div class="formbar">
<form method="post" name="checkin" id="checkin" onsubmit="return checkCode()" />
<input name="barcode" id="barcode" placeholder="scan an item..." autocomplete="off" maxlength="9" />
</form>
</div>
</div>
<div class="result">
<table id="completed-checkins">
<tbody>
<tr>
<td id="cell"></td>
</tr>
</tbody>
</table>
</div>
</center>
</body>
<script type="text/javascript">
function checkCode() {
var form = document.getElementById('checkin');
var x = form.elements.barcode.value.substring(0, 2);
// var x = this.value.substring(0, 2);
if (x == 't00') document.getElementById('#barcode').style.display = 'none';
}
</script>
<script type="text/javascript">
$(document).ready(function() {
$('#checkin').submit(function() {
$.post("index.php", {
barcode: $('#barcode').val()
},
function(data) {
var content = '';
content += '<div class="result">';
content += '<tbody>';
content += '<tr>';
content += '<td>' + data + '</td>';
content += '</tr>';
content += '</tbody>';
content += '</div>';
$('#barcode').val('').focus();
$('#completed-checkins tbody').html(content);
});
return false;
});
});
</script>
</html>
Have you tried printing "x" to the console? I think your problem is that this line
var x = form.elements.barcode.value.substring(0, 2);
only selects the first two characters out of the string, and then you compare it to "t00", which is three characters long and thus will always evaluate to false.
Also, you might want to consider using the "===" operator instead of the "==" operator. In this case both would work, but using "===" is a good habit to get in to. "===" works the way you expect it to work, whereas "==" has some little gotchas in Javascript. For instance
0 == '0' //This evaluates to true
0 === '0' //This evaluates to false
Basically, "==" doesn't check for type, and "===" does.

Create a inputbox which writes to textarea(php)

Just for fun am I creating a chatroom for one of my school classes.
What I'm after is a JavaScript, with a inputbox which pops up, once a button (add url) is pushed, where the user can paste a url which then gets written in the textarea.
I want this feature just so "http://" gets placed in front of the added url.
Been trying with this script (which looks correct to me... but it doesn't work)
<input type="button" id="s_5" onclick="addUrl()">
<script>
function addUrl()
{
var x;
var nettside=prompt("Type in URL:","www.example.com");
if (nettside!=null)
{
x="http://" + nettside + ";
document.getElementById("area").innerHTML=x;
}
}
</script>
yeah, the textarea it's supposed to write to:
<textarea name="txt" id="area" class="typo_vind" placeholder="......" autofocus title="Type your message here, have a great day!"></textarea>
EDIT
HTML:
<input type="button" id="s_5" onclick="javascript:formatText(addUrl())">
JS:
<script>
function addUrl()
{
var x;
var nettside=prompt("Skriv inn lenkeadressen her:","www.testtest.com");
if (nettside!="")
{
x="" + "BESKRIVELSE AV LENKEN" + "";
document.getElementById("area").value=x;
}
}
</script>
Two problems remains.
I don't want that script to clean out the textarea
I don't want the <undefined></undefined> to get added to the end
This is the result with the script as it is now:
<a href=http://www.eksempel.com>__BESKRIVELSE_AV_LENKEN__</a><undefined></undefined>
EDIT 2
Solved the problem where the script cleaned out the texarea with this:
<script>
function addUrl()
{
var x;
var nettside=prompt("Skriv inn lenkeadressen her (uten http://):","www.eksempel.com");
{
x="<a target =_blank href=http://" + nettside + ">" + "__BESKRIVELSE_AV_LENKEN__" + "</a>";
var Field = document.getElementById('area');
var val = Field.value;
var selected_txt = val.substring(Field.selectionStart, Field.selectionEnd);
var before_txt = val.substring(0, Field.selectionStart);
var after_txt = val.substring(Field.selectionEnd, val.length);
Field.value = before_txt + x + after_txt;
}
}
</script>
So now all that's missing is removal of the <undefined></undefined>-tags.
HTML: <input type="button" id="s_5" onclick="javascript:addUrl()">
SOLVED!
You should check the console of your browser - it always notifies about what error has occurred.
You have a typo in this line:
x="http://" + nettside + ";
The ending + " should be deleted.
Also, here:
document.getElementById("area").innerHTML=x;
you should use value instead (normally you do this with for elements):
document.getElementById("area").value=x;
This might not cause problems in the browser you are using, but might lead to strange behaviour under certain circumstances :).

Jquery adding items to a list without reloading page

I'm pretty stuck on how this should be achieved, mostly down to my lack of javascript knowledge. This is the code I'm looking at:
http://jsfiddle.net/spadez/VrGau/
What I'm trying to do is have it so a user can type add a "responsibility" in the responsibility field, then click add and have it appear in a list above it. The user can do this for up to 10 responsibilities.
The result would look something like this:
**Responsibility List:**
- Added responsibility 1
- Added responsibilty 2
*responsibility field - add button*
Can anyone explain how this should be done, it seems like it would have to involve ajax. I would really appreciate some more information or even an example.
Thank you.
EDIT: Here is a little bit more clarification. I want this data to be sent to the server as a list of items. I have seen examples of this being implemented, and here is a screenshot:
The user types in something in the text box, then clicks "add" and then it appears in a list above it. This information is what is submitted to the server.
Maybe this one can help also, this limits only 10 list
var eachline='';
$("#send").click(function(){
var lines = $('#Responsibilities').val().split('\n');
var lines2 = $('#Overview').val().split('\n');
if(lines2.length>10)return false;
for(var i = 0;i < lines.length;i++){
if(lines[i]!='' && i+lines2.length<11){
eachline += '- Added ' + lines[i] + '\n';
}
}
$('#Overview').text(eachline);
$('#Responsibilities').val('');
});
Try it here
http://jsfiddle.net/markipe/ZTuDJ/14/
Something like that maybe?
http://jsfiddle.net/VrGau/10/
var $responsibilityInput = $('#responsibilityInput'),
$responsibilityList = $('#responsibilityList'),
$inputButton = $('#send'),
rCounter = 0;
var addResponsibility = function () {
if(rCounter < 10){
var newVal = $responsibilityList.val()+$responsibilityInput.val();
$responsibilityList.val(newVal+'\n');
$responsibilityInput.val('');
}
}
$inputButton.click(addResponsibility);
Add id for textarea fields
<textarea rows="4" cols="50" placeholder="Responsibilities" id="resplist"></textarea>Add responsibility<br />
<textarea rows="4" cols="50" placeholder="How to apply" id="inputresp"></textarea>
You need Jquery. Use this js code
var i=0;
$("#send").click(addresp);
function addresp()
{
if (i<10)
{
$("#resplist").val($("#resplist").val()+$("#inputresp").val()+'\n');
$("#inputresp").val("");
i++;
}
}
http://jsfiddle.net/br0nsk1y/bDE9W/
It depends on if you want to post data to the server or not. If only in the client side you can do like this.
$("#send").on("click", function(event){
if($("#list li").size() < 10){
$("#list").append("<li>" + $("#responsibilities").val() + "</li>");
}
});
http://jsfiddle.net/VrGau/7/

Categories