The onClick attribute for a button element created within a variable is not firing.
I tried directly defining the function in the onClick attribute, and simply out-putting to the console, but there is still nothing output to the console, and the button is not working as expected.
I also added a 'disabled={false}' attribute to the button to make sure that was not an issue, but the onClick attribute is still not working as expected.
let display = (<div className ='dtaskhome'>
<h1>Tasks</h1>
<button disabled={false} onClick={newTask} className='btask'>New Task +</button>
<ul className ='ultasks'>{taskItems}</ul>
</div>);
function newTask() {
console.log('point reached');
Tasks.props.state.newTask = true;
}
No error messages related to the onClick attribute are being displayed, and the current code correctly renders the component.
I also added a 'disabled={false}' attribute to the button to make sure
that was not an issue, but the onClick attribute is still not
responsive.
Try implementing the function as a method.
newTaskHandler = (props) => {
console.log('point reached');
props.state.newTask = true;
}
Then try
onClick={this.newTask(this.props)}
Hope this helps you.
try to call the function:
onClick={newTask()}
And if not try to call it with this.
onClick={this.newTask()}
Related
I have a svelte app where
licking a button "Show" sets a show variable to true which shows a input text box and a save button.
Clicking the "Save" button calls a function which sets the show variable to false
Testing shows that clicking Show also triggers the on:click of Save.
Google tells me to add stopPropagation to fix this issue, but it does not fix this issue.
Any hints on what is my mistake?
A repl with my code is available at
https://svelte.dev/repl/592a544ac59a45b385ab153dec7a42f1?version=3.55.1
I forked the repl and made some changes to it
https://svelte.dev/repl/b897aa42e87d4adc8c04b381b5a66692?version=3.55.1
Here is the new code:
<script>
var name = ''
let names=[];
let show=false;
function addName(){
console.log("Clicked");
show=false;
if (name.length > 0){
names.push(name);
console.log(names)
}
}
</script>
<button on:click={()=>(show=true)} > Show
</button>
{#if show}
<input bind:value={name} type="text">
<button on:click={()=> {addName()}}>Save</button>
{/if}
<h1>Hello {name}!</h1>
You shouldn't have a propogation issue because the event listeners are not nested elements https://www.tutorialrepublic.com/javascript-tutorial/javascript-event-propagation.php
Your Save button on:click was setup like
<button on:click={addName()}>Save</button>
This definition is not correct because on:click={addName()} calls the addName function immediately. If you use this syntax you likely need to write it like this
on:click={addName}
Otherwise you can write it like your other on:click with an anonymous function (which is what I did).
on:click={()=> {addName()}}
I am using the ng-multiselect-dropdown package in angular 5 for creating a multi-select dropdown.
I want to do call a function on close or hide of the drop-down component.
like this
closeDropdown : function(){
console.log("dropdown close triggered");
}
According to the documentation you can pass closeDropDownOnSelection value true to close the dropdown whenever the selection is done
ng-multiselect dropdown
Incase of multiple selection you can call (onSelect)="onItemSelect($event)"
for more information check this Demo documentation
You can call the function within (change) event.
ex :
<ng-multiselect-dropdown
(blur)="closeDropdown($event)"
>
</ng-multiselect-dropdown>
To solve the bug identified by satira ( I couldn't comment due to low reputation), ie.
"When the component which has this multi-dropdown opens for the first time or you reload the page and click anywhere outside the dropdown, onDropDownClose() gets called." For me, it didn't happen after the first time. Anyway, i solved it by getting the id of any element on the screen(header, footer or any div) and used docuement.getElementById('element_id').click() on ngAfterViewInit.
ngAfterViewInit() { document.getElementById('header').click(); }
This made sure that no sideeffects take place on my app. I know this is a messy solution but since closeDropdown() of ng-multidropdown doesn't work, this was my only way out.
I had this issue recently and found a solution that works for me using a combination of (ngModelChange) and (click). When using ng-multiselect-dropdown the other normal HTML Element triggers like (blur) and (change) don't work, but the (ngModelChange) does work. Only problem with that is it triggers when being initialized. But I added a boolean variable to the (click) trigger that does seem to work.
Note that this also works to cover the onSelect, onDeSelect, etc
component.ts:
...
dropDownSelect: boolean = false;
dropDownSelection: number;
...
saveFunction(event) {
if(!this.dropDownSelect) return;
...
this.dropDownSelect = false;
}
component.html:
...
<ng-multiselect-dropdown [data]="dataSource" [(ngModel)]="dropDownSelection" [settings]="dropDownSettings" (click)="dropDownSelect = true" (ngModelChange)="saveFunction($event)"></ng-multiselect-dropdown>
...
I tried #misterz's solution but it didn't work. However I modified it and it works perfectly.
The trick:
In addition to (onDropDownClose), listen to a click event;
// this act as a differentiator between other calls(bug) and an intended call
(click)="dropDownSelect = true".
In your component, declare your variable and use it like this:
dropDownSelect = false;
saveFunction($event) {
if (this.dropDownSelect) {
// close the opening to subsequent actions
this.dropDownSelect = false;
// Perform action;
};
}
I would expect that setting the disabled attribute on a react component would block the onClick handler for that element.
<a role="button"
className={`btn btn-block btn-info`}
disabled={!this.state.readyToView}
href={this.state.selectedObjectLink}
onClick={this.handleLink}
>View</a>
but although the element shows a "disabled" attribute it still registers a click event.
Edit: I should clarify - I handle the click event in handleLink, I want to know why the disabled attribute doesn't remove the handler? Sorry for any confusion.
The problem isn't with disabled; it's with the HTML element a. Anchor <a> cannot have a disabled property (what does that even mean?). Just because you've passed CSS to make the element look like a button, doesn't make it a button. It is still an anchor.
The solution would be either to use something else (like button):
<button
role="button"
className={`btn btn-block btn-info`}
disabled={!this.state.readyToView}
onClick={this.handleLink}
>
View
</button>
You can use this.state.selectedObjectLink inside handleLink if you want to redirect to a page
Or use one of the many other suggestions on this page.
Why not just handle this in handleLink?
handleLink () {
if (!this.state.readyToView) return
// ...
}
If you really want to bind/remove the handler dynamically, you can do something like this:
const clickHandler = this.state.readyToView ? this.handleLink : null
...
<a role="button"
...
...
onClick={clickHandler}
>View</a>
You can add a condition in your click handler, something like this
<a role="button"
className={`btn btn-block btn-info`}
disabled={!this.state.readyToView}
onClick={this.state.readyToView && this.handleLink}
>
View
</a>
jsfiddle
If you are using react version 16 and up
on onClick don't call the method directly use () => method instead like this
const handleRemoveBtnClick = () => {
...
}
<button ...onClick={() => handleRemoveBtnClick} />
Another trick to disable the click to any components is to use useState with boolean value either true to disable or false to resume the click functionality
example
export default const ElementComponent() =>{
//set the initial value of disable click to false
const [disableClick,setDisableClick] = useState(false)
const anotherFunction =() =>{
console.log("I've been run")
}
const handleClick()=>{
//if disableClick is false then run this if block, else don't do anything
if(!disableClick){
anotherFunction()
}
}
return(
<img src="..." onClick={handleClick}/>
)
}
the good thing about this is that we can pass the function as a props to another components and we can run it there, we can even let's say disable a click for let's say 1 second using setTimeout function, there are tons of way you can use this method, hope it helps anyone if you want to use onClick not only on the button element itself
I'm trying to make a button onClick add its value to a text form. I don't really understand the "this" keyword but I tried using this:
function typing(){
document.getElementById('searchbar').value+=this.value
}
For the onClick, nothing happens and there are no errors in console either. Any help would be appreciated.
You can simply bind to click event of the button and add it's value to your text box using this:
$('#button1').click(function(){
$('#searchbar').val($(this).val());
});
Or if you just want to use plain js, you can pass the value inside the click handler like this:
<input type="button" value="A" onclick="doAction(this.value)">
And then:
function doAction(value) {
var searchbar = document.getElementById('searchbar');
searchbar.value = value;
}
Here is a plunkr:
https://plnkr.co/edit/AGR29w1g4TzW4udfazMv?p=preview
I have an inline on click event that looks like this:
<a href="#" class="nextStep" onclick="formHandler.changeStep(2, 'nameYourReport'); return false;">
This onclick basically slide the form to the next step, which works great. My issue is I also want to slide the form if the user clicks the enter key and I am having issues getting the proper parameters for my changeStep function within my actual JS component file since they are normally pulled in based on hardcoded values in the actual HTML.
So my question is, is there a way I can just pull or run the exact function on and enter keydown from an external js file.
My idea would to be to grab the fieldset(parent) with the class active. Then grab the a tag with the class of 'nextStep'. then run the function attached to that element.
So I have gotten the function from the HTML and now have is as a varible with this:
var parent = document.querySelectorAll('.fieldsetParent.active')[0],
clickable = parent.getElementsByClassName("nextStep")[0],
changeStep = clickable.getAttribute('onClick')
.replace('formHandler.', '')
.replace(' return false;', '');
But when I call the variable which should output the function and theoretically run the function it equals to, it doesnt run.
You should use addEventListener in JavaScript instead of inline onclick in HTML. Example:
clickable.addEventListener('click', function () {
event.preventDefault()
formHandler.changeStep(2, 'nameYourReport')
})
This way, you can call formHandler.changeStep() elsewhere if you need to.
document.addEventListener('keypress', function (ev) {
if (ev.key === "Enter") {
event.preventDefault()
formHandler.changeStep(2, 'nameYourReport')
}
})
You can't simply pull the function from the HTML because the attributes are strings not live code.