it does not returns prpoer answer it returnes NAN in Answer
<html>
<head>
<script type="text/javascript">
function pro(n,p)
{
var number=parseInt(n);
var powe=parseInt(p);
for(var i=1;i<powe;i++)
{
number*=number;
}
document.getElementById("answer").value=number;
}
</script>
</head>
<body>
<form name="F" >
Enter Number <input type="text" name="num" id="num"/>
Enter Power <select name="powe" id="powe">
<option value="2" >square</option>
<option value="3" >cube</option>
</select>
Answer<input type="text" name="Answer" id="answer" />
<input type="button" onClick="pro(num,powe)" value="Calculate" />
</form>
</body>
</html>
The issue is this: onClick="pro(num,powe)". Instead of the values for num and powe being gotten from the input elements and passed into the pro function, the actual element references (which are not numbers) are being passed.
To solve this problem, you'll need to get the values of the elements. But, before you just make a quick edit to your code, don't use inline HTML event attributes (onclick) in the first place. Instead, separate your JavaScript from your HTML and set up event handlers using modern standards with .addEventListener() as shown below.
Also (FYI):
Since you aren't actually submitting form data anywhere, you don't
need a <form> element.
It's not necessary to use parseInt with p.value because that
value is coming from your select and you've already set those at
whole numbers.
Don't bother with self-terminating tags (<input />) as you
gain nothing from using them.
If you are expecting only numeric input, it's better to use input
type=number which restricts the user input to numbers. Making this change also saves you from worrying about parseInt on the input number being misinterpreted as other bases than 10.
Since you don't want the user to be able to change the result of the
operation, it's better to display it in a non-editable element, like
a span.
It's a good idea to move your <script> element to just before the
closing body tag because, by the time the parser reaches that
point, all your HTML elements will have been parsed into memory.
<html>
<head>
</head>
<body>
<div>
Enter Number <input type="number" name="num" id="num">
</div>
<div>
Enter Power
<select name="powe" id="powe">
<option value="2">square</option>
<option value="3">cube</option>
</select>
</div>
<div>
Answer <span id="answer"></span>
</div>
<div>
<input type="button" value="Calculate">
</div>
<script>
// Get references to the inputs, the answer container and the button
let inputNum = document.getElementById("num");
let power = document.getElementById("powe");
let answer = document.getElementById("answer");
let btn = document.querySelector("input[type='button']");
// Set up the click event handler for the button
btn.addEventListener("click", function(){
// Now you need to get the input values and pass them
// to the function that will act with them
pro(inputNum.value, power.value);
});
function pro(n,p) {
var number = parseInt(n);
for(var i = 1; i < p; i++) {
number *= number;
}
answer.textContent = number;
}
</script>
</body>
</html>
Try
document.getElementById("answer").innerHTML = number
Related
Is it possible to autocomplete only after a user entered at least 3 letters?
Here is my current code:
HTML/PHP:
<form name="form" class="form-container" method="post" onsubmit="return doValidate()" id="myForm2">
<label>
<input placeholder="Organisator" id="name" list="users" name="mitarbeiter" required />
</label>
<datalist id="users" class="dle" >
<?php
for ($i=0; $i<$counts; $i++) {
echo '<option value="'.$AllData[$i]["mail"][0].'">'.$AllData[$i]["cn"][0].'</option>';
}
?>
</datalist>
<br><br>
von
<input type="time" name="zeitstart" class="zeitangaben" id="startzeitid"> Uhr bis
<input type="time" name="zeitende" id="endzeitid" class="zeitangaben"> Uhr <br><br>
<button type="submit" class="btn" name="submit">Reservierung erstellen</button>
<button type="reset" class="btn cancel" onclick="hideDiv()">Abbrechen</button>
</form>
I only find some Code with Jquery, is it not possible to do this without jquery?
Is it even possible? Any ideas?
Here is a way to do it: removing the datalist ID attribute.
First, declare the querySelector() methods.
var input = document.querySelector("#name"), // Selects the input.
datalist = document.querySelector("datalist"); // Selects the datalist.
Then declare the addEventListener method on the input element.
// Adds a keyup listener on the input.
input.addEventListener("keyup", (e) => {
// If input value is longer or equal than 2 chars, adding "users" on ID attribute.
if (e.target.value.length >= 2) {
datalist.setAttribute("id", "users");
} else {
datalist.setAttribute("id", "");
}
});
Explanation
When the input value has a length greater than or equal to 2, the setAttribute() method sets the datalist ID attribute to "users".
I set the operator to >= 2 and not >= 3. Here is why: the datalist dropdown element is triggered at each keypress.
The process goes like this:
length == 1 id="" - The drop down is not displayed, no ID is linked to the datalist;
length == 2 id="users" - The drop down is not displayed, then datalist has its ID set to "users";
length == 3 id="users" - The drop down now reads that the ID is set to "users" and displays the drop down.
Cons
Since the attribute is set when the input length is >= 2, if the input length == 3, the attribute will be removed when the input length == 2, and the drop down will be hidden when the input length == 1.
Since the drop down list is part of the OS and is not a DOM
element, it cannot be styled (or hidden, in this case). This is why I
used the setAttribute() method to set or remove the ID.
Upgrade?
A great upgrade / perfect solution would be creating a dropdown in JS just under the input. The drop down would be DOM element, and you could style it the way you want. You could ealisy display it > 2 chars and hide it < 3 chars.
Snippet
var input = document.querySelector("#name"), // Selects the input.
datalist = document.querySelector("datalist"); // Selects the datalist.
// Adds a keyup listener on the input.
input.addEventListener("keyup", (e) => {
// If input value is larger or equal than 2 chars, adding "users" on ID attribute.
if (e.target.value.length >= 2) {
datalist.setAttribute("id", "users");
} else {
datalist.setAttribute("id", "");
}
});
// I had to include your doValidate() function otherwise I would get an error while validaing.
function doValidate() {};
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>reading json</title>
<script type="text/javascript">function log(p) {return console.log(p)}</script>
</head>
<body>
<form name="form" class="form-container" method="post" onsubmit="return doValidate()" id="myForm2">
<label><input placeholder="Organisator" id="name" list="users" name="mitarbeiter" autocomplete='off' required /></label>
<datalist id="users" class="dle">
<option value="alicia#keys.com">Alicia Keys</option>
<option value="alicia#keyssecond.com">Alicia The Second</option>
<option value="john#doe.com">John Doe</option>
<option value="martin#scorsese.com">Martin Scorsese</option>
<option value="iron#man.com">Iron Man</option>
</datalist><br><br>
von <input type="time" name="zeitstart" class="zeitangaben" id="startzeitid"> Uhr bis <input type="time" name="zeitende" id="endzeitid" class="zeitangaben"> Uhr <br><br>
<button type="submit" class="btn" name="submit">Reservierung erstellen</button>
<button type="reset" class="btn cancel" onclick="hideDiv()">Abbrechen</button>
</form>
</body>
</html>
You need to use javascript and listen to the keyup event for your input element.
Then you check if the value of the input is longer than 3 character and if it is, you need to make an ajax request to your server to get the related names and use them to fill the datalist
Just thought I'd share what I did using setAttribute and removeAttribute on the keyUp and keyDown to display the datalist (dir) when the text box contains at least 3 characters and handling the Backspace (keyCode=8) to prevent the full list from showing as it widens the search results.
<input type="search" name="q" id="q" autofocus="true"
onkeyup="if(this.value.length>=3)this.setAttribute('list','dir');"
onkeydown="if(this.value.length<3||event.keyCode==8)this.removeAttribute('list');"
placeholder="Search Staff Directory"
/>
Hope this helps anyone looking for a simple solution that does not require jQuery or Ajax, just a simple datalist.
I have created a working Binary to Decimal Calculator but would like a HTML input.
<html>
<input placeholder="00000000" name="htmlinput"></input>
<input id="clickMe" type="button" value="Go" onclick="runbintodec();"></input>
</html>
<script>
function runbintodec()
{
var bin = document.getElementByName('htmlinput').value;
...(Bin to Dec Calc code)
}
</script>
I need some way to take an input from a html input form and send it to the script when i click the button 'go'.
First of all, input is a non-closing tag. Secondly, there's nothing like document.getElementByName, use document.getElementsByName instead or even better - assign an unique id identifier to your input and then catch it by document.getElementById.
function runbintodec() {
var bin = document.getElementsByName('htmlinput')[0].value;
}
<input placeholder="00000000" name="htmlinput">
<input id="clickMe" type="button" value="Go" onclick="runbintodec();">
I am trying to make a small calculator-thingy for my website. I want to be able to write a number in a text-input, then get the double of that number back. I tried this way at first:
<form name="form">
<input type="text"/>
</form>
<script type="text/javascript">
function calc() {
var x = document.forms[0].elements[0].value;
document.write(x*2);
}
</script>
<input type="button" onClick="calc()" value="Calculate here"/>
This is working fine, but when calling the function ( calc() ) with the button, all HTML is removed. The only thing appearing is the double of the number (variable x) you wrote. I have read that the "function" make all other HTML disappear.
Is it possible to make the page stay the same, but at the same time showing the calculated number (x*2)? Can I reach the variable x without using a function?
Is it possible to "control" where and how the calculated number (x*2) is going to appear, within the JavaScript or within the HTML?
I am new to this coding art, was hoping to find a relatively easy way to solve this.
Thanks!
The best way is probably to add a div outside the form which is intended to reflect the calculated value. Then you can update calc to find this div and replace its contents with the calculated value.
<script>
function calc() {
var x = document.forms[0].elements[0].value;
var result = x * 2;
document.getElementById("result").innerHTML = result;
}
</script>
<form name="form">
<input type="text"/>
</form>
<input type="button" onclick="calc()" value="Calculate here"/>
<div id="result"></div>
Adding to your original code and the accepted answer.
Make sure that the value you retrieve is an integer(or a float).This way you will prevent the user from getting weird results.
You can do it like this:
<script>
function calc() {
var x = parseFloat(document.forms[0].elements[0].value);// or parseInt(document.forms[0].elements[0].value)
var result = x * 2;
document.getElementById("result").innerHTML = result;
}
</script>
<form name="form">
<input type="text"/>
</form>
<input type="button" onclick="calc()" value="Calculate here"/>
<div id="result"></div>
I cant for the life of me figure out why the following is not working. I took if from the W3school example here.
Basically I want to take the value from the input text when it changes and modify another div to include the value. I only want the div to show the new value, but I do want it to change it each time so I figured the onchange was the way to go.
<!DOCTYPE html>
<html>
<head>
<script>
function myFunction()
{
var div = document.getElementById('divID');
div.innerHTML = div.innerHTML + x.value;
}
</script>
</head>
<body>
Enter your name: <input type="text" id="fname" onchange="myFunction()">
<p>When you leave the input field, a function is triggered which transforms the input text to upper case.</p>
<div id="divID"></div>
</body>
</html>
Thanks in advance for all the help on this one.
You have 2 problems, first is that x is undefined.
second you should use another trigger for this for this to happen each time.
try this out:
function myFunction()
{
var input = document.getElementById('fname')
var div = document.getElementById('divID');
div.innerHTML = div.innerHTML + input.value;
}
and change your html to:
<input type="text" id="fname" onkeypress="myFunction()">
x is undefined in your function, it should be document.getElementById('fname').
And if you want to change the div each time you press the key, use onkeyup or onkeypress instead of onchange.
You may change x.value to document.getElementById("fname").value, if I understand your question correctly.
<head>
<script type="text/javascript">
function input(){
var input_taker = document.getElementById('email').value;
document.getElementById('display').innerHTML = input_taker;
}
</script>
</head>
<form method="post" action="#">
<input type="text" name="email" placeholder="email#example.com" id="email" onchange="input()">
<input type="submit" name="save" value="save">
</form>
<div id="display"></div>
Ok, so check this out - http://jsfiddle.net/2ufnK/2/
The issue is that you need to define x here,
var x = document.getElementById("fname");
x now references to the html object.
Then you can just call the, ".value", method to get its text. Then everything else works the way you've written it.
I'm attempting to make a form that asks the user for a number of units, then asks whether or not they would like those units to be provisioned, and depending on the answer, generates text fields corresponding with the number of units the typed in, along with a text field asking for an account number.
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.6.2/jquery.min.js">
</script>
<script type="text/javascript">
function Getunits(value) {
var units = document.getElementById('units');
for(count=0; count<=units; count++) {
$("<input type='text'>").appendTo("inpane");
}
document.getElementByTag('futureacc').InnerHTML='What is your account number? <input type="text" value="accountnum">';
}
</script>
</head>
<body>
<div id="container">
<form method="post" action="sendcontact.php">
<div id="unitammount" class="inpane">
Number of units ordered: <input type="text" name="units" id="units"/><br />
</div>
<div id="futureacc" class="inpane">
Are these units to be provisioned? <input type="radio" name="select" value="yes" onClick="Getunits('units.value')"/> Yes <input type="radio" name="select" value="no"/> No
</div>
Obviously I would like the new text fields to appear inside the futureacc div and inpane div respectively.
I don't know whether it's the loop that doesn't do anything or that I'm not appending correctly but as I currently have it this does nothing...
Any help would be greatly appreciated.
You had a number of errors with your code. It was confusing because you were mixing jQuery and pure Javascript. It's generally better to just use jQuery if you've decided to use it anyway. Your loop should have been iterating while it was smaller than units.val(), not while it was smaller than or equal to units. innerHTML is spelled with a lowercase "i," and your appendTo selector needed a period before the class name. I went ahead and cleaned up your code so it should work now!
HTML:
<div id="container">
<form method="post" action="sendcontact.php">
<div id="unitammount" class="inpane">
Number of units ordered: <input type="text" name="units" id="units"/>
</div><br>
<div id="futureacc" class="inpane">
Are these units to be provisioned? <input type="radio" name="select" value="yes" onClick="getUnits()"/> Yes <input type="radio" name="select" value="no"/> No <br>
</div>
</form>
</div>
Javascript:
function getUnits() {
var units = $("#units").val();
for (var count = 0; count < units; count++) {
$("<input type='text' /><br>").appendTo("#futureacc");
}
$("#futureacc").append('<br>What is your account number? <input type="text" placeholder="accountnum">');
}
WORKING DEMO
var units = document.getElementById('units');
needs to be
var units = document.getElementById('units').value;
you are passing value to onclick but it is a string will not give you exact value anyway you are not using it in you function so it doesnt have any side effect.
also you need to some error check to make sure that user has entered a number
with
for(count=0; count<=units; count++)
You are adding 1 more text box than user entered value. so if user has entered 4 you are creating 5 <= should be changed to <
This is wrong
onClick="Getunits('units.value')"
Instead use this:
onClick="Getunits(units.value)"
try this
$(document).ready(function(){
$('input[name=select]').click(function(){
if($(this).val() ==='yes'){
var numberOfTextboxes = $('#units').val();
for(var i =0; i<numberOfTextboxes; i++){
$('#unitammount').append('<input type="text" />');
}
}
});
});
See the fiddle