Showing characters while typing - javascript

I need to see characters while I am typing characters inside an input, and I want to achieve this the simplest way. I have tried the following way, but it is not working. I am more interested to know what I am doing wrong rather than to get a script.
<input type='text' id='inpt' />
<script>
var getText = document.getElementById("inpt");
document.write(getText);
</script>

You're thinking of a callback, or event handler. Typically you would use onkeyup=callback_name(), and callback_name() would write to the element you want the output to appear in.
<script type="text/javascript">
function callback()
{
var text = document.getElementById('input').value;
document.getElementById('output').innerHTML = text;
}
</script>
<input type='text' id='input' onkeyup='callback()' />
<div id="output"></div>

Related

Javascript getElementByID from form input

I am providing a form where the user shall enter an arithmetic calculation. Further down the result shall appear, once the user hits enter. It might just be a problem of syntax, but I couldn't find the mistake. Here is what I did so far:
<!DOCTYPE html>
<html>
<body>
<p>What do you want to calculate?</p>
<form method="post"><span>Type here:</span><input type="text" id="calc"></input>
</form>
<script>
num_field = document.getElementById("calc");
num_field.onsubmit=function ()
{
document.getElementById("display_result").innerHTML = num_field;
}
</script>
<p id="display_result"></p>
</body>
</html>
So, the user shall enter for instance "1+2". The result shall appear below.
Any idea where is my mistake?
Best regards
Here is how you can achieve that.
eval is the best way for doing that but eval is risky to use so make sure to sanitize the value of input before using eval.
I am using this regex /(^[-+/*0-9]+)/g to extract only numbers and few operators (-+/*) and doing eval on that value.
remove the <form> that is not required use keypress event listener and check for enter key. keycode of enter key is 13
num_field = document.getElementById("calc");
num_field.onkeypress = function(e) {
if(e.which==13)
{
var value = num_field.value.match(/(^[-+/*0-9]+)/g);
if(!value) return;
else value = value[0];
var res = eval(value);
document.getElementById("display_result").innerText = res;
}
}
<p>What do you want to calculate?</p>
<span>Type here:</span>
<input type="text" id="calc" />
<p id="display_result"></p>
You were nearly there, your code just needed a bit of tweaking - see below (comments in code as what I have done and why)
The following seems to be an alternate and safer way to do this without using eval (function taken from the second answer in this post):
<!DOCTYPE html>
<html>
<body>
<p>What do you want to calculate?</p>
<form method="post" id="form">
<span>Type here:</span>
<input type="text" id="calc"> <!-- inputs are self closing no need for closing tag -->
<input type="submit" value="submit"> <!-- added a submit button -->
</form>
<script>
form = document.getElementById("form");
num_field = document.getElementById("calc");
form.onsubmit = function() { // attach this event to the form
document.getElementById("display_result").innerHTML = evalAlternate(num_field.value); // add .value here to get the value of the textbox
return false; // return false so form is not actually submitted and you stay on same page (otherwise your display result will not be updated as the page is reloaded
}
function evalAlternate(fn) { // function safer alternate to eval taken from here: https://stackoverflow.com/questions/6479236/calculate-string-value-in-javascript-not-using-eval
fn = fn.replace(/ /g, "");
fn = fn.replace(/(\d+)\^(\d+)/g, "Math.pow($1, $2)");
return new Function('return ' + fn)();
}
</script>
<p id="display_result"></p>
</body>
</html>
see the below fiddle
https://jsfiddle.net/ponmudi/13y9edve/
num_field = document.getElementById("calc");
num_field.onkeydown = (event) => {
if (event.keyCode === 13) {
document.getElementById("display_result").innerHTML = eval(num_field.value);
return false;
}
}
This should work:
calc = document.getElementById("calc");
formula = document.getElementById("formula");
calc.addEventListener('click', function() {
document.getElementById("display_result").innerHTML = eval(formula.value);
});
<p>What do you want to calculate?</p>
<span>Type here:</span>
<input type="text" id="formula" />
<button id="calc" type="submit">calc</button>
<p id="display_result"></p>
eval() JavaScript Method
Try this:
var calculation_input = document.getElementById('calculation_input');
calculation_input.onkeydown = function(event) {
if (event.keyCode == 13) { // Enter key.
// Sanitize before using eval()
var calculation = calculation_input.value.replace(/[^-()\d/*+.]/g, '');
document.getElementById("display_result").innerHTML = eval(calculation);
}
}
<p>What do you want to calculate?</p>
<span>Type here:</span>
<input type="text" id="calculation_input" />
<p id="display_result"></p>
You don't need to submit the calculation in a form, you can just use native javascript to calculate the result. And don't forget to always sanitize before using eval :)

How to pass a Javascript ID value into a form Placeholder?

I have used a function to capture the Query String value of "name" - i.e. imagine a party invite site;
https://cometomyparty.com?name=phil
The function used is;
script type="text/javascript">
function getQuerystring(){
var q=document.location.toString();
q=q.split("?");
q=q[1].split("&");
var str=""
for(i=0;i<q.length;i++){
tmp=q[i].split("=")
str+=" "+tmp[1]+"<br />"
}
document.getElementById("name").innerHTML=str
}
onload=function(){
getQuerystring()
}
</script>
Then I can call the value of 'name' using id="name" where I want to use this on my page, i.e. in the heading, I could say, Phil, looking forward to having you at the party...
That's working well. The problem I have is, I have a Form I'm using as well, and within that, it has a Placeholder field, like so;
<div class="form-section">
<input type="text" name="name" class="validate-required" placeholder="Names">
How can I insert my 'id' value of 'name' into my placeholder here? The end result would be, the invite mechanic would work on the same URL, across multiple invitees, but the URL would just change. The RSVP form would reflect what is in the URL as the placeholder, yet the user could still update it if it was incorrect.
Any advice appreciated.
This find placeholder and change using jquery
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script>
$(document).ready(function(){
$('#name').attr("placeholder", "your place holder here");
});
</script>
if it's a $var also don't need quotes would be like
$('#name').attr("placeholder", $str);
Or using javascript
<script type="text/javascript">
function getQuerystring(){
var q=document.location.toString();
q=q.split("?");
q=q[1].split("&");
var str=""
for(i=0;i<q.length;i++){
tmp=q[i].split("=");
str+=" "+tmp[1]+"<br />";
}
document.getElementById("name").innerHTML=str;
document.getElementById("name").placeholder=str;
}
onload=function(){
getQuerystring();
};
</script>
document.getElementById("name").placeholder="value here" if it's a var so don't need quotes
Also you need to insert an id to your html input field
<div class="form-section">
<input type="text" id="name" name="name" class="validate-required" placeholder="Names">

Passing on a variable to a JS function from HTML

I'm currently working on a little programming task for school. I chose the task because I had an idea how to get the core of the program running in Java, but I'm having issues translating this into a very simple web page, no experience with HTML or JS.
My issue is: I'm receiving input via a button. When clicked, a function is called and that function gets the value of the input. However, all I get as the alert window is objectHTMLinputElement. What am I doing wrong?
function myRT() {
var risikoTraeger=document.getElementById('input1').value;
}
function myRH() {
var risikoHoehe = parseInt(document.getElementById('input2')).value;
alert(input2);
}
<h1>Siemens: Risikoassessment</h1>
<p id="demo">How many entries?</p>
<input type="text" id="input1" />
<button type="button" onclick="myRT()">Risk carrier</button>
<input type="text" id="input2" />
<button type="button" onclick="myRH()">Sum of the risk</button>
Get the value of the input before parsing it. Plus, you are alerting an input element instead of the variable that you are setting the value to. Use:
function myRH(){
var risikoHoehe = parseInt(document.getElementById('input2').value);
alert(risikoHoehe);
}
Change this part parseInt(document.getElementById('input2')).value; as :
parseInt(document.getElementById('input2').value)
You're calling the wrong variable, try 'risikoHoehe' instead of 'input2':
function myRT() {
var risikoTraeger=document.getElementById('input1').value;
}
function myRH(){
var risikoHoehe = document.getElementById('input2').value;
alert(risikoHoehe);
}
1) You are trying to parse a DOM element to an int so it returns undefined.
Use document.getElementById('input2').value.
2) Use parseInt only if needed, if its just for alerting then you can skip it
3) You cannot directly refer to an dom element by id, you have to get that element in a variable and then use it.
alert(input2); should be alert(risikoHoehe);
Well, Here is the complete working code-
<!DOCTYPE html>
<html>
<head>
<script type="text/javascript">
function myRT() {
var risikoTraeger=document.getElementById('input1').value;
alert(risikoTraeger);
}
function myRH(){
var risikoHoehe = parseInt(document.getElementById('input2').value);
alert(risikoHoehe);
}
</script>
</head>
<body>
<h1>Siemens: Risikoassessment</h1>
<p id="demo">How many entries?</p>
<input type="text" id="input1" />
<button type="button" onclick="myRT()">Risk carrier</button>
</br>
<input type="text" id="input2" />
<button type="button" onclick="myRH()">Sum of the risk</button>
</body>
</html>
Hoping this will help you :)
Let's see what you are doing wrong:
var risikoHoehe = parseInt(document.getElementById('input2')).value;
document
document itself
getElementById()
the function which gives us the element that has the specific ID parameter
'input2'
the ID of the desired input
.value
the element's value if it has any.
parseInt()
the function that converts any string to it's integer value.
now look at here:
document.getElementById('input2') => the input element itself (objectHTMLInputElement)
parseInt(objectHTMLInputElement) => what can we get if we try to convert the html input element to an integer?
(integer).value => does integers have value property?
But if you write it like this:
var risikoHoehe = parseInt(document.getElementById('input2').value);
document.getElementById('input2') => the input element itself (objectHTMLInputElement)
objectHTMLInputElement.value => the value of the input as string
parseInt(string) => Parse the integer value of the string

Return Output in an HTML Element onkeyup

I'm working on html editor but this part is giving me a problem is there anyway to archive this? when i type in the text filed it will display an output in the div element.
<script type="javascript/text">
function ColorText(){
T = Rep(document.getElementById("text").value);
document.getElementById("wcode").innerHTML=T;
setTimeout("ColorText()",10);
}
</script>
HERE IS HTML PART
<input type="text" id="text" onkeypress="ColorText()"/>
<div type="text" id="wcode"></div>
A more elegant solution, without setTimeout:
function Rep(value){
//Do your thing...
return value;
}
var wcode = document.getElementById("wcode");
var text = document.getElementById("text");
text.addEventListener("input", function(){
wcode.innerHTML = Rep(this.value);
});
<input type="text" id="text"/>
<div id="wcode"></div>
Codesoft, your code may not be working for 2 things:
<script type="javascript/text">
change it for:
<script>
or
<script type="text/javascript">
And the other possible problem:
T = Rep(document.getElementById("text").value);
Maybe you hadn't defined the function Rep(). You have to define it and return a string value, or just don't use it, like this:
T = document.getElementById("text").value;
Besides of that, Marcos Casagrande gave you a better solution to your problem, please, take a look to that code.

How to get the return value of a java-script function to a variable which is called on keyup

I am really new to javascript. I am trying to create an auto load text box for my project. I want to get the return value of a javascript function to a variable when the function is called on keyup event. How can I do that.
<input id="autocomplete" onkeyup="myFunction()">
<script>
var abc = "";
function myFunction() {
var keywordx = document.getElementById("autocomplete").value;
abc = keywordx;
}
console.log(abc);// abc should have the typed values in the
</ script>
**EDITED
Try this:
<input id="autocomplete" onkeyup="myFunction()" onchange="showIt()">
function showIt() {
console.log(abc);
}
This waits until you finish editing the field before trying to use abc.
Try this code
<input id="autocomplete" onkeyup="myFunction()">
<input type='button' id='temp' onclick='getText()' value='Get Text'>
<script>
var abc = "";
function myFunction() {
var keywordx = document.getElementById("autocomplete").value;
abc = keywordx;
}
function getText() {
console.log(abc);
}
</script>
The code below should fix your problem. There's not a need to create the variables outside the function. Just keep it simple by passing around one variable as the value and resetting it with each onkeyup event.
function myFunction() {
var x = document.getElementById("autocompleted").value;
console.log(x)
}
More elegant solution will be like this
var autocomplete = document.querySelector('#autocomplete');
autocomplete.onkeyup = function(e) {
alert(e.target.value);
//e.target.value is value of input
//console.log or use it
}
<input id="autocomplete">
I would recommend use Hidden Filed instead of global variable.
You can achieve the same functionality using jQuery
<input id="autocomplete" onkeyup="myFunction()">
<input type="hidden" id="someFlag" />
<script>
$('#autocomplete').keyup(function () {
$('#someFlag').val($('#autocomplete').val());
console.log($('#someFlag').val());
})
</script>

Categories