Input format smpte-timecode - html

Whats the best way to set the input format when using smpte-timecode?
<Input
placeholder="In"
autoFocus={true}
onChange={e => this.onChange(e)}
type="time"
step="00.01"
pattern="^(?:(?:([01]?\d|2[0-3]):)?([0-5]?\d):)?([0-5]?\d)$"
style={{fontSize: "16px", width: "100%"}}/>
)}
onChange = (element, frameRate) => {
const { form } = this.props;
const keys = form.getFieldValue('keys');
keys.forEach(function (value) {
var inTc = Timecode(form.getFieldValue('1-in'), 25); // errors
console.log(inTc.toString());
});
This keeps resulting in the following
Error: Timecode string expected as HH:MM:SS:FF or HH:MM:SS;FF

Related

How to set initial value on useRef<HTMLInputElement> - ReactJs + Typescript

I would like to set a number as initial value on useRef<HTMLInputElement>.
I don't need to use useState<number>() because the field is a simple counter.
Here is my typescript code:
const MyComponent = () => {
const productAmountRef = useRef<HTMLInputElement>();
const handleReduceClick = () => {
productAmountRef.current.value -= 1;
}
const handleAddClick = () => {
productAmountRef.current.value += 1;
}
return (
<>
<SomeWrapper>
<ReduceButton onClick={handleReduceClick}/>
<input disabled={true} ref={productAmountRef}/>
<AddButton onClick={handleAddClick}/>
</SomeWrapper>
</>
)
}
For obvious reasons, when the onClick function is triggered, the value is a NaN.
My doubt is, how can I set a Initial Value on useRef<HTMLInputElement>? As I said and as you saw, it need to be a number.
Is this possible?
Set the initial value using the defaultValue attribute:
<input disabled={true} ref={productAmountRef} defaultValue={3} />
Or use useState() and render the number without the use of an input:
const MyComponent = () => {
const [productAmount, setProductAmount] = useState(0);
const handleReduceClick = () => {
setProductAmount(val => val - 1);
}
const handleAddClick = () => {
setProductAmount(val => val + 1);
}
return (
<SomeWrapper>
<ReduceButton onClick={handleReduceClick}/>
<div>{productAmount}</div>
<AddButton onClick={handleAddClick}/>
</SomeWrapper>
)
}

Change the input initial value of controlled component in React

I have this input component
const FOO = props => {
const [inputValue, setInputValue] = useState(
props.editState ? props.initialValue : ""
);
const setSearchQuery = (value) => {
setInputValue(value);
props.onSearch(value);
};
return (
<input
placeholder="Select ..."
onChange={(e) => {
setSearchQuery(e.target.value);
}}
value={inputValue}
/>
)}
I'm using it like this
const BAR = props => {
const [fetchedData, setfetchedData] = useState({
value : "" // to get rid of can't change controlled component from undefined error
});
const params = useParams();
//request here to get fetchedData
return(
<FOO
onSearch={(value) => {
searchSomethingHandler(value);
}}
initialValue={
params.ID
? fetchedData.value
: ""
}
editState={params.ID ? true : false}
/>
)}
I need to set the initial value of the fetched data into the input so the user could see the old value and edit it, if I pass the data (fetchedData) as props it works perfectly,
but if I get the data through API it wont set the value cause it's empty at the first render,
how can I solve this please?
You'll probably want to make use of the useEffect hook to run code when a value updates.
In FOO:
const FOO = props => {
// ...
useEffect(() => {
// This hook runs when props.initialValue changes
setInputValue(props.initialValue);
}, [props.initialValue]);
// ...
};
You can leave BAR the same as before, I think. Though, I would put the request to the API inside a useEffect hook with an empty dependency array so you're not querying it on every render.

pass function to input onChange and then set it in state reactjs?

I just cannot figure out how to do this.
This function works to split the string of the input ID.
function func() {
// Original string
let str = urlInput.value
// Splitting up the string
let array = str.split(".com/");
let joined = array[0]+".com/embed/"+array[1];
document.write(joined);
console.log("function happened")
}
I am trying to pass it through onChange and then set it in state but the function isn't being passed onChange?
{
currentAccount ? (<textarea
placeholder={spotifyLink}
type="url"
id="urlInput"
onChange={e => {{func}; setMessageValue(e.target.value)}}/>) : null
}
What am I doing wrong? How do I pass the function and then setState after the function has split the user input string onChange?
You can make use of controlled components. With this approach, the input value is controlled by a state. It promotes single source of truth, you can read more here.
CODE -
function TextAreaComponent() {
const [messageValue, setMessageValue] = useState('');
const splitString = (str) => {
// Splitting up the string
let array = str.split(".com/");
let joined = array[0]+".com/embed/"+array[1];
return joined;
}
const handleOnChange = (event) => {
const { value } = event.target;
const splittedString = splitString(value);
setMessageValue(splittedString);
}
return (
<textarea
// placeholder={spotifyLink}
// id="urlInput"
type="url"
value={messageValue}
onChange={handleOnChange}
/>
);
}

how to filter data that pulling from backend in angular

I have input where I user can search/type a data and I'm wondering how I can make the user ONLY able to search what was already provided from the backend and forbid them from creating new data.
so in my backend I've "Chart" and "Map" words and I figuring out a way to make the user able to search only this. If I user type other than this and press enter, nothing will happen.
Right now, if the user type other text than this two and press enter, it create a new data and push it to the backend.
I don't want to hard code like this (input == "Chart" || input == "Map") since we will be adding more data in the backend later.
super <= data type like "Chart and Map"
<div>
<input matInput #input [formControl]="tagCtrl" [matAutocomplete]="auto" [matChipInputFor]="chipList"
[matChipInputSeparatorKeyCodes]="separatorKeysCodes" (matChipInputTokenEnd)="add($event,null)">
</div>
<mat-autocomplete #auto="matAutocomplete" (optionSelected)="selected($event)">
<mat-option *ngFor="let tag of filteredSuperTags | async" [value]="tag">
{{tag}}
</mat-option>
</mat-autocomplete>
tagCtrl = new FormControl();
superTags: Tag[] = [];
filteredSuperTags: Observable<String[]>;
allsuperTags: Array<Tag> = [];
allSuperTagNames: Array<String> = new Array<String>();
add(event: MatChipInputEvent, event1: MatAutocompleteSelectedEvent): void {
if (event1 == null) {
const input = event.input;
const value = event.value;
this.tagService.addTag(this._workspace.guid, 'workspace', value).subscribe((tag) => console.log("added", tag));
this.snackbar.open(input.value + " has been added as super tag.", " ", { duration: 2500 });
if ((value || '').trim()) {
if (this.allSuperTagNames.find((f) => f.toUpperCase() === value.toUpperCase()))
{this.superTags.push({ tag: value.trim(), type: TagType.super }); } }
// Reset the input value
if (input) {
input.value = '';
}
this.tagCtrl.setValue(null);
}
else {
const input = event1.option;
const value = event1.option.value;
this.tagService.addTag(this._workspace.guid, 'workspace', value).subscribe((tag) => console.log("added", tag));
this.snackbar.open(input.value + " has been added as super tag.", " ", { duration: 2500 });
if ((value || '').trim()) {
if (this.allSuperTagNames.find((f) => f.toUpperCase() === value.toUpperCase()))
{this.superTags.push({ tag: value.trim(), type: TagType.super }); } }
if (input) {
input.value = '';
}
this.tagCtrl.setValue(null);
}
}
any recommendation or help will be really appreciated.
Your backend was adding the option no matter what because you were calling the service before verifying if the value existed. If its a form, its super weird to call the backend everytime you select something in a typeahead. In my opinion it should be done once when everything is filled properly or on some kind of submit event.
I just moved the service call inside the verification and removed a if that was only used to assign the input and the value but was duplicating about 10 lines. Now you have an if assigning the value and then followed by the content of the previous if.
add(event: MatChipInputEvent, event1: MatAutocompleteSelectedEvent): void {
const input = event.input;
const value = event.value;
if (event1 === null) {
input = event.input;
value = event.value;
else {
input = event1.option;
value = event1.option.value;
}
if ((value || '').trim()) {
if (this.allSuperTagNames.find((f) => f.toUpperCase() === value.toUpperCase()))
{
this.superTags.push({ tag: value.trim(), type: TagType.super });
this.tagService.addTag(this._workspace.guid, 'workspace', value).subscribe((tag) => console.log("added", tag));
this.snackbar.open(input.value + " has been added as super tag.", " ", { duration: 2500 });
}
}
// Reset the input value
if (input) {
input.value = '';
}
this.tagCtrl.setValue(null);
}

HTML Form Concatenate Inputs into One Field (with GET)

Long story short:
<form action="example.com/" method="get">
<input type="hidden" name="q" value="one,two,">
<input type="text" name="q">
</form>
The goal is that, when the user inputs e.g. "three", the website
example.com/?q=one,two,three
is called, instead of example.com/?q=one,two,&q=three.
A solution without JavaScript would be ideal, but I suspect that's not possible.
Thank you so much!
If you don't mind using an array then you can try using this solution
<form action="example.com/" method="GET">
<input type="hidden" name="q[]" value="one">
<input type="hidden" name="q[]" value="two">
<input type="text" name="q[]">
<input type="submit" name="submit">
</form>
this way you will get an array of values on submit then you can handle it on server side. But if you just still want to use your method then Javascript is required. With javascript you can get formdata then append the user input to the form then send it using ajax.
Yes, it's not possible without using Javascript as far I know.
it's better if you handle this at the backend.
But, if you really want to do at the front-end, you can do as follows (With vanilla Javascript).
document.addEventListener("DOMContentLoaded", function(){
let form = document.getElementById('form');
let query = '';
let valueObj = {};
if(form){
form.addEventListener('submit', (e) => {
e.preventDefault();
let exceptinput = ['submit','reset','button','file','image'];
let allElem = e.srcElement;
if(allElem.length > 0){
createValueObj(allElem, valueObj, exceptinput).then(data => {
console.log(data);
query = serialize(data);
window.location = 'http://www.example.com/?' + query;
}).catch(err => {
console.log(err);
})
}
});
}
let serialize = (obj) => {
var str = [];
for (var p in obj)
if (obj.hasOwnProperty(p)) {
str.push(encodeURIComponent(p) + "=" + encodeURIComponent(obj[p]));
}
return str.join("&");
}
let insertValueToObj = (key, value, obj) => {
if(obj[key]){
obj[key] = obj[key]+','+ value;
}else{
obj[key] = value;
}
return obj;
}
let createValueObj = (arr, obj, exceptinput) => {
return new Promise((resolve, reject)=>{
for (let index = 0; index < arr.length; index++) {
let isProperInput = exceptinput.includes(arr[index].type);
if(!isProperInput) {
let key = arr[index].name;
let value = arr[index].value.trim();
obj = insertValueToObj(key, value, obj);
}
if(index == (arr.length -1)){
resolve(obj);
}
}
});
}
});
thanks.