clearing a form dropdown using just javascript - javascript

I am creating a basic todo - list and the input field seems to save all the data entered as a drop down list and I am unable to fix it.I have tried using the.reset() fn and also other options shown here like using val("") or val(0) and nothing seems to work.So can anyone suggest how I can fix this. I had tried the return fn and the val function as well but it still wouldn't work.Thanks in advance.
const addForm = document.querySelector('.add');
const todolst = document.querySelector('.todolst');
const deletelst = document.querySelector('.delete')
const task = addForm.add.value.trim();
const newTemplate = task => {
const html =
<li class="list-group-item d-flex justify-content-between align-items-center"><span>${task}</span><i class="far fa-trash-alt delete"></i></li>
todolst.innerHTML += html
}
// to add a tag
addForm.addEventListener('Enter', e => {
e.preventDefault();
if (task.length) {
newTemplate(task);
addForm.val(0);
}
});
[enter image description here][1]
[1]: https://i.stack.imgur.com/gIdeL.png

Well, I managed to have found a solution which was by just clearing the cache on my browser. Although not the one I was expecting but seemed to have done the job. I tried the reset() and the clear() options which seemed have cleared the text just entered but not the previous ones that got stored onto the drop-down box.

Related

draft-js-link-detection-plugin save to html with link?

So, what I'm trying to do is use this draftjs plugin to save text already formatted as HTML so I can insert it as HTML in my div to have clickable links, I already saw these examples and guides and tried to follow them, but I can't figure out what I'm doing wrong, examples and documentation used:
oficial documentation for plugin
Code sandBox with code example
-> These two I think were the really helpful ones and my base to write my code:
example of front with working implementation
The code behind that implementation
OBS: the problem is they don't really show how they save the formatted HTML state to pass in the div
After reading the documentation I coded this (dummies for show):
Some background to understand the code below
contentPost // useState passed in the <Editor>
const [contentPost, setContentPost] = useState(EditorState.createEmpty())
The component USAGE
<TextEditor
editorState={contentPost}
setEditorState={setContentPost}
hasError={hasError}
/>
component DEFINITION
function TextEditor({
editorState,
setEditorState
}: {
editorState: any
setEditorState: any
}) {
const linkifyPlugin = createLinkifyPlugin()
const plugins = [linkifyPlugin]
return (
<div>
<Editor
plugins={plugins}
editorState={editorState}
onEditorStateChange={setEditorState}
/>
</div>
)
}
How I save the values:
const payload = {
content: contentPost.getCurrentContent().getPlainText(),
contentFormatted: contentHtml,
}
handleCreatePost({ ...payload })
How I make the variable in which I save the HTML
const contentHtml = React.useMemo(() => {
const currentContent = contentPost.getCurrentContent()
return stateToHTML(currentContent)
}, [contentPost])
Any help would be appreciated!

Why does e.target return undefined when trying to change an inputs value?

I know this question has been asked before but the solutions posted there didn't correct my issue.
So I'm working with React and have a component. Everything else works fine, but now I'm trying to use a few useStates to get dynamic information as I intend to connect to an API/server further down the line.
I'm also using styled-components, which is why you'll see odd tag names. These work fine because I worked on them first and have them visible when I run npm start
The issue is that when I try to type something other than 0 in to this input, it refuses to update and gives me e.target is undefined
Here's where my error is occuring (on the e.target.value):
<InnerWrap flexColumn>
<AttributeFrame>
<EngravingInput
type= "text"
placeholder="20"
inputWidth="50px"
name="charSTR"
value={charAttributes.charSTR}
onChange={(e) => handle_attr_Change(e.target.value)}/>
<Spacer />
<>{((charAttributes.charSTR)-10)/2}</>
<>STR</>
</AttributeFrame>
</InnerWrap>
Here's the useState (Recently learned I could put multiple fields in a single useState):
const [charAttributes, set_CharAttributes] = useState(
{
charSTR: 0,
charSTRmod: 0
});
Then, here's the function that's supposed to fire on the onChange part of my element input:
//This is in my component definition, before the return block
const handle_attr_Change = (e) => {
const value = e.target.value;
set_CharAttributes(
{
...charAttributes,
[e.target.name]: value
}
);
The whole idea is that the charSTRmod value is supposed to update whenever the user types in a number. It's meant to calculate the attribute bonus for a strength attribute from DnD 5e.
Screengrab of the part:
Please could someone tell me what I did wrong?
You can pass the event itself e into handle_attr_Change instead of unpacking it:
<EngravingInput
...
onChange={handle_attr_Change}
/>
...
const handle_attr_Change = (e) => {
set_CharAttributes(
{
...charAttributes,
[e.target.name]: e.target.value
}
);
...

Uncaught TypeError: Cannot read property 'object' of undefined

So this is my first ever question and I'm new here. So I'm attending course on Udemy for javascript and this is my problem:
I define a parameter(object) before executing a function but the browser throws an error on it.
So I console.log it before executing function and it returns the data like it suppose to be,
but when using in a function it errors out that it's undefined.
After losing hope at trying to find mistake I even copy paste code from the original program from the course but it still throws mistake! So I think it's not a problem with the code but something else. Maybe you know what? Here is the code anyway.
const controlList = () => {
// Create a new list IF there in none yet
if (!state.list) state.list = new List();
// Add each ingredient to the list and UI
console.log(state.recipe.ingredients);
state.recipe.ingredients.forEach(el => {
const item = state.list.addItem(el.count, el.unit, el.ingredient);
console.log(state.list.items);
console.log(item); // HERE IS OK
listView.renderItem(item); // THIS LINE THROWS MISTAKE
});
}
export const renderItem = item => {
const markup = `
<li class="shopping__item" data-itemid=${item.id}>
<div class="shopping__count">
<input type="number" value="${item.count}" step="${item.count}" class="shopping__count-value">
<p>${item.unit}</p>
</div>
<p class="shopping__description">${item.ingredient}</p>
<button class="shopping__delete btn-tiny">
<svg>
<use href="img/icons.svg#icon-circle-with-cross"></use>
</svg>
</button>
</li>
`;
elements.shopping.insertAdjacentHTML('beforeend', markup);
};
// controlList() is called in the event listener
here
elements.recipe.addEventListener('click', e => {
if(e.target.matches('.btn-decrease, .btn-decrease *')) {
// Decrrease button is clicked
if (state.recipe.servings > 1) {
state.recipe.updateServings('dec');
recipeView.updateServingsIngredients(state.recipe);
}
} else if (e.target.matches('.btn-increase, .btn-increase *')) {
// Increase button is clicked
state.recipe.updateServings('inc');
recipeView.updateServingsIngredients(state.recipe);
} else if (e.target.matches('.recipe__btn--add, .recipe__btn--add *')) {
// Add ingredients to shopping list
controlList(); <---------------- HERE
}
});
Holy molly guakamolly I found whats wrong.
Turn out while importing functions from another file I didn't import correctly...
(I mean everything *)

How to generate an array for each input value from textBox in reactJs

I have a textBox which will allow me to enter the building name and after I click on 'Add Building' button, it takes the value and passes it to the next page.So, in my screenshot below, the values 'AbsBuildingOne' and 'AbsBuildingTwo' comes from the textBox input.So, currently I am able to pass a single value from the textBox to the next page, but I am not able to understand if I want to enter the second building how do I save the previous value in this page and add the second value below it. I guess I have to do it with arrays, but I am not able to figure it out how to proceed.
Currently, my code looks as shown below for passing the single value.I have added a state:
this.state = {
textBoxValue: '',
};
So, in my textBox the onUpdateHandler function looks like this:
onClickAddBuildingTextBoxHandler = (inputData) => {
this.setState({ textBoxValue: inputData.value});
}
My textBox component looks like this.Its a custom textBox designed for the project:
<SceTextBox
placeholder='Enter Building Name'
id='AddBuilding'
type='buildingName'
maxLength='40'
onTextUpdatedHandler={this.onClickAddBuildingTextBoxHandler.bind(this)}
forceValidate={this.state.forceValidate}
validator={app.appUtil.validator}
isError={this.state.textBoxEmptyError}
errorMsg={this.errorMessage}
/>
So, currently I am passing the value of this.state.textBoxValue to my next component where the building names are displayed.
So, how do I proceed with multiple values and how do I save all the building names? Also, I have to delete the building name when i click on close icon. So do I have to work with push/pop in array? Someone please guide me with this.
Edit 1:
My new state looks like this:
this.state = {
buildingNames: {
[id++]: ''
}
};
Both my functions are:
onClickAddBuildingButtonHandler = () => {
const { buildingNames } = this.state;
this.setState({
buildingNames: {
...buildingNames,
[id++]:''
}
});
if (!this.state.selectedOptions) {
this.setState({ isRadioEmptyError: true });
if (!this.state.buildingNames.id) {
this.setState({ textBoxEmptyError: true });
}
}
if (this.state.selectedOptions && this.state.buildingNames) {
this.props.navigateToAddBuilding(this.state.buildingNames);
}
}
onClickAddBuildingTextBoxHandler = (inputData) => {
const { buildingNames } = this.state;
this.setState({
buildingNames:{
...buildingNames,
[inputData.id] : inputData.value
}
});
}
To get an array of values from a textarea you can use the this.state.value.split('\n') to separate split the string on each new line producing an array for you.
Below is a very simple example demonstrating its effectiveness. Just type in the textarea and look at the console. Once you make a new line you'll see a second element appears in the array.
function handleKeyUp() {
const textarea = document.getElementById('my-ta');
console.log(textarea.value.split('\n'));
}
<textarea id='my-ta' onKeyUp='handleKeyUp()'></textarea>
EDIT #1:
Here is a Code Sandbox Example 1 demonstrating how it is done. Type in the textarea, make a new line and type some more and then hit the toggle button. You'll see the values displayed and if you toggle back they're in the textarea still.
EDIT #2:
So here is another example of how something can be done. This will show you how to add an item to a list. Code Sandbox Example 2
I'm going to leave it up to you to combine the two methods.

Chart.js & Angular 2 - ng2-charts Custom on Click Event

I am trying to implement ng2-charts in my Angular 2 project and I was wondering about creating custom onclick events. Meaning, I want to override the current onclick events on the carts to do some custom functions (redirect to a page, have a modal show up, etc).
Is there a simple way to do this? Is it built in at all?
Any insight would be appreciated it
I found this solution at https://github.com/valor-software/ng2-charts/issues/489
public chartClicked(e: any): void {
if (e.active.length > 0) {
const chart = e.active[0]._chart;
const activePoints = chart.getElementAtEvent(e.event);
if ( activePoints.length > 0) {
// get the internal index of slice in pie chart
const clickedElementIndex = activePoints[0]._index;
const label = chart.data.labels[clickedElementIndex];
// get value by index
const value = chart.data.datasets[0].data[clickedElementIndex];
console.log(clickedElementIndex, label, value)
}
}
}
Try to read DOCS
They have pretty good and understandable explanation of use.
There-are built-in 2 event handlers:
Events
chartClick: fires when click on a chart has occurred, returns information regarding active points and labels
chartHover: fires when mousemove (hover) on a chart has occurred, returns information regarding active points and labels
In code it looks like that:
<base-chart class="chart"
[datasets]="lineChartData"
[labels]="lineChartLabels"
[options]="lineChartOptions"
[colors]="lineChartColours"
[legend]="lineChartLegend"
[chartType]="lineChartType"
(chartHover)="chartHovered($event)"
(chartClick)="chartClicked($event)"></base-chart>
</div>
that chartHovered and chartClicked are your custom functions, which could has another names, and do custom things like showing modal, redirect to url etc.
public chartClicked(e: any): void {
console.log(e);
}
e.active[0]._model and e.active[0]._view contain information about the part of the chart you clicked (i.e. label).
I hope my answer is correct. After much searching for the only solution I found was:
public chartClicked(e:any):void {
if(e.active.length > 0){
var points = [];
var pointSelected = e.active[0]._chart.tooltip._model.caretY;
var legends = e.active[0]._chart.legend.legendItems;
for (var i = 0; i < e.active.length; ++i) {
points.push(e.active[i]._model.y);
}
let position = points.indexOf(pointSelected);
let label = legends[position].text
console.log("Point: "+label)
}}
After checking multiple places, I got it working like this for click event.
HTML:
<div class="chart">
<canvas
baseChart
[data]="pieChartData"
[type]="pieChartType"
[options]="pieChartOptions"
[plugins]="pieChartPlugins"
(chartHover)="chartHovered($event)"
>
</canvas>
</div>
TS:
public chartHovered(e: any): void {
if (e.event.type == "click") {
const clickedIndex = e.active[0]?.index;
console.log("Clicked index=" + clickedIndex);
}
}
Ref

Categories

Resources