Javascript Replace onKeyUp event with a string - javascript

Im not very good at JavaScript and need a hand with what I think is an easy script. Basically I have an input box that when the user types in a key it will disappear and change to whatever string I have. I could only get the one letter to change, so that I have something to show what i mean. So whenever a user types a message it gets replaced with an "h", what I want though is to have "hello" typed out letter by letter and not just "h" all the time and not "hello" all at once.
Here is the code.
<form action=# name=f1 id=f1 onsubmit="return false">
<input type=text name=t1 id=t1 value="" size=25 style="width:300px;"
onkeypress="if(this.value.match(/\D/))"
onkeyup ="this.value=this.value.replace(/\D/g,'h')">
</form>

JUST EDITED AS IT IS GIVING JS ERROR HOPE YOU WONT MIND:Are you trying something like this:
function replaceString(el){
var sampleText = "hello".split("");
var value = "";
console.log(el)
el.value.split("").forEach(function(str, index){
value += sampleText[index%sampleText.length];
});
el.value = value;
}
<form action=# name=f1 id=f1 onsubmit="return false">
<input type=text name=t1 id=t1 value="" size=25 style="width:300px;"
onkeypress="if(this.value.match(/\D/));"
onkeyup ="replaceString(this);"/>
</form>

If you want to simulate typing text into the textbox then you will need to use a timeout. The following function should suffice:
function simulateTyping(str, el)
{
(function typeWriter(len)
{
var rand = Math.floor(Math.random() * (100)) + 150;
if (str.length <= len++)
{
el.value = str;
return;
}
el.value = str.substring(0,len);
if (el.value[el.value.length-1] != ' ')
el.focus();
setTimeout(
function()
{
typeWriter(len);
},
rand);
})(0);
}
You'll need to pass it two parameters : the string to type e.g. "hello" and the element into which to type the string. Here's a simple wrapper function:
function typeHello() {
var el = document.getElementById('t1');
var str = 'hello';
simulateTyping(str, el);
}
When you call the typeHello function it will find the element with the "t1" id and type the "hello" text.

Related

Mask the first 2 characters in input form

Hello i trying to hide/change (with *) the 1-st and 2-nt characters in input form, but value do not changed.
E.x if in my input form i put sarahlovecode in input form show **rahlovecode, but when submit get the full value sarahlovecode
HTML:
<input type="text" class="input" name="secret_word" id="secret_word">
And Js i using is:
$.fn.mask = function( regexp, matchGroup, callback ) {
this.on("blur", function(e){
$(this).data("value", this.value);
var result;
while (result = regexp.exec(this.value)) {
var matches = result.slice(1);
if (callback){
var substitute = callback(matches[0]);
} else {
var substitute = Array(matches[matchGroup-1].length + 1).join("*");
}
matches[matchGroup-1] = substitute;
this.value = matches.join("");
}
})
this.on("focus", function(e){
this.value = $(this).data("value") || "";
});
}
// With Regular expression
phoneRegexp = new RegExp("(.*?)(.{1})$", "g");
$("#secret_word").mask(phoneRegexp, 2);
ref: https://www.sitepoint.com/community/t/mask-input-fields-without-affecting-validation/37100/15
And it's working but change the value with **, same as input word.
Suggestion to fix this?
Thanks.
You need to change the value of the input back when you submit the form. Add a function on the event "onsubmit" of the form:
<form onsubmit="fix_asterisk();">
<fieldset>
<input type="text" class="input" name="secret_word" id="secret_word">
</fieldset>
<input type="submit">
</form>
Then in the javascript add the function:
<script>
function fix_asterisk(){
let input = document.getElementById("secret_word");
input.value = $(input).data("value");
}
</script>

Basic math functions in JavaScript to show on HTML page

I would like to make major of basic math functions (addition, subtraction, ect.) to develop in JavaScript. Input parameters should be from HTML webpage, than do the in JavaScript and return result on the same HTML page.
function math() {
//document.getElementById("frm1").innerHTML;
var numb = document.getElementById("number").innerHTML;
var mod = document.getElementById("modifier").innerHTML;
console.log(numb);
console.log(mod);
var sum = 1; //numb + mod; //the 1 is a placeholder
console.log(sum);
sum = document.getElementById("sum").innerHTML;
}
<form id="frm1" action="randScript.js">
Number: <input type="int" name="number" id="number"><br> Modifiers: <input type="int" name="modifier" id="modifier"><br>
<input type="button" onclick="math()" value="Submit">
</form>
<p id="sum"></p>
Your form tag has an action attribute. This means the page will submit your information to the specified page. You can use jQuery to prevent the form from submitting.
$("#yourFormId").on("submit",function(event){event.preventDefault()})
You can also edit the forms action attribute itself to prevent it from submitting.
<form id="frm1" action"javascript:void(0);">
First: The type is text - there is no "int" thing
Number: <input type="text" name="number" id="number">
Second: if we read a bit documentation we figure also out how to get the alue into the JS part
var numb = document.getElementById("number").value;
here you can now do your further homework ;)
Third: Get things back:
either use another input. They work two ways.
document.getElementById("result").value="I did not do my homework alone"
or you place a div somewhere with an id
<div id="result"> </div>
and now you can really use innerHTML in js
document.getElementById("result").innerHTML="I am too lazy";
The rest and to put it all together is now up to you :) Have fun to study :)
Try that if you want to display the sum at the html element:
document.getElementById("sum").innerHTML = sum;
But a more precise Question would help!
There is no int type for form inputs in HTML you can learn here about input types: HTML form input types
<form id="frm1" >
Number1: <input type="number" name="number" id="number1"><br>
Number2: <input type="number" name="number" id="number2"><br>
Modifiers: <input type="text" name="modifier" id="modifier"><br>
<input type="button" onclick="math()" value="Submit">
</form>
<p id = "sum"></p>
<script type="text/javascript">
function math() {
var numb1 = parseInt(document.getElementById("number1").value);
var numb2 = parseInt(document.getElementById("number2").value);
var mod = document.getElementById("modifier").value;
if(mod == '+'){
var sum = numb1 + numb2;
}else if(mod == '-'){
var sum = numb1 - numb2;
}else if(mod == '*'){
var sum = numb1 * numb2;
}
if(sum === undefined){
alert('invalid inputs');
return false;
}else{
document.getElementById("sum").innerHTML = sum;
}
return true;
}
To retrieve inputs values properly use value rather then innerHtml.
Retrieved values are strings so you need to parse them to numbers (with parseInt) before using them in math.
function math() {
const numb = document.getElementById("number").value;
const mod = document.getElementById("modifier").value;
sum = document.getElementById("sum").innerText = parseInt(numb) + parseInt(mod);
}

How to display rounded values in a form and show on focus the original values?

I have numeric values with many decimal places and the precision is required for other functions. I want to present the values in a form, so the user can change the values if necessary.
To increase the readability, I want to display the values rounded to 2 decimal places, but if the user clicks on an input field, the complete value should be presented. By doing this, the user can see the real value and adjust them better.
Example:
HTML
<button id="myBtn" onclick="fillForm()">Try it</button>
<form id="myForm" >
<fieldset>
<input type="text" id="myInput1" onchange="myFunction()" >
</fieldset>
</form>
JavasSript
<script>
//Example values that should be presented
var x = 3.14159265359;
function fillForm(){
document.getElementbyId("myInput1").value = x;
}
function myFunction(){
x = document.getElementbyId("myInput1");
}
</script>
The form input value should be " 3.14 " and if the user clicks in the field, the displayed value should be 3.14159265359.
Now the user can change the value and the new value has to be saved.
Because this is for a local 1 page website with no guaranty of internet connection, it would be an asset but not a requirement, to do it without an external script (jquery …).
you can use focus and blur event to mask/unmask you float, then simply store the original value in a data param, so you can use the same function to all input in your form ;)
function fillForm(inputId, val)
{
var element = document.querySelector('#'+inputId);
element.value = val;
mask(element);
}
function mask(element) {
element.setAttribute('data-unmasked',element.value);
element.value = parseFloat(element.value).toFixed(2);
}
function unmask(element) {
element.value = element.getAttribute('data-unmasked') || '';
}
<button onclick="fillForm('myInput1',3.156788)">Fill!</button>
<form id="myForm" >
<fieldset>
<input type="text" id="myInput1" onblur="mask(this)" onfocus="unmask(this)" >
</fieldset>
</form>
Edit: added "fillForm()" :)
Just use .toFixed(). It accepts one argument, an integer, and will display that many decimal points. Since Javascript primitives are immutable, your x variable will remain the same value. (also when getting/setting the value of an input use the .value property
function fillForm(){
document.getElementbyId("myInput1").value = x.toFixed(2);
}
If you need to save it you can store it in a new value
var displayX = x.toFixed(2)
Here is my solution. I hope you have other suggestions.
HTML
<form id="myForm" >
<fieldset>
<input type="text" id="myInput1" >
</fieldset>
</form>
<button id="myBtn" onclick="fill_form()">fill form</button>
JavasSript
<script>
var apple_pi = 10.574148541;
var id_form = document.getElementById("myForm");
//Event listener for form
id _form.addEventListener("focus", copy_input_placeh_to_val, true);
id _form.addEventListener("blur", round_input_2decimal, true);
id _form.addEventListener("change", copy_input_val_to_placeh, true);
// Replace input value with input placeholder value
function copy_input_placeh_to_val(event) {
event.target.value = event.target.placeholder;
}
// Rounds calling elemet value to 2 decimal places
function round_input_2decimal(event) {
var val = event.target.value
event.target.value = Number(val).toFixed(2);
}
// Replace input placeholder value with input value
function copy_input_val_to_placeh(event) {
event.target.placeholder = event.target.value;
}
// Fills input elements with value and placeholder value.
// While call of function input_id_str has to be a string ->
//fill_input_val_placeh("id", value) ;
function fill_input_val_placeh (input_id_str, val) {
var element_id = document.getElementById(input_id_str);
element_id.placeholder = val;
element_id.value = val.toFixed(2);
}
// Writes a value to a form input
function fill_form(){
fill_input_val_placeh("myInput1", apple_pi);
}
</script>
Here is an running example
https://www.w3schools.com/code/tryit.asp?filename=FLDAGSRT113G
Here is solution, I used focus and blur listeners without using jQuery.
I added an attribute to input named realData
document.getElementById("myInput1").addEventListener("focus", function() {
var realData = document.getElementById("myInput1").getAttribute("realData");
document.getElementById("myInput1").value = realData;
});
document.getElementById("myInput1").addEventListener("blur", function() {
var realData = Number(document.getElementById("myInput1").getAttribute("realData"));
document.getElementById("myInput1").value = realData.toFixed(2);
});
function fillForm(value) {
document.getElementById("myInput1").value = value.toFixed(2);
document.getElementById("myInput1").setAttribute("realData", value);
}
var x = 3.14159265359;
fillForm(x);
<button id="myBtn" onclick="fillForm()">Try it</button>
<form id="myForm" >
<fieldset>
<input type="text" id="myInput1" realData="" onchange="myFunction()" >
</fieldset>
</form>
jsfiddle : https://jsfiddle.net/mns0gp6L/1/
Actually there are some problems that needs to be fixed in your code:
You are redeclaring the x variable inside your myFunction function with var x =..., you just need to refer the already declared x without the var keyword.
Instead of using document.getElementById() in myFunction, pass this as a param in onchange="myFunction(this)" and get its value in the function.
Use parseFloat() to parse the value of your input to a float, and use .toFixed(2) to display it as 3.14.
This is the working code:
var x = 3.14159265359;
function fillForm() {
document.getElementById("myInput1").value = x.toFixed(2);
}
function myFunction(input) {
x = parseFloat(input.value);
}
To display the original number when you click on the input you need to use the onfocus event, take a look at the Demo.
Demo:
var x = 3.14159265359;
function fillForm() {
document.getElementById("myInput1").value = x.toFixed(2);
}
function focusIt(input){
input.value = x;
}
function myFunction(input) {
x = parseFloat(input.value);
}
<button id="myBtn" onclick="fillForm()">Try it</button>
<form id="myForm">
<fieldset>
<input type="text" id="myInput1" onchange="myFunction(this)" onfocus="focusIt(this)">
</fieldset>
</form>

I cant change value of Input

I want to create Javascript simple calculator, I want to change <input> tag's value on click, I used this
document.getElementById('input').value = "1"
But it types once 1 so I can't type 11 or 111. What is problem? Can you help me?
I don't know if that's the correct answer as OP's code wasn't provided...
var el = document.getElementById('input');
el.value = 1;
var button = document.getElementById('button')
button.onclick = function() {
el.value = parseInt(el.value) + 1;
}
<input id="input" type="text" name="name" value="">
<button id="button">Add 1!</button>
On button click, the function will retrieve the value from the input box, convert it to integer and then add 1.
If that's not the answer you were looking for, let me know.
EDIT: Just to clarify.
I have used parseInt() to convert to integer. This way if el.value = 1
The result will be 2. However if I don't use parseInt() I would get a concatenation instead of an operation and el.value + 1 would do 11, el.value being a string.
First you have to get the value of that field as
var val = document.getElementById('input').value;
Then Add a value and show in it as
document.getElementById('input').value = val + 1;
Here is a complete Running code:
function function_name (argument) {
var val = document.getElementById('input').value;
document.getElementById('input').value = val + 1;
}
<input id="input" type="text" name="name" value="">
<button id="button" onclick="function_name()">Press 1!</button>

How do I prevent invalid characters from being entered into a form?

For example, if I have a form and I don't want the user to enter numbers in it and I validate it with a function containing a regular expression, how do I prevent the invalid character the user entered (in this example, a digit) from showing up in the text form if it fails the regular expression test?
This is the function I tried and the select list I tried it on (in other words, this isn't the whole program). I tried returning false to the onkeypress event handler but what the user enters into the textbox still goes through.
function noNumbers(answer) { //returns false and displays an alert if the answer contains numbers
if (/[\d]+/.test(answer)) { // if there are numbers
window.alert("You can not enter numbers in this field");
return false;
}
}
<form action="get" enctype="application/x-www-form-urlencoded">
<select id="questions" name="questions">
<option value="no_numbers">What is the name of the city where you were born?</option>
<option value="no_letters">What is your phone number?</option>
<option value="no_numbers">What is the name of your favorite pet?</option>
<option value="no_letters">What is your social security number?</option>
<option value="no_numbers">What is your mother's maiden name?</option>
</select>
<p><input type="text" name="answer" onkeypress="validateAnswer();" /></p>
</form>
This validation works great for stripping invalid characters on the fly as you enter them in the relevant field. Example:
<form id="form1" name="form1" method="post">
Email:
<input type="text" name="email" id="email" onkeyup='res(this, emailaddr);' ; </form>
<script>
var phone = "()-+ 0123456789";
var numb = "0123456789";
var alpha = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ #-'.,";
var alphanumb = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ #-.'1234567890!?,:;£$%&*()";
var alphaname = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ ,-.1234567890";
var emailaddr = "0123456789#._abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";
function res(t, v) {
var w = "";
for (i = 0; i < t.value.length; i++) {
x = t.value.charAt(i);
if (v.indexOf(x, 0) != -1)
w += x;
}
t.value = w;
}
</script>
Then you would simply change the second value of the javascript call to the type of data you want entered in the field using the variables that are defined within the code.
This is the function you are looking for
function validateAnswer(src) {
var questions = document.getElementById("questions");
var rule = questions.options[questions.selectedIndex].value;
if(rule=="no_numbers") src.value = src.value.replace(/\d/g, '');
if(rule=="no_letters") src.value = src.value.replace(/\w/g, '');
}
just send the input field reference to the function and set it to onkeyup event instead:
<input type="text" name="answer" onkeyup="validateAnswer(this);" />
you should also hook the onchange event of the selectbox to reset the value of the input box. I suggest you also consider the HTML5 pattern attribute. See
the fiddle
patern attribute support
workaround for unsupported browsers
You get the key being pressed from the event object passed to the handler.
input type="text" name="answer" onkeypress="validateAnswer(this, event);" />
function validateAnswer(element, event) {
if (event.charCode) {
if (/\d/.test(String.fromCharCode(event.charCode))) {
window.alert("You can not enter numbers in this field");
return false;
}
}
}
Googling for "onkeypress event" finds many examples of this.
Make your life simpler by adding an extra parameter to your validateAnswer function like this:
<input type="text" id="answer" name="answer" onkeyup="validateAnswer(this);" />
Then you can define your validateAnswer like this:
function validateAnswer(elem){
elem.value = elem.value.replace(/[^\d]/g, '');
}
Here an example: http://jsbin.com/iwiduq/1/

Categories

Resources