Change to function Mask - javascript

I have this code below, it works as expected, but I need to pass the id of each one to work.
How can I turn it into a function to use the onKeyPress event:
document.getElementById('inp').addEventListener('input', e => {
const val = e.target.value.replace(/\D/g, '').replace(/^0*/, '').padStart(3, '0')
e.target.value = val.slice(0, -2).replace(/(\d)(?=(\d{3})+(?!\d))/g, '$1.') + ',' + val.slice(-2)
})
I would like to turn to use as a: function Mask(){ // code }
<input asp-for="Frete" name="Frete" onKeyPress="return(Mask(this,'.',',',event))" class="form-control" />
To be able to use the function, so I would need to create one by one by id

Here you go you could use event object like :
document.getElementById('inp1').addEventListener('input', (e) => { Mask(e, 'inp1'); });
document.getElementById('inp2').addEventListener('input', (e) => { Mask(e, 'inp2'); });
document.getElementById('inp3').addEventListener('input', (e) => { Mask(e, 'inp3'); });
function Mask(e, id) {
const target = document.getElementById(id);
const val = target.value.replace(/\D/g, '').replace(/^0*/, '').padStart(3, '0');
target.value = val.slice(0, -2).replace(/(\d)(?=(\d{3})+(?!\d))/g, '$1.') + ',' + val.slice(-2);
}
<input id="inp1">
<input id="inp2">
<input id="inp3">

Related

How to delete All string in input tag using Vue

I want to make password input using type 'text' not 'password.
<input type="text" v-model="form.password" #input="test" />
<input type="hidden" v-model="form.hiddenPassword" />
So I made some methods for my goal. When I put 'a', it be changed to * and 'a' is in hiddenPassword.
test(e) {
if (e.inputType === "deleteContentBackward") {
this.form.hiddenPassword = this.form.hiddenPassword.substr(
0,
this.form.hiddenPassword.length - 1
);
this.form.password = this.masking(this.form.hiddenPassword);
console.log(this.form.hiddenPassword);
} else {
this.form.hiddenPassword =
this.form.hiddenPassword +
this.form.password.substr(this.form.password.length - 1);
this.form.password = this.masking(this.form.hiddenPassword);
}
},
masking(input) {
const lng = input.length;
let maskingResult = "";
maskingResult += "*".repeat(lng);
return maskingResult;
}
This works well. But the unique problem is that when I want to delete all password in input using Ctrl+A and Backspace, the delete works only one letter by my methods.
I don't know how can I catch Ctrl+A or select some range situation by mouse to delete password.
Could you give me some solution for this? THank you so much for reading it.
Your code will work only if you add to the end or delete from the end of the string. Here the method working even if you delete/insert text from/in the middle of the string. It uses selectionStart property to determine where changes occurred.
It also works fine with Delete key. To do it I compare the length of form.hiddenPassword and form.password instead of checking event type.
I use replace standard method for masking. So, no need to create your own method.
...
data: {
form: {
hiddenPassword: '',
password: ''
}
},
methods: {
test: function (e) {
let caretPosition = e.target.selectionStart
let restPartLength = this.form.password.length - e.target.selectionStart
if (this.form.hiddenPassword.length > this.form.password.length) {
this.form.hiddenPassword = this.form.hiddenPassword.substr(0, caretPosition) +
this.form.hiddenPassword.substring(
this.form.hiddenPassword.length-restPartLength,
this.form.hiddenPassword.length
);
} else {
let inserted = this.form.password.replace(/\*/g,'');
this.form.hiddenPassword =
this.form.hiddenPassword.substr(
0,
this.form.hiddenPassword.length - restPartLength) +
inserted +
this.form.hiddenPassword.substring(this.form.hiddenPassword.length-restPartLength, this.form.hiddenPassword.length);
}
this.form.password = this.form.password.replace(/./g,'*');
}
}
...
new Vue({
el: "#test",
data: {
form: {
hiddenPassword: '',
password: ''
}
},
methods: {
test: function (e) {
let caretPosition = e.target.selectionStart
let restPartLength = this.form.password.length - e.target.selectionStart
if (this.form.hiddenPassword.length > this.form.password.length) {
this.form.hiddenPassword = this.form.hiddenPassword.substr(0, caretPosition) +
this.form.hiddenPassword.substring(this.form.hiddenPassword.length-restPartLength, this.form.hiddenPassword.length);
} else {
let inserted = this.form.password.replace(/\*/g,'');
this.form.hiddenPassword =
this.form.hiddenPassword.substr(0, this.form.hiddenPassword.length - restPartLength) +
inserted +
this.form.hiddenPassword.substring(this.form.hiddenPassword.length-restPartLength, this.form.hiddenPassword.length);
}
this.form.password = this.form.password.replace(/./g,'*');
}
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.1.10/vue.min.js"></script>
<div id="test">
<input type="text" v-model="form.password" #input="test" />
{{ form.hiddenPassword }}
</div>

JS/jQ make a URL builder function without duplicate

First I should say, I just want to solve this as logic, not my real code is jQuery or JavaScript, because I learning reactjs I trying to solve this logic with jQ or JS then do it in React. So I don't want a solution like $.param and also don't want to replace last & with something, I looking for to make a URL Builder function, What I trying to do is add URL parameter (Query String) What I tried so far is:
let obj = {}
let array = []
let url = 'http://www.example.com/foo';
function buildUrl(base, key, value) {
var sep = (base.indexOf('?') > -1) ? '&' : '?';
return base + sep + key + '=' + value;
}
$('#btn1').click(function() {
obj = {
name: 'province',
value: 11
}
array.push(obj)
console.log('param 1 added!')
});
$('#btn2').click(function() {
obj = {
name: 'city',
value: 2
}
array.push(obj)
console.log('param 2 added!')
});
$('#build').click(function() {
$.each(array, function(i, v) {
url = buildUrl(url, v.name, v.value);
});
console.log(url)
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<button id="btn1">1. Click this</button>
<kbd>-></kbd>
<button id="btn2">2. Then click this</button>
<kbd>=</kbd>
<button id="build">Make URL</button>
Somehow, it add province twice, I don't how to make this function to avoid duplicate parameters, any idea?
side note: I have many btn to build parameter, so I can't detect value each time!
It is all here and here
let url = new URL('http://www.example.com/foo');
let params = url.searchParams;
document.getElementById("buts").addEventListener('click', (e) => {
const tgt = e.target;
if (tgt.classList.contains('add')) {
params.set(tgt.id, tgt.getAttribute('data-value'));
console.log('param ' + tgt.id + ' added!', params.toString())
}
});
document.getElementById("build").addEventListener('click', (e) => console.log(url));
<div id="buts">
<button class="add" id="province" data-value="11">1. Click this</button>
<kbd>-></kbd>
<button class="add" id="city" data-value="2">2. Then click this</button>
<kbd>=</kbd>
<button id="build">Make URL</button>
</div>

unable to get correct typed input value without reloading page

I can get the input value correctly the first time the handler is called. but it gives me the default value in the html template afterwards and without reloading pages. what might be the prolbem? Thank you!
render: function () {
this.$tpl = $(this.options.template);
this.$tpl.attr('id', this.newrowSelector);
this.newrowSelector = (this.newrowSelector.charAt(0) == '#') ? this.newrowSelector : '#' + this.newrowSelector;
this.$tpl.find(".actions").append(this.options.cancelButton);
this.$tpl.find(".actions").append(this.options.saveButton);
$(this.options.selector).append(this.$tpl);
this.$newrow = $(this.newrowSelector);
this.$element.on('click.tablerow.save', this.options.saveTarget, $.proxy(this.save, this));
},
save: function () {
var formdata = this.getValues();
formdata.zone_id = $.pdns.getZoneId();
this.$element.triggerHandler('saved.tablerow.linline',
[formdata]);
},
getValues: function () {
var formdata = {};
$(this.newrowSelector).find('input,select').each(function () {
var value = $(this).val();
var key = $(this).attr('id');
formdata[key] = value;
});
return formdata;
}
the following is the template:
<tr><td class="name" title="sub domain name"><input id="name" type="text" value="subdomain name"></td><td class="dnstype"><select class="dns-options" id="dnstype"><option>A</option><option>AAAA</option><option>CNAME</option><option>MX</option><option>NS</option></select></td><td class="ttl" ><input id="ttl" type="text" value="600"></td><td class="content"><input id="content" type="text" value="10.10.10.10"></td><td class="actions"></td></tr>

How to clear input field after hitting submit

I have a form, and I would like to clear the input field every time I enter the submit (plus) button.
I have tried using this, it does not work. I may be implementing it in the wrong spot.
document.getElementById('add-item').value='';
My Javascript code is below.
window.addEventListener('load', function(){
// Add event listeners
document.getElementById('add-item').addEventListener('click', addItem, false);
document.querySelector('.todo-list').addEventListener('click', toggleCompleted, false);
document.querySelector('.todo-list').addEventListener('click', removeItem, false);
function toggleCompleted(event) {
console.log('=' + event.target.className);
if(event.target.className.indexOf('todo-item') < 0) {
return;
}
console.log(event.target.className.indexOf('completed'));
if(event.target.className.indexOf('completed') > -1) {
console.log(' ' + event.target.className);
event.target.className = event.target.className.replace(' completed', '');
document.getElementById('add-item').value='';
} else {
console.log('-' + event.target.className);
event.target.className += ' completed';
}
}
function addItem() {
var list = document.querySelector('ul.todo-list');
var newItem = document.getElementById('new-item-text').value;
var newListItem = document.createElement('li');
newListItem.className = 'todo-item';
newListItem.innerHTML = newItem + '<span class="remove"></span>';
list.insertBefore(newListItem, document.querySelector('.todo-new'));
}
function removeItem(event) {
if(event.target.className.indexOf('remove') < 0) {
return;
}
var el = event.target.parentNode;
el.parentNode.removeChild(el);
}
});
This is what you need:
document.getElementById('new-item-text').value = "";
regarding your need, you will need to put it at the end of your addItem()
you can refer this simple code:
<html>
<body>
<input type="text" id="test">
<button onclick="func()">remove</button>
<br/>
Value = <span id="val"></span>
<script>
function func(){
alert("clicked");
document.getElementById('val').innerHTML = document.getElementById('test').value;
document.getElementById('test').value = '';
}
</script>
</body>
</html>
Use form reset method to clear inputs in one go.
document.getElementById("myForm").reset();
You can set your textbox value = '' in submit button.
and you can create a ClearFunction and then you can call it everytime you need it.
function cleartextbox() {
$('#name').val("").focus();
$('#selectgender').val("");
$('#telephone').val("");
}

Display file name from input type file - console.log(fileName) return null

I'm trying to display file name from input type file.
This is my code:
<input id="id_file_field" name="file_field" type="file" style="display:none" />
Here jQuery:
$(document).ready(function () {
$("#upload_file").click(function () {
$("#id_file_field").trigger('click');
var path = $("#id_file_field").val();
var fileName = path.match(/[^\/\\]+$/);
console.log(fileName);
});
});
Why console.log(fileName) return null?
You need to wait for the change event
$(document).ready(function () {
$("#upload_file").click(function () {
$("#id_file_field").trigger('click');
});
$('#id_file_field').change(function () {
var value = this.value;
var fileName = typeof value == 'string' ? value.match(/[^\/\\]+$/)[0] : value[0]
console.log(fileName);
})
});
Demo: Fiddle
You can use following js;
$("#upload_file").click(function () {
$("#id_file_field").trigger('click');
});
$('#id_file_field').change(function () {
var value = $(this).val();
var name = value.split(/[\\/]/);
console.log(name[name.length - 1]);
});
Here is a working fiddle: http://jsfiddle.net/cubuzoa/BKuLT/3/

Categories

Resources