set value of html input or textarea - javascript

It is perfectly working. I want to get the current URL and set it inside textarea or input tag. Actually the value is set into a p tag.
function urlf() {
document.getElementById("root").innerHTML = "The full URL of this page is: < br > " + window.location.href;
}
<h2>JavaScript</h2>
<h3>The window.location.href</h3>
<button id="my btn" type="button" onclick="urlf()">
get
</button>
<p id="root"> </p>
How can I do this?

Create an input tag and set its value
function urlf() {
document.getElementById("root").value = "The full URL of this page is:" + window.location.href;
}
<h2>JavaScript</h2>
<h3>The window.location.href</h3>
<button id="my btn" type="button" onclick="urlf()">
get
</button>
<input type="text" style="width:100%;" id="root">

you set the innerHTML of the element with the id root. According to your code this is:
<p id="root"> </p>
so if you want to load the content into an input field you need to change the following:
document.getElementById("root").value = "The full URL of this page is:" + window.location.href;
<input id="root" type="text" />
greetings

<input id="root" type="text">
function urlf() {
document.getElementById("root").value = window.location.href;
}

You just want the current URL in a input? Like below:
function urlf() {
document.getElementById("root").value = "The full URL of this page is:" + window.location.href; }
<div>
<h2>JavaScript</h2>
<h3>The window.location.href</h3>
<button id="my btn" type="button" onclick="urlf()">
get
</button>
<input style="width:500px;" type="text" id="root"/>
</div>

Related

how to set value in javascript div tag

how to set value using javascript i want set value onclick function + 20 current points please help
my code not working please help me this
ony use javascript not jquery
<div class="score">
<input id="txtscore" value= "0"class="width150" type="text" />
</div>
<div class="box1">
<a href='' onclick='check()'>check</a>
</div>
function check(){
var getvalue = document.getElementById('txtscore').value;
getvalue = getvalue + 20;
}
You need to get your element and set the new value
Convert the entered value to number to get the right result.
You need to validate the entered value before any calculation.
To avoid a refresh in your page, use this: href='#' or bind a click event to prevent the default behavior.
function check() {
var textscore = document.getElementById('txtscore');
textscore.value = Number(textscore.value) + 20;
}
<div class="score">
<input id="txtscore" value="0" class="width150" type="text" /> </div>
<div class="box1">
<a href='#' onclick='check()'>check</a>
</div>
You need to transform the value to a number otherwise you will concatenate a string, you can also use button instead of a link, if you use a link by default the page will refresh...
function check(){
var getvalue = document.getElementById('txtscore').value;
getvalue = parseInt(getvalue) + 20;
document.getElementById('txtscore').value=getvalue;
}
<div class="score">
<input id="txtscore" value= "0"class="width150" type="number" /> </div>
<div class="box1">
<button onclick='check()'>check</button>
</div>

DRY-ing JS code and hiding input on address bar?

I've got a script which would pass input of the user onto the completed.html page but here are two problems:
All of the user inputs are displayed on the address bar, i want to hide it but i dont want to use the POST method which will ruin the purpose of my JS script. Is there any way i can hide those inputs without changing the method even if i have to change the JS script?
My JS code is really repetitious, it's repeated 4 times and i want to know a better way of writing it without copy and pasting all over?
index.html
<div id="container">
<header>
<h1>Registration Form</h1>
<hr>
</header>
<article>
<form action="completed.html" method="GET">
<label for="FirstName"><b>First Name:</b></label>
<input name="FirstName" type="text" placeholder="John" required>
<label for="LastName"><b>Last Name:</b></label>
<input name="LastName" type="text" placeholder="Doe" required>
<label for="email"><b>Email:</b></label>
<input name="email" type="text" placeholder="example#mail.com" required>
<label for="password"><b>Password:</b></label>
<input name="password" type="password" placeholder="Password here." required>
<p></p>
<input type="submit" value="Submit">
</form>
</article>
<footer>
Copyright # 2017 Name
</footer>
</div>
completed.html
<div id="container">
<header>
<h1>Registration Completed!</h1>
<hr>
</header>
<article>
<div id="info" style="float: left;">
<p>Thank you for registering on our site! An verification email has been seen to your email address! To make sure we got everything right, we would like you to review the infomation you've put in.</p>
<div id="fn">
Your First Name is:
</div>
<div id="ln">
Your Last Name is:
</div>
<div id="em">
Your email is:
</div>
<div id="pw">
Your password is:
</div>
</div>
</article>
<footer>
Copyright # 2017 Name
</footer>
</div>
<script>
function processForm() {
var ary = location.search.substring(1).split("&");
var fnpart = ary[0].split("=");
frn = unescape(fnpart[1]);
document.getElementById("fn").innerHTML = "<b>Your First Name is:</b>" + "<br>" + frn;
var lnpart = ary[1].split("=");
lsn = unescape(lnpart[1]);
document.getElementById("ln").innerHTML = "<b>Your Last Name is:</b>" + "<br>" + lsn;
var empart = ary[2].split("=");
ema = unescape(empart[1]);
document.getElementById("em").innerHTML = "<b>Your Email is:</b>" + "<br>" + ema;
var pwpart = ary[3].split("=");
psw = unescape(pwpart[1]);
document.getElementById("pw").innerHTML = "<b>Your First Name is:</b>" + "<br>" + psw;
}
processForm();
</script>
You can try with a pattern like below, using the loop index to match the position in the short names/ long names :
But the password shouldn't be visible in the location like it is now !
var names = [['fn', 'First Name'],
['ln', 'Last Name'],
['em', 'Email'],
['pw', 'Password']
]
for (ind in ary){
var part = unescape(ary[ind].split("=")[1]);
document.getElementById(names[ind][0]).innerHTML = "<b>Your "+ names[ind][1] + " is:</b> <br>" + part;
}
To accomplish goal no. 1, you do not need to use attribute action on form. Also you can replace submit button with <input type="button"> and handle click event and call processForm() function.
To be able to call that function, you need to move processForm() declaration into index.html. so you only need one file. You do not need to read any data from query string. Just read input value from DOM element

How to click on an image to show images with a function

Trying to click the magic8, but the happy, sad and surprised pictures won't show below the line. What did I do wrong? I have saved the images in random.js in the same folder.
<html>
<head>
<script type=text/javascript src="random.js">
</script>
<script>
function magicEight() {
var imgName;
imgName = RandomOneOf(["happy.gif", "sad.gif", "surprised.gif"]);
document.getElementById('outputDiv').value = imgName;
}
</script>
</head>
<body>
<div style="text-align:center">
<h1> Magic 8-ball (Mattel, Inc.) </h1>
<p> Enter a question below, then click on the Magic 8-Ball to recieve its wisdom. </p>
<input type="text" id="questionBox" size=90 value="">
<p>
<input type="image" src="http://balance3e.com/Images/8ball.gif" id="button" onclick="magicEight();">
</p>
<hr>
<div id="outputDiv"></div>
</div>
</body>
</html>
If you want to show and image you need to add the value of the randomoneof on a img tag not on a div tag. Change that and I think it will work
Demo: https://codepen.io/hienhuynhtm/pen/dpLgNr
<script>
var IMAGE_LIST = [
"http://balance3e.com/Images/happy.gif",
"http://balance3e.com/Images/sad.gif",
"http://balance3e.com/Images/surprised.gif"
];
function magicEight() {
var imgName = IMAGE_LIST[Math.floor(Math.random() * IMAGE_LIST.length)];
document.getElementById("randomImg").src = imgName;
}
</script>
<div style="text-align:center">
<h1> Magic 8-ball (Mattel, Inc.) </h1>
<p> Enter a question below, then click on the Magic 8-Ball to recieve its wisdom. </p>
<input type="text" id="questionBox" size=90 value="">
<p><input type="image" src="http://balance3e.com/Images/8ball.gif" id="button" onclick="magicEight();"></p>
<hr />
<img id="randomImg" />
</div>
Setting .value on outputDiv will not display images. You have to set the src attribute of an <img> tag.
Assuming all of the random images live in /Images, you could use the below as your new magicEight function.
function magicEight() {
var imgName;
imgName = RandomOneOf(["happy.gif", "sad.gif", "surprised.gif"]);
var imageTag = "<img src='/Images/" + imgName + "'>";
document.getElementById('outputDiv').innerHTML= imageTag;
}

Display a var in a span

<div id=name>Whats your Name?: <input type="text" id="User">
<input type="button" value="submit" onclick="giveUser()"/>
<br> I dont know your Name </br>
</div>
<br>
<div id=P2>
Oh its <span id=User>Default</span>!
</div>
<script>
function giveUser() {
var User = document.getElementById("User").value;
console.log(User)
document.getElementById('User').innerHTML = User;
document.getElementById('name').style.visibility = 'hidden';
document.getElementById('P2').style.visibility = 'visible';
}
</script>
Here i am asking the user there name through a textbox
but it won't display it in the span.
here is a fiddle demo
ID attributes should be unique. Your span and input both have an ID of User
Change the ID of one and then try again. (https://jsfiddle.net/k04pvhug/1/)
In addition, you should enclose all your attributes with quotes ("). It's not required, but it looks cleaner ;)
You need quotes around the id's.
<span id="someid" />
Then JavaScript can access the DOM and set innerHTML
Also, P2 is a pre-defined setting, so it's not aviable as an id anyway. try "paragraphTwo" or something.
Give the quotes around id and make sure that each attribute has the unique id
like this
<span id="id" />
<p id="paragraph" />
<span id="span2" />
Use a different name for the var and the id
function giveUser() {
var User = document.getElementById("User").value;
console.log(User)
document.getElementById("demo").innerHTML = User ;
document.getElementById('name').style.visibility = 'hidden';
document.getElementById('P2').style.visibility = 'visible';
}
#P2 {
visibility: hidden;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id=name>Whats your Name?:
<input type="text" id="User">
<input type="button" value="submit" onclick="giveUser()" />
<br>I dont know your Name</br>
</div>
<br>
<div id=P2>Oh its <span id="demo">Default</span>!</div>

innerHTML won't change element

I have an div element ("main") on my page who's contents changes back and forth between two different screens (their id's are "readout" and "num"), the contents of which are stored as hidden div elements (using display:none). Each screen has a button which sets mainto the other hidden div.
Since I struggled to get javascript to put num.innerHTML into main on load, I've ended up putting virtually identical content to num (with a different form name) into main:
<p>Number of Passengers per Carriage:</p>
<form method="post" action="javascript:void(0);" name="applesForm" onSubmit="setPassengers();">
<input type="text" name="numApples" id="numPassengers" />
<br/><br/>
<input type="submit" name="Submit" value="OK!"/>
</form>
setPassengers() successfully sets main's contents to readout. readout successfully sets main's contents to num (virtually identical to the original content of main). But then it won't go back to readout.
Here are setPassengers() and setPassengersAgain(), which is the same but for a different form name:
function setPassengers()
{
passengers=document.applesForm.numPassengers.value;
document.getElementById('main').innerHTML=readout.innerHTML;
}
function setPassengersAgain()
{
passengers=document.applesFormAgain.numPassengers.value;
document.getElementById('main').innerHTML=readout.innerHTML;
}
So my question is:
1)Why isn't num changing to readout?
2)Is there a way to load num straight away on page load so as to simplify the code?
EDIT: I can use onload, which means that num is the only bit that's broken...
EDIT 2: Here are the hidden div's:
<div id="readout" style="display:none">
<p>Throughput per hour:</p>
<p id="output">--</p>
<p>Average Dispatch Time:</p>
<p id="avDisTime">--</p>
<form method="post" action="javascript:void(0);" name="dispatchForm" onSubmit="dispatch();i++;">
<input type="submit" name="Submit" value="Press on Dispatch!"/>
</form>
<br/>
<form method="post" action="javascript:void(0);" name="resetTimesForm" onSubmit="resetTimes();">
<input type="submit" name="Submit" value="Reset Times"/>
</form>
<form method="post" action="javascript:void(0);" name="resetAllForm" onSubmit="resetAll();">
<input type="submit" name="Submit" value="Reset All"/>
</form>
</div>
<!--back to default page-->
<div id="num" style="display:none">
<p>Number of Passengers per Carriage:</p>
<form method="post" action="javascript:void(0);" name="applesFormAgain" onSubmit="setPassengersAgain();">
<input type="text" name="numApples" id="numPassengers" />
<br/><br/>
<input type="submit" name="Submit" value="OK!"/>
</form>
</div>
You didn't post your HTML code, so I don't know how it looks like, but you could use somethin like:
HTML:
<button id="changeMain">Change #main</button>
<div id="main">
<div id="readout" class="screen show">
Readout
</div>
<div id="num" class="screen">
Num
</div>
</div>
CSS:
#main>.screen{display:none;}
#main>.screen.show{display:block;}
JavaScript:
var els=[document.getElementById('readout'),document.getElementById('num')],current;
function addClass(el,c){
var arr=el.className.split(' ');
if(arr.indexOf(c)>-1){return;}
arr.push(c);
el.className=arr.join(' ');
}
function delClass(el,c){
var arr=el.className.split(' ');
var i=arr.indexOf(c);
if(i===-1){return;}
arr.splice(i,1);
el.className=arr.join(' ');
}
document.getElementById('changeMain').onclick=function(){
if(!current){
for(var i=0,l=els.length;i<l;i++){
if(els[i].className.indexOf('show')>-1){
current=i;
break;
}
}
}
delClass(els[current],'show');
current=(current+1)%els.length;
addClass(els[current],'show');
}
DEMO: http://jsfiddle.net/CUgqh/
Explanation:
If you want some content insode #main, you should place inside it (hidden or shown). Then, we hide all .screen with #main>.screen{display:none;} except .screen.show: #main>.screen.show{display:block;}.
Then, JavaScript code:
First we create an array with the elements:
var els=[document.getElementById('readout'),document.getElementById('num')],current;
And a function which adds/removes a class c to the element el:
function addClass(el,c){
var arr=el.className.split(' ');
if(arr.indexOf(c)>-1){return;}
arr.push(c);
el.className=arr.join(' ');
}
function delClass(el,c){
var arr=el.className.split(' ');
var i=arr.indexOf(c);
if(i===-1){return;}
arr.splice(i,1);
el.className=arr.join(' ');
}
And we create an event to the button:
document.getElementById('changeMain').onclick=function(){
if(!current){
for(var i=0,l=els.length;i<l;i++){
if(els[i].className.indexOf('show')>-1){
current=i;
break;
}
}
}
delClass(els[current],'show');
current=(current+1)%els.length;
addClass(els[current],'show');
}
The code above does:
If it's the first time the current els' index (current) is undefined, we search which element has the class show by default.
It removes the class show to the current shown element, so it disappears.
It adds 1 to current (or it becomes 0 if it was the last els' element
It add class show to the current element, so it appears.

Categories