HTML Window Refresh Top of Page - javascript

Everytime the page refreshes it goes to top of page, I would like it to stay where it is, I'm pretty sure it has something to do with function move() {window.location = window.location.href}. Heres the code.
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<meta http-equiv="refresh" content="83">
<META HTTP-EQUIV="Pragma" CONTENT="no-cache">
<META HTTP-EQUIV="Expires" CONTENT="-1">
<title>[DashboardDescrip]</title>
<style type="text/css">
body
{
background-image:
url('../Images/Black-BackGround.gif');
background-repeat: repeat
}
</style>
</head>
<script type="text/javascript">
var time = null
function move() { window.location = window.location.href }

Well you are not actually refreshing the page.. You are redirecting it to the same page.. To refresh use:
location.reload();
http://www.w3schools.com/jsref/met_loc_reload.asp
This might still not solve your problem.. and you'll have to look for some script.. Are you using asp.net?

Perhaps the following code would work for you? Source
<HTML>
<HEAD>
<TITLE>Test</TITLE>
<script>
function SaveScrollXY() {
document.Form1.ScrollX.value = document.body.scrollLeft;
document.Form1.ScrollY.value = document.body.scrollTop;
}
function ResetScrollPosition() {
var hidx, hidy;
hidx = document.Form1.ScrollX;
hidy = document.Form1.ScrollY;
if (typeof hidx != 'undefined' && typeof hidy != 'undefined') {
window.scrollTo(hidx.value, hidy.value);
}
}
</script>
</HEAD>
<BODY onload="ResetScrollPosition()">
<form name="Form1" id="Form1" method="post"
onsubmit="SaveScrollXY()" action="index.php">
<input name="ScrollX" id="ScrollX" type="hidden"
value="<?php echo $_REQUEST['ScrollX'] ?>" />
<input name="ScrollY" id="ScrollY" type="hidden"
value="<?php echo $_REQUEST['ScrollY'] ?>" />
<p>This is just a paragraph to make a very long page.</p>
…
<P>This is just a paragraph to make a very long page.</P>
<P>
<input name="TextBox1" type="text"
value="<?php $v = $_REQUEST['TextBox1']; echo $v ? $v + 1 : 1 ?>"
readonly="readonly" id="TextBox1" /></P>
<P>
<input type="submit" name="Button1" value="Post Form"
id="Button1" /></P>
</form>
</BODY>
</HTML>

Shawn313131 came up with this answer for me so credit to him not me!!!
<!DOCTYPE html>
<html>
<head>
<style type="text/css">
body {
background-image: url('../Images/Black-BackGround.gif');
background-repeat: repeat;
}
body td {
font-Family: Arial;
font-size: 12px;
}
#Nav a {
position:relative;
display:block;
text-decoration: none;
color:black;
}
</style>
<script type="text/javascript">
function refreshPage () {
var page_y = document.getElementsByTagName("body")[0].scrollTop;
window.location.href = window.location.href.split('?')[0] + '?page_y=' + page_y;
}
window.onload = function () {
setTimeout(refreshPage, 35000);
if (window.location.href.indexOf('page_y') != -1 ) {
var match = window.location.href.split('?')[1].split("&")[0].split("=");
document.getElementsByTagName("body")[0].scrollTop = match[1];
}
}
</script>
</head>
<body>

I believe you are looking for something like this:
var pos = $(window).scrollTop();
..// Some Code Later, or after page refresh & retrieving the value from a cookie
$(window).scrollTop(pos);

Related

Function runs immediately without setTimeout() in Javascript

I want to build a web with HTML, CSS, Javascript, PHP and MySQL. I want my web will have a feature that the customers want to download the file from the web, if they don't want to download faster, no need to go through the shorten link, they will enter the code and web will use PHP and MySQL to check if the code is in the database. If the code valid, they will press the Next button to go to download file.
This is all my code:
HTML + CSS + JS + PHP:
<!DOCTYPE html>
<html>
<head>
<title>HTML Document</title>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.5.2/css/bootstrap.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.16.0/umd/popper.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.5.2/js/bootstrap.min.js"></script>
<script>
function countWord() {
var x = document.getElementById("code").value;
if ((x.length)!=12) {
document.getElementById("ok").disabled = true;
} else if ((x.length)==12) {
document.getElementById("ok").disabled = false;
}
}
</script>
<style>
* {
padding:0;
margin:0;
box-sizing:border-box;
}
body {
background-color:#fff;
}
#code {
width:98%;
margin-left:1%;
}
#ok {
width:50%;
margin-left:25%;
margin-top:10px;
}
#nextbtn {
width:50%;
margin-left:25%;
margin-top:10px;
}
</style>
</head>
<body>
<form method="POST" name="code_form" id="code_form">
<input type="text" class="form-control" name="code" id="code" onkeyup="countWord();">
<input type="submit" name="ok" id="ok" class="btn btn-primary" disabled>
</form>
<button type="button" disabled class="btn btn-primary" id="nextbtn">Next</button>
<?php
$conn = mysqli_connect("","","","");
if (isset($_POST["ok"])) {
$code = $_POST["code"];
$sql = "SELECT * FROM code WHERE code='$code'";
$result = mysqli_query($conn,$sql);
if (mysqli_num_rows($result) == 1) {
echo "
<script>
var x = setTimeout(function(){
document.getElementById('nextbtn').disabled = false;
document.getElementById('nextbtn').onclick = function() {
window.open('https://www.youtube.com');
};
},0);
</script>
";
} else {
echo "<script>alert('Error');</script>";
}
}
?>
</body>
</html>
In the code below, I want to be able to run the function immediately without using the setTimeout() function:
echo "
<script>
var x = setTimeout(function(){
document.getElementById('nextbtn').disabled = false;
document.getElementById('nextbtn').onclick = function() {
window.open('https://www.youtube.com');
};
},0);
</script>
";
Please help me!
This function will be invoked immediately. IIFE
(function(){
document.getElementById('nextbtn').disabled = false;
document.getElementById('nextbtn').onclick = function() {
window.open('https://www.youtube.com');
})()
Is removing the setTimeout only not enough?
<script>
(function(){
document.getElementById('nextbtn').disabled = false;
document.getElementById('nextbtn').onclick = function() {
window.open('https://www.youtube.com');
})();
</script>
<script>
document.getElementById('nextbtn').disabled = false;
document.getElementById('nextbtn').onclick = function() {
window.open('https://www.youtube.com');
};
</script>
//---
<html>
<head>
<title>HTML Document</title>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.5.2/css/bootstrap.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.16.0/umd/popper.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.5.2/js/bootstrap.min.js"></script>
<script>
function countWord() {
var x = document.getElementById("code").value;
if ((x.length) != 12) {
document.getElementById("ok").disabled = true;
} else if ((x.length) == 12) {
document.getElementById("ok").disabled = false;
}
}
</script>
<style>
* {
padding:0;
margin:0;
box-sizing:border-box;
}
body {
background-color:#fff;
}
#code {
width:98%;
margin-left:1%;
}
#ok {
width:50%;
margin-left:25%;
margin-top:10px;
}
#nextbtn {
width:50%;
margin-left:25%;
margin-top:10px;
}
</style>
</head>
<body>
<form method="POST" name="code_form" id="code_form">
<input type="text" class="form-control" name="code" id="code" onkeyup="countWord();">
<input type="submit" name="ok" id="ok" class="btn btn-primary" disabled>
</form>
<button type="button" disabled class="btn btn-primary" id="nextbtn">Next</button>
<?php
//$conn = mysqli_connect("", "", "", "");
if (isset($_POST["ok"])) {
$code = $_POST["code"];
//$sql = "SELECT * FROM code WHERE code='$code'";
//$result = mysqli_query($conn, $sql);
//if (mysqli_num_rows($result) == 1) {
if (1 == 1) {
echo "<script>
document.getElementById('nextbtn').disabled = false;
document.getElementById('nextbtn').onclick = function() {
window.open('https://www.youtube.com');
};
</script>";
} else {
echo "<script>alert('Error');</script>";
}
}
?>
</body>

Add two text fields together that include commas and decimals with JavaScript only

In order to add a feature to a existing application I'm attempting to use JavaScript to add together input fields which need to stay as text field types and show the end result text field as a total of those fields. I can easily make it work adding the numbers together. However the numbers will be typed in with commas and decimals every time. When this happens the adding breaks and doesn't work. Anyone have any ideas of how I could possibly make this work?
HTML CODE
<form method="post">
<input type="text" id="the_input_id">
<input type="text" id="the_input_id1">
<input type="text" id="total">
JavaScript
$(function() {
$('#the_input_id').keyup(function() {
updateTotal();
});
$('#the_input_id1').keyup(function() {
updateTotal();
});
var updateTotal = function () {
var input1 = parseInt($('#the_input_id').val());
var input2 = parseInt($('#the_input_id1').val());
if (isNaN(input1) || isNaN(input2)) {
if(!input2){
$('#total').val($('#the_input_id').val());
}
if(!input1){
$('#total').val($('#the_input_id1').val());
}
} else {
$('#total').val(input1 + input2);
}
};
var output_total = $('#total');
var total = input1 + input2;
output_total.val(total);
});
How about something like this?
var num1 = "1,000,000.00"
var num2 = "1,000,000.25"
var re = /,/gi;
var num1a = num1.replace(re,''); // strip commas
var num2a = num2.replace(re, ''); // strip commas
var sum = Number(num1a) + Number(num2a); // convert to Number and add together
console.log(sum); // before formatting
var total = Number(sum).toLocaleString(); // formatted
console.log(total)
Read my comment above, then take a look here:
//<![CDATA[
/* js/external.js */
$(function(){
var num1 = $('#num1'), num2 = $('#num2'), total = $('#total'); // why get them again unless they're dynamic ?
function updateTotal(){
var s = num1.val().replace(/,/g, ''), s2 = num2.val().replace(/,/g, '');
if(s === '' && s2 === ''){
total.text('Awaiting Input').addClass('er');
}
else if(isNaN(s) && isNaN(s2)){
total.text('Numbers Required').addClass('er');
}
else if(s === ''){
total.text('Awaiting First Number').addClass('er');
}
else if(isNaN(s)){
total.text('First Input Requires Number').addClass('er');
}
else if(s2 === ''){
total.text('Awaiting Second Number').addClass('er')
}
else if(isNaN(s2)){
total.text('Second Input Requires Number').addClass('er');
}
else{
total.text(((+s)+(+s2)).toLocaleString(undefined, {minimumFractionDigits:2, maximumFractionDigits:2})).removeClass('er');
}
};
num1.keyup(updateTotal); num2.keyup(updateTotal);
}); // end jQuery load
//]]>
/* css/external.css */
*{
box-sizing:border-box; padding:0; margin:0;
}
html,body{
width:100%; height:100%;
}
body{
background:#ccc;
}
#content{
padding:7px;
}
input[type=text]{
width:100px; padding:0 3px;
}
.er{
color:#900;
}
#total{
display:inline-block;
}
<!DOCTYPE html>
<html xmlns='http://www.w3.org/1999/xhtml' xml:lang='en' lang='en'>
<head>
<meta charset='UTF-8' /><meta name='viewport' content='width=device-width, height=device-height, initial-scale:1' />
<title>Test Template</title>
<link type='text/css' rel='stylesheet' href='css/external.css' />
<script type='text/javascript' src='https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js'></script>
<script type='text/javascript' src='js/external.js'></script>
</head>
<body>
<div id='content'>
<input type='text' id='num1' /> &plus;
<input type='text' id='num2' /> &equals;
<div class='er' id='total'>Awaiting Input</div>
</div>
</body>
</html>
Note that you can use + in front of a String to cast it to a number... and that JavaScript has a Floating Point Number Math issue.
Here is a <form> example:
//<![CDATA[
/* js/external.js */
$(function(){
var form = $('#form'), num1 = $('#num1'), num2 = $('#num2'), total = $('#total'); // why get them again unless they're dynamic ?
function updateTotal(){
var s = num1.val().replace(/,/g, ''), s2 = num2.val().replace(/,/g, '');
if(s === '' && s2 === ''){
total.val('Awaiting Input').addClass('er');
}
else if(isNaN(s) && isNaN(s2)){
total.val('Numbers Required').addClass('er');
}
else if(s === ''){
total.val('Awaiting First Number').addClass('er');
}
else if(isNaN(s)){
total.val('First Input Requires Number').addClass('er');
}
else if(s2 === ''){
total.val('Awaiting Second Number').addClass('er')
}
else if(isNaN(s2)){
total.val('Second Input Requires Number').addClass('er');
}
else{
total.val(((+s)+(+s2)).toLocaleString(undefined, {minimumFractionDigits:2, maximumFractionDigits:2})).removeClass('er');
}
};
form.submit(function(e){
console.log(form.serialize());
// run a bunch of tests using if conditions and the like before AJAXing - $.post example shown
/*
$.post('sendToPage.php', form.serialize(), function(jsonResult){
// should get echo json_encode($objOrAssocArray); from PHP as jsonResult now
}, 'json');
*/
// prevents old school submission
e.preventDefault();
});
num1.keyup(updateTotal); num2.keyup(updateTotal);
}); // end jQuery load
//]]>
/* css/external.css */
*{
box-sizing:border-box; padding:0; margin:0;
}
html,body{
width:100%; height:100%;
}
body{
background:#ccc;
}
#content{
padding:7px;
}
input[type=text]{
width:100px; padding:3px 5px;
}
.symbol{
display:inline-block; width:18px; text-align:center;
}
.er{
color:#900;
}
#total{
width:calc(100% - 236px);
}
input[type=submit]{
width:100%; height:30px; background:#007; color:#fff; border:0; border-radius:5px; margin-top:4px; cursor:pointer;
}
<!DOCTYPE html>
<html xmlns='http://www.w3.org/1999/xhtml' xml:lang='en' lang='en'>
<head>
<meta charset='UTF-8' /><meta name='viewport' content='width=device-width, height=device-height, initial-scale:1' />
<title>Test Template</title>
<link type='text/css' rel='stylesheet' href='css/external.css' />
<script type='text/javascript' src='https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js'></script>
<script type='text/javascript' src='js/external.js'></script>
</head>
<body>
<div id='content'>
<form id='form'>
<input type='text' id='num1' name='num1' /><div class='symbol'>&plus;</div><input type='text' id='num2' name='num2' /><div class='symbol'>&equals;</div><input type='text' class='er' id='total' name='total' value='Awaiting Input' readonly='readonly' />
<input type='submit' id='sub' value='Submit Test' />
</form>
</div>
</body>
</html>
Maybe something like this by simply extracting only numbers from any string the user inputs:
$(function () {
var $firstInput = $('#first');
var $secondInput = $('#second');
var $totalInput = $('#total')
$firstInput.keyup(updateTotal);
$secondInput.keyup(updateTotal);
function extractNumbers(str, def) {
var onlyNumbers = '';
for (var i = 0; i < str.length; ++i) {
var currChar = str.charAt(i);
if (!isNaN(currChar)) {
onlyNumbers += currChar;
}
}
return parseInt(onlyNumbers) || def;
}
function updateTotal () {
var valInput1 = extractNumbers($firstInput.val(), 0)
var valInput2 = extractNumbers($secondInput.val(), 0)
var total = valInput1 + valInput2;
$totalInput.val(total);
}
});
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width">
<title>Test</title>
<script src="https://code.jquery.com/jquery-3.1.0.js"></script>
</head>
<body>
<input type="text" placeholder="first number..." id="first">
<input type="text" placeholder="second number..." id="second">
<input type="text" placeholder="total number..." id="total">
</body>
</html>

Affecting returned PHP query result to HTML form input field

Contents of main file
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" >
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Test JSON</title>
<style type="text/css">
body {
margin : 100px;
}
h1 {
text-align: center;
}
</style>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.2/jquery.min.js"></script>
<link rel="stylesheet" href="https://ajax.googleapis.com/ajax/libs/jqueryui/1.11.4/themes/smoothness/jquery-ui.css" />
<script src="https://ajax.googleapis.com/ajax/libs/jqueryui/1.11.4/jquery-ui.min.js"></script>
<script type="text/javascript" >
$(document).ready(function () {
$("#btn").click(getNewVal);
});
function getNewVal(){
var xhr = new XMLHttpRequest();
var queryString = "getVal.php?str=" + "Blah";
xhr.open("GET", queryString, true);
xhr.onreadystatechange = function () {
if (xhr.readyState == 4) {
//alert(document.getElementById("txtField").value);
var JSONObj = JSON.parse(xhr.responseText);
alert(JSONObj.item);
document.getElementById("txtField").value = JSONObj.item;
}
}
xhr.send(null);
}
</script>
</head>
<body>
<h1>Test JSON</h1>
<hr />
<form id="testForm" method="GET" action="">
<label>Custom Value: </label>
<input type="text" value="La valeur a changer" id="txtField">
<input type="submit" value="Bouton pour changer la valeur" id="btn">
</form>
</body>
Contents of ajax call file
<?php
if (mysqli_connect_errno())
{
echo "Problème avec la connection : " . mysqli_connect_error();
}
else{
if(isset($_GET['str'])) {
$val = $_GET['str'];
$post_data = array('item' => $_GET['str']);
echo json_encode($post_data);
}
else{
echo "error";
}
}
?>
I want to return the result of the query and affect it to an html text input field in another php file. After making the changes for JSON everything works, except the document.getElementById("txtField").value = JSONObj.item; in the onreadystatechange. What am i missing?
Thanks in advance!

JavaScript - Toggle CSS colors with plain JavaScript?

I'm trying to change the colors of a form text field back and forth, using plain javascript. Can somebody help?
I can change the color once but not back
Here is what I have done
<!DOCTYPE html>
<html>
<head>
<title>JavaScript</title>
</head>
<body>
<script type="text/javascript">
function color() {
var x = document.getElementById("currID");
if(x.style.color="red") {
x.style.color="blue";
}
}
}
</script>
<input type="button" value="Click Me" id="testButton" onclick="color()" />
<form method="get" action="getresult.php">
<p>Current ID: <input id="currID" class="a" type="text" name="currID" /></p>
<p><input type="submit" value="Request new ID"/></p>
</form>
</body>
</html>
CSS
<style type="text/css">
.main {
color:black;
}
.a {
color:red;
}
</style>
Try this:
<!DOCTYPE html>
<html>
<head>
<title>JavaScript</title>
</head>
<body>
<script type="text/javascript">
function color() {
var x = document.getElementById("currID");
if(x.className == "main"){
x.className = "a";
} else {
x.className = "main";
}
}
</script>
<input type="button" value="Click Me" id="testButton" onclick="color()" />
<form method="get" action="getresult.php">
<p>Current ID: <input id="currID" class="a" type="text" name="currID" /></p>
<p><input type="submit" value="Request new ID"/></p>
</form>
</body>
</html>
CSS:
<style type="text/css">
.main {
color:black;
}
.a {
color:red;
}
</style>
Demo: https://jsfiddle.net/a5rxoh03/
Specifically to your issue, and why it didn't work, is because when adding a 2nd IF, you just reveresed the result.
Check out this fiddle, it will change the input field of the "currID" as requested from blue to red and vice verca.
https://jsfiddle.net/0rnnqe3y/
This is the JS :
function color() {
var x = document.getElementById("currID");
console.log(x.style.color == "red");
if(x.style.color=="red") {
x.style.color="blue";
return;
};
if(x.style.color=="blue"){
x.style.color="red";
return;
}
}

Text Alignment Issue in IE9

I have a input field and it has some text in it. On click of a button I want to change the text-align to center, left and right.
It works in every browser but not in IE9.
<!DOCTYPE html>
<html>
<head>
<title> Test for Text Align</title>
<meta charset = "UTF-8" />
<style type="text/css">
#testBox{
text-align: left;
}
</style>
</head>
<div>
<input type="text" id ="testBox" name="testBox" value="testBox" maxlength="32" />
</div>
<div>
<input type="button" onClick="testFunction('centeralign')" name="centeralign" id="centeralign" value="centeralign"/>
<input type="button" onClick="testFunction('leftalign')" name="leftalign" id="leftalign" value="leftalign"/>
<input type="button" onClick="testFunction('rightalign')" name="rightalign" id="rightalign" value="rightalign"/>
</div>
<script type="text/javascript">
function testFunction(el){
var testTextBox = document.getElementById("testBox");
if(el == "centeralign"){
testTextBox.style.textAlign = "center";
}else if (el == "leftalign") {
testTextBox.style.textAlign = "left";
}else if (el == "rightalign") {
testTextBox.style.textAlign = "right";
}
}
</script>
</html>
This is an odd bug in IE (at least some versions of it). It seems that the input box rendering is not updated when its style is changed via an event handler attribute. It seems to help to add the following after the definition of testTextBox:
testTextBox.value += '';
This does not modify the value, since it appends an empty string, but it seems to be sufficient for waking up IE so that it renders the input box with the changed style.
If u have still not got it solved u can get the below code works in ie9 tested js code as ur wish ..
<!DOCTYPE html>
<html>
<head>
<title> Test for Text Align</title>
<meta charset = "UTF-8" />
<style type="text/css">
#testBox{
text-align: left;
}
</style>
</head>
<body>
<div>
<input type="text" id ="testBox" name="testBox" value="testBox" maxlength="32" />
</div>
<div>
<input type="button" onClick="testFunction('centeralign')" name="centeralign" id="centeralign" value="centeralign"/>
<input type="button" onClick="testFunction('leftalign')" name="leftalign" id="leftalign" value="leftalign"/>
<input type="button" onClick="testFunction('rightalign')" name="rightalign" id="rightalign" value="rightalign"/>
</div>
<script type="text/javascript">
function testFunction(el){
var testTextBox = document.getElementById("testBox");
if(el == "centeralign"){
testTextBox.style.textAlign = "center";
}else if (el == "leftalign") {
testTextBox.style.textAlign = "left";
}else if (el == "rightalign") {
testTextBox.style.textAlign = "right";
}
}
</script>
</body>
</html>

Categories