refreshing div tag without refreshing a - javascript

I want to reload the div tag in click event.I want to generate random password in click event.now whole page get refreshed.This should take some time.so I want to refresh div tag every 3 second or in click event.Here I attached my code.
<body>
hello
<div class="refresh">
<?php
function randomPassword() {
$alphabet = "abcdefghijklmnopqrstuwxyzABCDEFGHIJKLMNOPQRSTUWXYZ0123456789";
$pass = array(); //remember to declare $pass as an array
$alphaLength = strlen($alphabet) - 1; //put the length -1 in cache
for ($i = 0; $i < 8; $i++) {
$n = rand(0, $alphaLength);
$pass[] = $alphabet[$n];
}
return implode($pass); //turn the array into a string
}
echo $pwd=randomPassword();
?>
</div>
<button class="click">click me</button>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script>
$(document).ready(function(){
$(".click").click(function(){
location.reload();
});
});
</script>
</body>

On click of a button, you are reloading the page using location.reload(); For only refreshing a div you need to modify your code.
<body>
hello
<div class="refresh">
</div>
<button class="click">click me</button>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script>
$(document).ready(function(){
$(".click").click(function(){
var str = randomPassword();
$(".refresh").html(str);
});
function randomPassword() {
$alphabet = "abcdefghijklmnopqrstuwxyzABCDEFGHIJKLMNOPQRSTUWXYZ0123456789";
$pass = array(); //remember to declare $pass as an array
$alphaLength = strlen($alphabet) - 1; //put the length -1 in cache
for ($i = 0; $i < 8; $i++) {
$n = rand(0, $alphaLength);
$pass[] = $alphabet[$n];
}
return implode($pass); //turn the array into a string
}
});
</script>
</body>

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<title> New Document </title>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script>
setInterval(RandPwd,30000);
function RandPwd()
{
var pwd = "";
var possible = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";
for( var i=0; i < 5; i++ )
pwd += possible.charAt(Math.floor(Math.random() * possible.length));
$(".refresh").html(pwd);
return false;
}
</script>
</head>
<body>
hello
<div class="refresh">
</div>
<button class="click" onclick="return RandPwd();">click me</button>
</body>
</html>

This is for refreshing the div tag without reloading the page.
<script>
var auto_refresh = setInterval(function () {
$('.refresh').fadeOut('slow', function() {
$(this).load('/echo/json/', function() {
$(this).fadeIn('slow');
});
});
}, 3000);
</script>

Related

How to add the returned value from a JavaScript function into an HTML element [duplicate]

I am looking for a way to call a javascript number in the body of an html page. This does not have to be long and extravagant just simply work, I just want something like:
<html>
<head>
<script type="text/javscript">
var number = 123;
</script>
</head>
<body>
<h1>"the value for number is: " + number</h1>
</body>
</html>
Try This...
<html>
<head>
<script>
function myFunction() {
var number = "123";
document.getElementById("myText").innerHTML = number;
}
</script>
</head>
<body onload="myFunction()">
<h1>"The value for number is: " <span id="myText"></span></h1>
</body>
</html>
Use document.write().
<html>
<head>
<script type="text/javascript">
var number = 123;
</script>
</head>
<body>
<h1>
the value for number is:
<script type="text/javascript">
document.write(number)
</script>
</h1>
</body>
</html>
<html>
<head>
<script type="text/javascript">
var number = 123;
var string = "abcd";
function docWrite(variable) {
document.write(variable);
}
</script>
</head>
<body>
<h1>the value for number is: <script>docWrite(number)</script></h1>
<h2>the text is: <script>docWrite(string)</script> </h2>
</body>
</html>
You can shorten document.write but
can't avoid <script> tag
<script type="text/javascript">
function get_param(param) {
var search = window.location.search.substring(1);
var compareKeyValuePair = function(pair) {
var key_value = pair.split('=');
var decodedKey = decodeURIComponent(key_value[0]);
var decodedValue = decodeURIComponent(key_value[1]);
if(decodedKey == param) return decodedValue;
return null;
};
var comparisonResult = null;
if(search.indexOf('&') > -1) {
var params = search.split('&');
for(var i = 0; i < params.length; i++) {
comparisonResult = compareKeyValuePair(params[i]);
if(comparisonResult !== null) {
break;
}
}
} else {
comparisonResult = compareKeyValuePair(search);
}
return comparisonResult;
}
var parcelNumber = get_param('parcelNumber'); //abc
var registryId = get_param('registryId'); //abc
var registrySectionId = get_param('registrySectionId'); //abc
var apartmentNumber = get_param('apartmentNumber'); //abc
</script>
then in the page i call the values like so:
<td class="tinfodd"> <script type="text/javascript">
document.write(registrySectionId)
</script></td>
Here is another way it can be done .
function showData(m)
{
let x ="<div> added from js ";
let y = m.toString();
let z = "</div>";
let htmlData = x+y+z ;
content.insertAdjacentHTML("beforeend",htmlData);
}
You can do the same on document ready event like below
<script>
$(document).ready(function(){
var number = 112;
$("yourClass/Element/id...").html(number);
// $("yourClass/Element/id...").text(number);
});
</script>
or you can simply do it using document.write(number);.
<?php
$x1='<span id="x1"></span><script>document.getElementById("x1").innerHTML = x1;</script>';
$x2='<span id="x2"></span><script>document.getElementById("x2").innerHTML = x2;</script>';
$x3='<span id="x3"</span><script>document.getElementById("x3").innerHTML = x3;</script>';
?>
<html><body>
<script> var
x1="123",
x2="ABC",
x3=666;
</script>
<?php echo $x1 ?><br>
<?php echo $x2 ?><be>
<?php echo $x3 ?><be>
</body></html>
Index.html:
<html>
<body>
Javascript Version: <b id="version"></b>
<script src="app.js"></script>
</body>
</html>
app.js:
var ver="1.1";
document.getElementById("version").innerHTML = ver;
You cannot add JavaScript variable to HTML code.
For this you need to do in following way.
<html>
<head>
<script type="text/javscript">
var number = 123;
document.addEventListener('DOMContentLoaded', function() {
document.getElementByTagName("h1").innerHTML("the value for number is: " + number);
});
</script>
</head>
<body>
<h1></h1>
</body>
</html>

Why does content of h1 tag doesnot change after clicking reset button?

var one = document.getElementById("one");
var two = document.getElementById("two");
var reset = document.getElementById("reset");
var i = 0;
var j = 0;
one.addEventListener("click", function() {
i = i + 1;
document.querySelector("#d1").textContent = i;
});
two.addEventListener("click", function() {
j = j + 1;
document.querySelector("#d2").textContent = j;
});
reset.addEventListener("click", function() {
document.getElementsByTagName("h1").innerHTML = "<h1>0 to 0</h1>";
});
// it doent work when i add textcontent in place of inner html
> why does content of h1 doesnot change when i click reset button.
<!DOCTYPE html>
<html>
<head>
<title>Score Keeper</title>
</head>
<body>
<h1><span id="d1">0</span> to <span id="d2">0</span></h1><br>
<p>Playing To : 5</p><br>
<input type="number">
<button id="one">Player One</button>
<button id="two">Player Two</button>
<button id="reset">Reset</button>
</body>
<script type="text/javascript" src="score.js"></script>
</html>
why does content of h1 doesnot change when i click reset button.
Problem :
document.getElementsByTagName returns an array so you will need index you could use
document.getElementsByTagName("h1")[0].innerHTML = "<h1>0 to 0</h1>";
But a better version is this :
var one = document.getElementById("one"),
two = document.getElementById("two"),
reset = document.getElementById("reset"),
i = 0,
j = 0;
one.addEventListener("click", function() {
i ++;
document.querySelector("#d1").textContent = i;
});
two.addEventListener("click", function() {
j ++;
document.querySelector("#d2").textContent = j;
});
reset.addEventListener("click", function() {
i = 0 , j = 0
document.getElementById("resetId").innerHTML = "<span id="d1">0</span> to <span id="d2">0</span>"; // Thanks to #Micheale
});
<!DOCTYPE html>
<html>
<head>
<title>Score Keeper</title>
</head>
<body>
<h1 id='resetId'><span id="d1">0</span> to <span id="d2">0</span></h1><br>
<p>Playing To : 5</p><br>
<input type="number">
<button id="one">Player One</button>
<button id="two">Player Two</button>
<button id="reset">Reset</button>
<script type="text/javascript" src="score.js"></script>
</body>
</html>
You are using getElementsByTagName which doesn't return a single element like getElementById. It returns an HTMLCollection/NodeList (depending on which browser), but you can just treat it like a standard array.
You should select the first element by using getElementsByTagName[0] instead.
You can either use innerHTML or textContent, but they do different things.
innerHTML would replace the contents of the h1 tag with whatever you assign. So, document.getElementsByTagName("h1").innerHTML = "<h1>0 to 0</h1>"; would output two h1 elements, which you don't want.
So in either case, set innerHTML or textContent to simply 0 to 0
var one = document.getElementById("one");
var two = document.getElementById("two");
var reset = document.getElementById("reset");
var i = 0;
var j = 0;
one.addEventListener("click", function() {
i = i + 1;
document.querySelector("#d1").textContent = i;
});
two.addEventListener("click", function() {
j = j + 1;
document.querySelector("#d2").textContent = j;
});
reset.addEventListener("click", function() {
document.getElementsByTagName("h1")[0].innerHTML = "0 to 0";
});
// it doent work when i add textcontent in place of inner html
<!DOCTYPE html>
<html>
<head>
<title>Score Keeper</title>
</head>
<body>
<h1><span id="d1">0</span> to <span id="d2">0</span></h1><br>
<p>Playing To : 5</p><br>
<input type="number">
<button id="one">Player One</button>
<button id="two">Player Two</button>
<button id="reset">Reset</button>
</body>
</html>
document.getElementsByTagName("h1") returns an array so you have to select the h1 you want.
Your code modified to take first h1 (assuming it is always the good one).
var one = document.getElementById("one");
var two = document.getElementById("two");
var reset = document.getElementById("reset");
var i = 0;
var j = 0;
one.addEventListener("click", function() {
i = i + 1;
document.querySelector("#d1").textContent = i;
});
two.addEventListener("click", function() {
j = j + 1;
document.querySelector("#d2").textContent = j;
});
reset.addEventListener("click", function() {
document.getElementsByTagName("h1")[0].innerHTML = "<h1>0 to 0</h1>";
});
// it doent work when i add textcontent in place of inner html
<!DOCTYPE html>
<html>
<head>
<title>Score Keeper</title>
</head>
<body>
<h1><span id="d1">0</span> to <span id="d2">0</span></h1><br>
<p>Playing To : 5</p><br>
<input type="number">
<button id="one">Player One</button>
<button id="two">Player Two</button>
<button id="reset">Reset</button>
</body>
<script type="text/javascript" src="score.js"></script>
</html>
Three problems here:
1- getElementsByTagName returns an array, not an element. You can retrieve the first element of the array with "[0]" as I've done in the snippet.
(I'd recommend giving that header an id.)
2- Problems with the innerHTML for h1. When replacing the h1 innerHTML, there's no need to repeat the h1 tags (you end up with nested h1s). But another problem is that you shouldn't forget the d1 and d2 spans, otherwise the code breaks.
3- Also, don't forget to reset i and j
var one = document.getElementById("one");
var two = document.getElementById("two");
var reset = document.getElementById("reset");
var i = 0;
var j = 0;
one.addEventListener("click", function() {
i = i + 1;
document.querySelector("#d1").textContent = i;
});
two.addEventListener("click", function() {
j = j + 1;
document.querySelector("#d2").textContent = j;
});
reset.addEventListener("click", function() {
document.getElementsByTagName("h1")[0].innerHTML = '<span id="d1">0</span> to <span id="d2">0</span>';
i = j = 0;
});
// it doent work when i add textcontent in place of inner html
<!DOCTYPE html>
<html>
<head>
<title>Score Keeper</title>
</head>
<body>
<h1><span id="d1">0</span> to <span id="d2">0</span></h1><br>
<p>Playing To : 5</p><br>
<input type="number">
<button id="one">Player One</button>
<button id="two">Player Two</button>
<button id="reset">Reset</button>
</body>
<script type="text/javascript" src="score.js"></script>
</html>
EDIT: I see some other people have got here first, but I'll leave my answer up for now because the other answers don't maintain the spans with id d1 and d2, which makes the code fail after hitting reset

How to pass Image from database in to javascript?

I am new to javascript and I'm trying to pass image from database into javascript, but I can not.
The problem code is :
'<img src="<?php echo base_url().'./images/burger/'.$val->image ?>">';
and this is my code
<!DOCTYPE html>
<html>
<head>
<title></title>
</head>
<body>
<div id="box">
<img id="image" />
</div>
<?php
$query = $this->db->get('product');
foreach($query->result() as $val):
?>
<script>
var images =
'<img src="<?php echo base_url().'./images/burger/'.$val->image ?>">';
function randImg() {
var size = images.length
var x = Math.floor(size * Math.random())
document.getElementById('image').src = images[x];
}
randImg();
</script>
<?php endforeach; ?>
</body>
</html>
<!DOCTYPE html>
<html>
<head>
<title>Javascript random image</title>
<?php
/* Query the db */
$query = $this->db->get('product');
/* use php to generate the javascript array of images from db query */
echo "
<script type='text/javascript'>
var images=[];
var baseurl='".base_url()."';
var path='./images/burger/';";
foreach( $query->result() as $val ){
/* Add image to javascript array */
echo "images.push('{$val->image}');\n";
}
echo "
</script>";
?>
<script type='text/javascript'>
function rnd_index(a,b) {
return Math.round( a + ( Math.random() * ( b - a ) ) );
}
function randImg() {
var x = rnd_index( 0, images.length-1 );
document.getElementById('image').src = baseurl + path + images[ x ];
}
function orig__randImg() {
var size = images.length;/* This might be too large sometimes for the array */
var x = Math.floor( size * Math.random() );
document.getElementById('image').src = path + images[ x ];
}
/* Load a random image when the page has loaded */
window.onload=randImg;
</script>
</head>
<body>
<div id="box">
<img id="image" />
</div>
</body>
</html>
You need to create an array in javascript and push the image path.
Before <?php foreach(...
<script>
var images = [];
function randImg(images) {
var size = images.length
var x = Math.floor(size * Math.random())
document.getElementById('image').src = images[x];
}
</script>
Inside the loop..
<script>
images.push("<?php echo base_url().'./images/burger/'.$val->image ?>");
</script>
After loop...
<script>
randImg(images);
</script>

events javascript

I need to display a message on mouse click. But I also need another message to be displayed on the next mouse click. The problem is that in my code both messages appear on the first mouse click.
<!DOCTYPE>
<html>
<head>
<script>
function myfunction()
{
var obj=document.getElementById("msg1");
obj.innerHTML="message1";
if(obj.innerHTML=="message1")
{
var obj1=document.getElementById("msg2");
obj1.innerHTML="message2";
}
}
</script>
</head>
<body>
<div id="msg">
<form name="myform">
<input type="button" value="click" onclick="myfunction()">
<p id="msg1"></p>
<p id="msg2"></p>
</form>
</div>
</body>
</html>
<script>
var flag=0;
function myfunction()
{
if (flag==0)
{
var obj=document.getElementById("msg1");
obj.innerHTML="message1";
flag=1;}
else
{
var obj1=document.getElementById("msg2");
obj1.innerHTML="message2";
}
}
</script>
if (obj.innerHTML == "message1") {
var obj1 = document.getElementById("msg2");
obj1.innerHTML = "message2";
}else{
obj.innerHTML = "message1";
}
Your if would always execute because you were trying to check if obj.innerHTML == "message1" immediately after setting it to that.
Do you see that you set the innerhtml of obj to "message1" and then immediately after you check if the innerHTML is "message1" that will always be true.
You need to change the if. So it says:
if(obj.innterHTML=="message1"){
obj.innerHTML="message2";
} else {
obj.innerHTML="message1";
}
Similar to others, but what the heck:
var obj1 = document.getElementById('msg1');
var obj2 = document.getElementById('msg2');
if (obj1.innerHTML == '') {
obj1.innerHTML = 'message1';
} else {
obj2.innerHTML = 'message2';
}
function myfunction() {
var i, ele;
for(i = 1; i <= 2; i++) {
ele = document.getElementById("msg"+i);
if (ele && ele.innerHTML.length == 0) {
ele.innerHTML = 'message' + i;
return;
}
}
}
Just add a click counter to check it was first click or more then first.
<!DOCTYPE>
<html>
<head>
<script>
var $clickCount = 0;
function myfunction() {
$clickCount++;
var obj = document.getElementById("msg1");
obj.innerHTML = "message1";
if (obj.innerHTML == "message1") {
var obj1 = document.getElementById("msg2");
if ($clickCount == 2) {
obj1.innerHTML = "message2";
}
}
}
</script>
</head>
<body>
<div id="msg">
<form name="myform">
<input type="button" value="click" onclick="myfunction()">
<p id="msg1"></p>
<p id="msg2"></p>
</form>
</div>
</body>
</html>

Prototype issue - How do I check for links on an input field and check for the length of that input field?

I sort of started coding for this. It's almost working.
My goals:
1) Check for the length or url's entered in a field (the total length) and reduce each link's length by 20 if the length is greater than 20
2) Determine the characters left in an input field
The javascript in profile.js (prototype):
function checkurl_total_length(text) {
var text = "";
var matches = [];
var total_length = 0;
var urlRegex = /(http|https):\/\/[A-Za-z0-9\.-]{3,}\.[A-Za-z]{3}/;
text.scan(urlRegex, function(match){ matches.push(match[0])});
for (var index = 0; index < matches.length; ++index) {
item = matches[index];
reduce_length = matches.length*20;
if(item.length>20) {
total_length = total_length + item.length - reduce_length;
}
else {
total_length = total_length + item.length;
}
}
return total_length;
}
function count_characters(field){
var limitNum=140;
var link_length = 0;
if(checkurl_total_length(field.value)!=0) {
link_length =link_length+ checkurl_total_length(field.value);
}
else {
link_length = 0;
}
limitNum = limitNum+link_length;
if( link_length !=0 ){
$("links").update("with links");
}
left = limitNum-field.value.length;
$("count").update(left);
}
THE HTML
<!DOCTYPE HTML>
<html lang="en"><head>
<meta http-equiv="content-type" content="text/html; charset=UTF-8">
<title>JUST A TEST FILE</title>
<script src="prototype.js" type="text/javascript"></script>
<script src="profile.js" type="text/javascript"></script>
</head><body>
<h1>
CHARACTERS COUNT
</h1>
<div class="container_24">
<h2 id="title2">
TESTING
</h2>
<div class="grid_24">
<div id="count"></div>
<br /s>
<div id="links"></div>
<form >
<textarea wrap="hard" onpaste="count_characters(this);" onkeyup="count_characters(this);" onkeydown="count_characters(this);" id="updates" onfocus="count_characters(this);" name="test"/> </textarea>
<input type="submit" value=" " name="commit" disabled=""/>
</form>
</div>
</div>
<!-- end .container_24 -->
</body></html>
Counting characters left is working but checking for url and the length of the url isn't. Any hints on why this isn't working?
not sure, but should this be
checkurl_total_length(field.value!=0) // ) != 0

Categories