Javascript output text based on input value - javascript

I'm trying to make a form where you input a number to a textbox and based upon that a text response is put in a textbox.
This is an example of what I have been trying to make work:
<html>
<head>
<script type="text/javascript">
function calculate()
{
var ph = document.test.ph.value;
if (ph > 7.45) {
var str = "Alkalosis";
}
else if (ph < 7.35) {
var str = "Acidosis";
}
else {
var str = "Normal";
}
document.test.acidalk.value = str;
}
</script>
</head>
<body>
<form name="test">
pH<input type="textbox" name="ph"><br>
<input type="submit" value="Calculate"><br>
<input type="textbox" id="acidalk" >
</form>
</body>
</html>
The idea of what I'm trying to achieve is if a number higher than 7.45 is put in the first text box, the button clicked, then the word "Alkalosis" is put in the second text box, but if the number is less than 7.35, the word is "Acidosis" instead.
Any help would be greatly appreciated

Well, you're most of the way there. Instead of having the button be a submit button, try
<input type="button" onclick="calculate();" value="Calculate" />

Base of your code This will be a way to do it:
<html>
<head>
<script type="text/javascript">
function calculate(){
var ph = document.getElementById('ph').value;
if(ph > 7.45){
var str="Alkalosis";
}else if(ph < 7.35){
var str="Acidosis";
} else{
var str="Normal";
}
document.getElementById('acidalk').value =str;
}
</script>
</head>
<body>
pH<input type="textbox" name="ph"><br>
<button onclick="calculate()">Calculate</button>
<input type="textbox" id="acidalk" >
</body>
</html>
hope helps!

You have the form, you have the function, you just need a way to tie them together. Do it by assigning calculate() as an event handler for the form's submit event. Make sure to return false else the form will be submitted and the result of calculate() will not be seen.
<form name="test" onsubmit="calculate(); return false">
jsfiddle.net/UhJG2
Binding to the form's submit event rather than button's click event has the added benefit of calling the function when enter is pressed. It also ensures the form is not ever accidentally submitted.

With jQuery:
<html>
<head>
<script src="http://code.jquery.com/jquery-latest.min.js" type="text/javascript"></script>
</head>
<body>pH
<input type="textbox" name="ph" id="ph">
<br>
<button id="calculate">Calculate Acid Level</button>
<br />
<input type="textbox" id="acidalk" value="" />
</body>
<script type="text/javascript">
$("#calculate").click(function () {
var ph = $("#ph").val();
if (ph > 7.45) str = "Alkalosis";
else if (ph < 7.35) var str = "Acidosis";
else var str = "Normal";
$("#acidalk").val(str);
});
</script>
</html>

Related

How do I trigger a JavaScript function when a button is pressed in HTML code

I am trying to create a calculator that solves the Pythagoras theorem. I have created a function inside a tag in my code which takes two arguments (one for each leg length of the right-angled triangle) The function works if I just do a console.log with two numbers as arguments and the function executes properly if it is inside the script tag. But I just want to know how to take the two arguments in the text boxes and then when I press the button make the result appear on the screen.
<html>
<main>
<head>
<!--Textboxes to input lengths of legs-->
<input type = "text" required placeholder= "1st legnth">
<br> <br>
<input type = "text" required placeholder= "2nd legnth">
<br> <br>
<button type = "submit">Give me the answer.
</head>
</main>
</html>
<script>
function solveforHyp (a, b)
{
var c = a*a + b*b;
return Math.sqrt(c);
}
var final = (solveforHyp(3, 4));
console.log(final);
</script>
add a span after the button to contain the final result:
<span id="final-result"></span>
add an onclick event to your button, it might look like this:
<button type="button" onclick="onButtonSubmit()"></button>
you might also give some relevant ID's to the input like this:
<input type = "text" id="first-length" required placeholder= "1st legnth">
<input type = "text" id="second-length" required placeholder= "2nd legnth">
and finally, write the onButtonSubmit function to access the inputs and call the solveforHyp function :
function onButtonSubmit(){
const firstValue = document.getElementById('first-length').value;
const secondValue = document.getElementById('second-length').value;
document.getElementById('final-result').innerText = solveforHyp(firstValue,secondValue); // finally, put the returned value in the created span.
}
First of all your document structure is entirely wrong, a lot of tags are not closed script is after the HTML tag, and content is written inside head tag and head is inside main, NO doctype declaration is done, and most importantly if you wanna submit something you should have a form at least with preventing its default behavior. Learn HTML before JavaScript Brother, and also its a good practice to use input type Number when you already know the input will be always a Number.
and here is the code what you are trying to make
<!DOCTYPE html>
<html>
<head>
<title>Example</title>
</head>
<body>
<form id="formOne">
<input type="number" required placeholder="1st legnth" id="first">
<br> <br>
<input type="number" required placeholder="2nd legnth" id="second">
<br> <br>
<button type="submit">Give me the answer</button>
</form>
</body>
<script>
let form = document.querySelector("#formOne");
let inputOne = document.querySelector("#first");
let inputTwo = document.querySelector("#second");
form.addEventListener("submit", function(e){
e.preventDefault();
console.log(Math.sqrt(Math.pow(inputOne.value,2) + Math.pow(inputTwo.value,2)));
})
</script>
</html>
Js file function to be called
function tryMe(arg) {
document.write(arg);
}
HTML FILE
<!DOCTYPE html>
<html>
<head>
<script type="text/javascript" src='object.js'> </script>
<title>abc</title><meta charset="utf-8"/>
</head>
<body>
<script>
tryMe('This is me vishal bhasin signing in');
</script>
</body>
</html>
You can try like this:
<!DOCTYPE html>
<html>
<head>
<title>Parcel Sandbox</title>
<meta charset="UTF-8" />
</head>
<body>
<form id="form">
<input type="text" id="first_length" name="first_length" />
<input type="text" id="second_length" name="second_length" />
<input type="submit" value="Submit" />
</form>
<script>
function logSubmit(event) {
event.preventDefault();
var first_length = document.getElementById("first_length").value;
var second_length = document.getElementById("second_length").value;
var final = solveforHyp(first_length, second_length);
console.log(final);
}
const form = document.getElementById("form");
form.addEventListener("submit", logSubmit);
function solveforHyp(a, b) {
var c = a * a + b * b;
return Math.sqrt(c);
}
</script>
</body>
</html>

Dynamically show text field's contents on labels

I want to enter names using input field and then show those names dynamically on the click of a button. Can anyone provide me with a code sample that does that?
What you want to achieve is fairly easy to do with jquery. However while asking a question first give it a try and then ask if you dont get it.
$(function(){
$('#submit').on('click', function(){
var value = $('#name').val();
var text = '<p>' + value + '</p>';
$('#display').append(text);
})
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" name="inputNames" id="name">
<button id="submit">Submit</button>
<div id="display"></div>
<html>
<body>
<input type="text" name="Names" id="Names">
<input type="button" value="Click" onclick="SendName();" name="">
<p id="ShowNames"></p>
<script type="text/javascript">
function SendName() {
var d= document;
var InputNames = d.getElementById("Names").value;
var ShowNames = d.getElementById("ShowNames");
ShowNames.innerHTML +=InputNames+"</br>";
}
</script>
</body>
</html>

The value gets copied to the textarea but disappears after a moment

I am trying to copy the value of the textbox to the textarea However the value gets copied using the javascript function but it disappears from the textarea after a second. What am i doing wrong?Why does it get disappear after being copied?
this is the html:
<html>
<head>
<title>
</title>
<script src="scripts/script.js" type="text/javascript"></script>
</head>
<body>
<form>
<label>Key/Value Pair: </label><input type="text" name="inputText" id="t1"></br></br>
<label>Key/Value List: </label><br>
<textarea name="outputText" rows="10" cols="50" id="t2" ></textarea><br><br>
<input type="submit" value="Add" onClick="fn_copy()" />
</form>
</body>
and this is the javascript code:
function fn_copy()
{
var temp = document.getElementById("t1").value;
if(temp != "")
{
document.getElementById("t2").value = temp;
}
else
alert("Text is Empty");
}
Thank you.
Change your button type to button instead of submit. Otherwise your page will be refreshed (default behavior with submit) and hence the content of your textarea reset.
<input type="button" value="Add" onClick="fn_copy()" />
Your problem is that you are using input of type submit, when you click it, the fuction fn_copy execute, but also do a post request, and that is why the value disappears.
Change the input for a button like that and it will work
function fn_copy()
{
var temp = document.getElementById("t1").value;
if(temp != "")
{
document.getElementById("t2").value = temp;
}
else
alert("Text is Empty");
}
<form>
<label>Key/Value Pair: </label><input type="text" name="inputText" id="t1"><br><br>
<label>Key/Value List: </label><br>
<textarea name="outputText" rows="10" cols="50" id="t2" ></textarea><br><br>
<button type="button" onclick="fn_copy()">Add</button>
</form>
You can sse a working sample here: https://jsfiddle.net/8e5e4wuz/
http://www.w3schools.com/jsref/event_preventdefault.asp
Use preventdefault to stop it from submitting.
Try this. Add any id to the button, for example btn, and do this:
function fn_copy()
{
var temp = document.getElementById("t1").value;
if(temp != "")
{
document.getElementById("t2").value = temp;
}
else
alert("Text is Empty");
}
document.getElementById("btn").addEventListener("click", function(event){
fn_copy();
event.preventDefault();
})

Form textbox content with javascript

I would like to know if there is better way to this exercice.
Here it is : Create a form that contain a textbox ;after the user enter the text ,all the letters will be converted to lowercase as soon as he or she clicks elsewhere in the form( hint: use change onChange event handler).
I have written this code :
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Event</title>
</head>
<body>
<form>
Username : <input type="text" id="username"><br>
<input type="submit" value="button">
</form>
<script type="text/javascript">
var username = document.getElementById("username");
username.onchange = function(){
username.value = username.value.toLowerCase();
};
</script>
</body>
</html>
Basically i'm replacing the content of the textbox by the formatted
Might be too easy, but setting the text over a style to lowercase transform doesn't allow uppercase :)
function toLower(element) {
if (element && element.value) {
element.value = element.value.toLowerCase();
var target = document.getElementById('realvalue');
target.innerHTML = element.value;
}
}
<input type="text" onblur="toLower(this)" />
<div id="realvalue"></div>
But, if all the letters will be converted to lowercase as soon as he or she clicks elsewhere in the form, your code work correctly...
http://jsfiddle.net/b6xwde62/
<form>
Username : <input type="text" id="username"><br>
<input type="submit" value="button">
</form>
<script type="text/javascript">
var username = document.getElementById("username");
username.onchange = function(){
username.value = username.value.toLowerCase();
};
</script>

Creating text fields according to user's input in JavaScript Function

I want to create text fields according to user's input and show the text fields through JavaScript function but this code is not working!
<html>
<head>
<title>Create text Fields according to the users choice!</title>
<script type="script/JavaScript">
function createTextField(){
var userInput = parseInt(document.form2.txtInput.view);
for(var i=0; i<=userInput;i++)
{
document.write('<input type="text">');
}
}
</script>
</head>
<form action="http://localhost.WebProg.php" method="post" name="form2">
<p>How many text fields you want to create? Enter the number below!</p>
Input: <input type="text" name="txtInput">
<input type="button" name="btnInput" value="Create" onclick="createTextField();">
</form>
</html>
Please Replace this line:
var userInput = parseInt(document.form2.txtInput.view);
To
var userInput = parseInt(document.getElementsByName('txtInput')[0].value);
function createTextField(){
// alert(document.getElementById('txtInput').value);
var userInput = parseInt(document.getElementsByName('txtInput')[0].value);
for(var i=0; i<userInput;i++)
{
document.write('<input type="text">');
}
}
<html>
<head>
<title>Create text Fields according to the users choice!</title>
</head>
<form action="http://localhost.WebProg.php" method="post" name="form2">
<p>How many text fields you want to create? Enter the number below!</p>
Input: <input type="text" name="txtInput" id="txtInput">
<input type="button" name="btnInput" value="Create" onclick="createTextField();">
</form>
</html>
You shouldn't use document.write. The correct way to do it is to append the inputs to a div.
Demo on Fiddle
HTML:
<form action="http://localhost.WebProg.php" method="post" name="form2">
<p>How many text fields you want to create? Enter the number below!</p>Input:
<input type="text" name="txtInput" />
<input type="button" name="btnInput" value="Create" />
<div></div>
</form>
JavaScript:
var btn = document.getElementsByTagName("input")[1];
btn.onclick = function () {
var userInput = parseInt(document.getElementsByTagName("input")[0].value, 10);
for (var i = 0; i <= userInput - 1; i++) {
document.getElementsByTagName("div")[0].innerHTML += "<input type='text' />"
}
};
Jquery is better option to add dynamic input/div's easy to manipulate DOM.
Check the following code
<div class="box">
<label> Enter input value </label>
<input type="number" id="in_num"/>
<button type="button" id="submit"> submit </button>
<h3> Append input values</h3>
<div id="dynamicInput"></div>
</div>
$(document).ready(function(e){
$('#submit').click(function(){
var inputIndex = $('#in_num').val();
for( var i=0; i<inputIndex; i++)
{
$('#dynamicInput').append('<input type=text id=id_'+ i +'/>');
}
});
});
Demo URl: http://jsfiddle.net/sathyanaga/75vbgesm/3/
Change:
var userInput = parseInt(document.form2.txtInput.view);
To:
var userInput = parseInt(document.getElementById("txtInput").value);
And give the input textbox an id (I used "txtInput", but it can be anything).
I believe you also need to change the loop from, when I typed "2" it created 3 inputs instead of 2.

Categories