Mask the first 2 characters in input form - javascript

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>

Related

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>

Javascript Replace onKeyUp event with a string

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.

How can I convert text typed in an input box to lower case?

I can't figure out how to convert the text typed into a text input box (txtQuestion) into all lower case, i.e. typing "input" or "INpUt" will be read the same and output the same result.
Use toLowerCase() function. Eg: "INPuT".toLowerCase();
exampleFunction = function(){
//First we get the value of input
var oldValue = document.getElementById('input').value;
//Second transform into lowered case
var loweredCase = oldValue.toLowerCase();
//Set the new value of input
document.getElementById('input').value = loweredCase;
}
<input id="input" type="text" onkeyup="exampleFunction()" />
You have to choose the events that you want to watch and then return to the input the same value but lowercase:
function InputLowerCaseCtrl(element, event) {
console.log(element.value)
return element.value = (element.value || '').toLowerCase();
};
InputLowerCaseCtrl.bindTo = ['blur'].join(' ');
document.addEventListener('DOMContentLoaded', function() {
var input = document.querySelector('.input-lowercase');
return input.addEventListener(InputLowerCaseCtrl.bindTo, InputLowerCaseCtrl.bind(this, input));
});
<input class="input-lowercase" type="text" />
You can convert any string input to lowercase using the String.prototype.toLowerCase function
https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/String/toLowerCase
For you example with an input for txtQuestion.
var inputStringLowerCase = inputTxtQuestion.value.toLowerCase();
https://jsfiddle.net/fbkq2po4/

Get variable via user input

I want that the user can see the value of a variable by writing it's name in a textarea, simpliefied:
var money = "300$";
var input = "money"; //user wants to see money variable
alert(input); //This would alert "money"
Is it even possible to output (in this example) "300$"?
Thanks for help!
Instead of seprate variables, use an object as an associative array.
var variables = {
'money': '300$'
}
var input = 'money';
alert(variables[input]);
You can use an object and then define a variable on the go as properties on that object:
var obj = {}, input;
obj.money = "300$";
input = "money";
alert(obj[input]);
obj.anotherMoney = "400$";
input = "anotherMoney";
alert(obj[input]);
A simple way,you can still try this one :
var money = "300$";
var input = "money"; //user wants to see money variable
alert(eval(input)); //This would alert "money"
Here is an answer who use the textarea as asked.
JSFiddle http://jsfiddle.net/7ZHcL/
HTML
<form action="demo.html" id="myForm">
<p>
<label>Variable name:</label>
<textarea id="varWanted" name="varWanted" cols="30" rows="1"></textarea>
</p>
<input type="submit" value="Submit" />
</form>
<div id="result"></div>
JQuery
$(function () {
// Handler for .ready() called.
var variables = {
'money': '300$',
'date_now': new Date()
}
//Detect all textarea's text variation
$("#varWanted").on("propertychange keyup input paste", function () {
//If the text is also a key in 'variables', then it display the value
if ($(this).val() in variables) {
$("#result").html('"' + $(this).val() + '" = ' + variables[$(this).val()]);
} else {
//Otherwise, display a message to inform that the input is not a key
$("#result").html('"' + $(this).val() + '" is not in the "variables" object');
}
})
});

Fill data in input boxes automatically

I have four input boxes. If the user fills the first box and clicks a button then it should autofill the remaining input boxes with the value user input in the first box. Can it be done using javascript? Or I should say prefill the textboxes with the last data entered by the user?
On button click, call this function
function fillValuesInTextBoxes()
{
var text = document.getElementById("firsttextbox").value;
document.getElementById("secondtextbox").value = text;
document.getElementById("thirdtextbox").value = text;
document.getElementById("fourthtextbox").value = text;
}
Yes, it's possible. For example:
<form id="sampleForm">
<input type="text" id="fromInput" />
<input type="text" class="autofiller"/>
<input type="text" class="autofiller"/>
<input type="text" class="autofiller"/>
<input type="button"value="Fill" id="filler" >
<input type="button"value="Fill without jQuery" id="filler2" onClick="fillValuesNoJQuery()">
</form>
with the javascript
function fillValues() {
var value = $("#fromInput").val();
var fields= $(".autofiller");
fields.each(function (i) {
$(this).val(value);
});
}
$("#filler").click(fillValues);
assuming you have jQuery aviable.
You can see it working here: http://jsfiddle.net/ramsesoriginal/yYRkM/
Although I would like to note that you shouldn't include jQuery just for this functionality... if you already have it, it's great, but else just go with a:
fillValuesNoJQuery = function () {
var value = document.getElementById("fromInput").value;
var oForm = document.getElementById("sampleForm");
var i = 0;
while (el = oForm.elements[i++]) if (el.className == 'autofiller') el.value= value ;
}
You can see that in action too: http://jsfiddle.net/ramsesoriginal/yYRkM/
or if input:checkbox
document.getElementById("checkbox-identifier").checked=true; //or ="checked"

Categories

Resources