get input value in typescript - javascript

I had 2 input value, I need to do validation on first input value which is credit card number input, get input value on ts file and check validation on API while user still typing on second input, example of my first input value: 4444 4444 4444 4444, so i need to use subString() to get first 6 number before do validation,
this is what I had tried;
html file
<div>
<input
(keypress)="numberOnly($event)"
class="input"
type="text"
(keyup)="onKey($event)"
[(ngModel)]="creditCardNo"
/>
</div>
<div>
<input
class="input"
type="text"
[(ngModel)]="cardHolderName"
/>
</div>
ts file
onKey(event) {
this.creditCardNo = event.target.value;
const test = this.creditCardNo
.replace(/\s/g, '')
.toString()
.substr(0, 6);
this.paymentService.getCreditCardDetail('JPJSMN', test).subscribe(res => {
if (!res) {
return;
}
console.log(res);
});
}
using (keyup)="onKey($event)" to get value change, and do a validation on ts file based on response I get, however I notice if Im using (keyup)="onKey($event)", it doesnt detect copy and paste, and it keep requesting API,if there are better practice to solve this ?

You can opt to create a custom 'digitOnly' Angular directive.
A great guide on how to do this can be found here:
https://codeburst.io/digit-only-directive-in-angular-3db8a94d80c3
The directive shown in the tutorial address issues such as copy and paste.

If you just want to get the model updated when the user pasts something the same way as editing the value, you can just use
(ngModelChange)="pasteEvent($event)"
<div>
<input
(keypress)="numberOnly($event)"
class="input"
type="text"
(ngModelChange)="pasteEventcreditCardNo(creditCardNo)"
[(ngModel)]="creditCardNo"
/>
</div>
<div>
<input
class="input"
type="text"
(ngModelChange)="pasteEventcardHolderName(cardHolderName)"
[(ngModel)]="cardHolderName"
/>
</div>

Related

How to properly control data input?

There is a task to supervise input in . It is necessary to give the ability to enter only strings of numbers ([0-9]) into the entity input. At the same time, if something else is entered, then do not overwrite value and do not display incorrect input in the input. I can't find a solution for my case. Validity check ( target.validity.valid ) didn't work either because I have control over the minimum and maximum lengths. At the same time, I have a universal function for several inputs, but only the entity needs to be checked. Please tell me how to correctly implement the check for input [0-9] and so that nothing else can be entered.
The examples that are on the resource are not suitable because they do not take into account the control of the minimum-maximum length
Below is a shortened code example
const [inputState, setInputState] = useState({title : "", entity: ""})
const handleChangeInputValue = (event) => {
const { target } = event;
const { name, value } = target;
// Need to check for numbers
setInputState({ ...inputState, [name]: value });
};
<input
required
minLength={5}
type="text"
placeholder="Enter name"
name="title"
value={inputState.title}
onChange={handleChangeInputValue}
/>
<input
required
minLength={13}
maxLength={15}
type="text"
placeholder="Enter entity"
name="entity"
value={inputState.entity}
onChange={handleChangeInputValue}
/>
you can use HTML 5
<input type="number" name="someid" />
This will work only in HTML5 complaint browser. Make sure your html document's doctype is:
<!DOCTYPE html>
if(name==='entity' && !value.match(/^\d+$/)) {
return
}

Search Input Is Cancelling Text as one types in vuejs

I have an issue with search input box where, as I type in the search, the last typed text get cancelled.
<input
class="navbar-searchbar__text-field"
type="search"
:value="searchQuery"
name="query"
placeholder="Search"
autocomplete="off"
#keyup="collectSearchQuery($event.target.value)"
/>
This is the method
async collectSearchQuery(searchQuery) {
this.searchQuery = searchQuery;
await this.handleSearch(searchQuery);
this.searchHidden = true;
},
I don't know why that issue is happening. kindly help if you have any solution
I guess it is because you assign the new value to this.searchQuery which is just one key instead of adding it to this.searchQuery string.

How can I make a search bar with an <input> button open a domain if entered?

I currently have this code for a custom DuckDuckGo search bar:
<form action="https://duckduckgo.com/" method="get" id="ddg-search">
<div class="div-block-4">
<input autofocus="true" class="text-field-3 hero-search-bar w-input" data-name="q" id="field-3" maxlength="256" name="q" placeholder="Search DuckDuckGo" type="text">
</div>
</form>
It automatically opens the URL https://duckduckgo.com/?q={{SEARCH}} when you enter text in the box and press the enter key.
How could I make this bar go to a domain if one is entered? Optimally, it wouldn't validate the domain, just if it sees a string in the pattern xxxx.* with no spaces, it would open that page in a new tab.
Thank you for any help!
One way to solve it is by capturing the submit event of the form, analyze the input value and when it is a domain, open a new window with the domain and cancel the submit by returning false. In case of not being a valid domain, let the form proceed as usual by returning true.
Your html:
<form action="https://duckduckgo.com/" method="get" onsubmit="return decideWhatToDo()" id="ddg-search">
<div class="div-block-4">
<input autofocus="true" class="text-field-3 hero-search-bar w-input" data-name="q" id="field-3" maxlength="256" name="q" placeholder="Search DuckDuckGo" type="text">
</div>
<input type="submit" />
</form>
Your javascript:
function decideWhatToDo() {
let inputValue = document.getElementById('field-3').value;
if (isDomain(inputValue)) {
// the form won't be sent and a new window will open requesting the domain
if (!startsWithProtocol(inputValue)) {
inputValue = 'http://' + inputValue;
}
window.open(inputValue, '_blank');
return false;
}
// Proceed to send the form as usual
return true;
}
function startsWithProtocol(value) {
return /^((https?|ftp|smtp):\/\/)/.test(value);
}
function isDomain(value) {
return /^((https?|ftp|smtp):\/\/)?(www.)?[a-z0-9]+\.[a-z]+(\/[a-zA-Z0-9#]+\/?)*$/.test(value);
}
So one way to handle it is to use an if condition and check the string against a RegExp that recognizes domain names.
Here's a nifty one you can use:
/[a-zA-Z0-9][a-zA-Z0-9-]{1,61}[a-zA-Z0-9](?:\.[a-zA-Z]{2,})+/
I assume you don't need help getting the value from your text field or the actual redirection. However, if you needed more help, comment below and I'll post a more complete answer. The code below should help you get to where you want:
var domainRegExp = /[a-zA-Z0-9][a-zA-Z0-9-]{1,61}[a-zA-Z0-9](?:\.[a-zA-Z]{2,})+/
var pass = domainRegExp.test('test.com')
var fail = domainRegExp.test('test')
console.log(pass, 'pass')
console.log(fail, 'fail')
So as you can see the value inside the 'pass' variable is true, and 'fail' is false.

angucomplete-alto auto populate based in other input

i have 2 autocomplete select box with a particular feature, basically in the first autocomplate i have a input that accepts a code, and in this code is related with a label. So basically when i select the code of the first input it autofills the second input with the selected object related. But in the second input haves also a autocomplete feature since the code is not a required field.
Bit there is a detail in the first input (code), the code is always 2 charecters, not more or less, but the user can insert more than 2 charecters.
In my code it works fine, but there is a detail, the input 1 (code) it autoselects the object and the first input removes the extra charecters of the user, but i need to have them there. How do i customize it?
Module that im using for autocomplete is this one Angucomplete-Alt
My code is:
<div angucomplete-alt
id="flight_code"
placeholder="flight code"
pause="100"
selected-object="claim.flight_details.flight_code"
local-data="airlines"
local-search="localSearch"
search-fields="code_airline"
title-field="code_airline"
minlength="2"
input-name="operating_airline"
input-class="form-control form-control-small"
match-class="highlight"
field-required="false">
<div angucomplete-alt
local-search="localSearch"
id="operating_airline"
placeholder="Search airline"
pause="100"
selected-object="claim.flight_details.operating_airline"
local-data="airlines"
search-fields="label"
title-field="label"
minlength="1"
input-name="operating_airline"
input-class="form-control form-control-small"
match-class="highlight"
field-required="true"
initial-value="claim.flight_details.flight_code.originalObject">
</div>
Controller:
$scope.localSearch = function(str, code_airline) {
var matches = [];
code_airline.forEach(function(code) {
if(str.toString().substring(0, 2).toUpperCase() === code.code_airline){
console.log("I found him!!");
matches.push(code);
}
});
return matches;
};
I resolved my issue, in made de first input code to a normal input a use the directive ngChange to detect the chareceters and than create a promise to search for the object and than inserted in the angcomplete input using the initialValue:
controller:
$scope.automaticFill = function(){
var str = $scope.claim.flight_details.flight_code;
if(str.toString().length === 2){
console.log("Im changed");
$http.get('data/airlines-companies.json').then(function(response){
var airlines = response.data;
airlines.forEach(function(code) {
if(code.code_airline === str.toString().toUpperCase())
$scope.test = code;
});
});
}
};
Html:
<input type="text"
class="form-control"
ng-model="claim.flight_details.flight_code"
name="flight_code"
id="flight_code"
ng-change="automaticFill()">
<div angucomplete-alt
local-search="tap"
id="operating_airline"
placeholder="Search airline"
pause="100"
selected-object="claim.flight_details.operating_airline"
local-data="airlines"
search-fields="label"
title-field="label"
minlength="1"
input-name="operating_airline"
input-class="form-control form-control-small"
match-class="highlight"
field-required="true"
initial-value="test">

How to store tags from Bootstrap Tags Input field into my collection...?

I'm using the ajduke:bootstrap-tagsinput` package and I'm trying to store the array in:
$('#dealTags').tagsinput('items')
in my deals collection, but the value of:
$(e.target).find('[name=dealTags]').val()
comes back as undefined. I'm a newbie to Meteor and Javascript, so sorry if this is a dumb question. Here is the form field:
<div class ="controls">
<input id="dealTags" type="text" class="form-control" value="" placeholder="Add some tags..." data-role="tagsinput">
</div>
And here I try to insert the data to my collection in the Template
var deal = {
dealTitle: $(e.target).find('[name=dealTitle]').val(),
venueName: $(e.target).find('[name=venueName]').val(),
when: $(e.target).find('[name=when]').val(),
dealTags: $(e.target).find('[name=dealTags]').val()
};
And my collection method doing the actual writing to DB
Meteor.methods({
dealInsert: function(dealAttributes) {
check(Meteor.userId(), String);
check(dealAttributes, {
dealTitle: String,
venueName: String,
when: String,
dealTags: String
});
Thanks!
I think you need to use the select element instead of input to have val() return an array. (see documentation)
<div class ="controls">
<select multiple id="dealTags" type="text" class="form-control" value="" placeholder="Add some tags..." data-role="tagsinput" />
</div>
Another solution is to keep using the input element, but call .tagsinput('items') instead of val()
var deal = {
dealTitle: $(e.target).find('[name=dealTitle]').val(),
venueName: $(e.target).find('[name=venueName]').val(),
when: $(e.target).find('[name=when]').val(),
dealTags: $(e.target).find('[name=dealTags]').tagsinput('items')
};

Categories