on:keydown event with Enter Key in svelte - javascript

I am using svelte with an on:click event on a button. When this button is clicked, I dispatch some information to a higher component. What I would like to do is hit the enter key instead, but on:keydown doesn't seem to work? How can I get this to fire when hitting enter?
<button on:click={() =>
dispatch('search', { searchword: item })}
>ClickMe</button>
<button on:keydown={() =>
dispatch('search', { searchword: item })}
>PressEnter</button>

Enter will automatically fire click if the button has focus or is part of a form and is clicked implicitly as part of the form submission.
Generally I would recommend using a form, then Enter within an <input> will cause a form submission. One can then also directly work with the form's submit event, as that may need cancelling anyway, unless the page reload is desired.
Example:
<script>
let value = '';
let submittedValue = null;
</script>
<form on:submit|preventDefault={() => submittedValue = value}>
<label>
Search
<input bind:value />
</label>
<button on:click={() => console.log('button clicked')}>GO</button>
</form>
{#if submittedValue != null}
<p>Submitted: {submittedValue}</p>
{/if}
REPL

The issue was a state machine giving focus/ not giving focus. This project was using xstate to manage alot.

Related

Is it possible to make a Close/Dismiss button for HTML native <dialog> (no plugin) with <form>?

Following this example, I create a simple dialog that contains a form:
const diag = document.querySelector("#diag")
diag.addEventListener("close", () => {
if (!diag.returnValue) { return; }
document.querySelector(".result").textContent = document.querySelector("#txt-name").value;
});
document.querySelector("#btn-show").addEventListener("click", () => {
diag.showModal();
});
<dialog id="diag">
<form method="dialog">
<input id="txt-name" required />
<button value="submit">Submit</button>
<button value="">Cancel</button>
</form>
</dialog>
<button id="btn-show">Show Dialog</button>
<p>Result: <span class="result"></span></p>
However since the input has required attribute, user cannot click it without filling it. I know I can add a click event to Cancel button and close the dialog but I have many dialogs like this and it's better if there is a general native solution.
I need a solution that closes the dialog; and sets its returnValue to empty ("") if close event is raised by such button.
Current workaround:
document.querySelector("#btn-cancel")
.addEventListener("click", () => {
diag.close(""); // Have to set this since onclose event is raised.
})
I think you should be using dialog.close() in your cancel button event listener.
Doing so will discard all of the dialog and thus get rid of all unfilled inputs.
The form will not get submitted on dialog.close().

why is the form value disappearing from the console log?

In the below code, I am trying to console.log the form input value when a button gets clicked. However, upon the button click, the value is only getting logged momentarily before disappearing.
why is this happening and how to resolve it?
document.querySelector("button").addEventListener("click",function(){
const listItem = document.querySelector("input").value;
console.log(listItem);
});
<body>
<form action="">
<input type="text">
<button class ="btn btn-lg btn-primary" type="submit"> ADD </button>
</form>
</body>
When submitting a form, the browser sends a request to the server and refreshes the page. To disable this behavior, you can use event.preventDefault() when clicking the button
document.querySelector("button").addEventListener("click",function(event){
event.preventDefault();
const listItem = document.querySelector("input").value;
console.log(listItem);
});
<body>
<form action="">
<input type="text">
<button class ="btn btn-lg btn-primary" type="submit"> ADD </button>
</form>
</body>
Others have explained that submitting a form reloads the page. But that doesn't really address the question about the console log.
Go to the Developer Tools settings, and in the Console section check Preserve log upon navigation. Then you won't lose log messages when the page reloads because of the form submission.
This is because browser reloads on the form submission. And your data is lost.
To prevent this simply use "event.preventDefault()" function after your log statement after passing "event" as a parameter in the event listener function.
Like this:
document.querySelector("button").addEventListener("click", function (event) {
const listItem = document.querySelector("input").value;
console.log(listItem);
event.preventDefault();
});

Disable the button after click using a global selector - prevent form submission

I have all kinds of buttons around the app. buttons that I want to have a spinner next to it ( to notify that something is going on ) - I add a specific class ajax_wait.
I catch them with $('.ajax_wait')
Problem is, when the selector catch buttons inside forms - the form will no longer submit.
BUT, this behavior happens only in Chrome - in Firefox it will still submit ..
This is caused because of the .prop('disabled', true) - if I remove it - it works fine.
But I'm trying to find a solution still to make it work globally ( w/o binding submits etc .. ) as I'm not sure what else it will catch when the app grows.
Tried to place return true, tried many thing, nothing seems to work.
$(function() {
$('.ajax_wait').on('click', function() {
$(this)
.prop('disabled', true)
.attr('data-text', "Save")
.html("saving please wait");
})
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
Click this button first - see the JavaScript change: <br />
<button type="button" class="ajax_wait"> Generic button </button>
<br />
<br />
<form method='GET'>
Click this button second in Chrome - it doesn't work <br /> Click this button second in Firefox - it works ?! <br />
<button type="submit" class="ajax_wait"> Save </button>
</form>
Codepen: https://codepen.io/arlevi/pen/PoqdgEZ
As you can see, the buttons that I bind are not always inside a form, sometimes they do other stuff - but generally across the app every "ajax_wait" will place a msg for waiting ...
How can I make the form to submit together with the .prop('disabled', true) ?

Form submits on wrong button click in React

Strange, my entire component keeps submitting by clicking the incorrect button.
The layout:
B Component is inside Component A. A Component has the form. B Component triggers the form submit and I dont know why.
In the return function of A Component:
<form action... method...>
<BComponent />
<button type="submit">Submit</button>
</form>
B Component:
...
_removeFile: function(num){
// issue if function is empty
},
_fileRender: function(){
var files = this.state.fileDetails.map( function(f, x) {
return(
<div key={x}>
<div className="">
<button onClick={this._removeFile.bind(this, x)}>Remove</button>
</div>
</div>
)
}.bind(this));
return(<div>{files}</div>)
},
render: function(){
return(<div>{this._fileRender()}</div>)
}
...
So when I click the remove button, the form submits. Why? That button passes data to _removeFile(). Regardless if that function's empty or not, it still submits. e.preventDefault() does nothing. My knowledge at this stage is limited so excuse the silly mistake, if any.
Worst case is to put Component A's submit button into an onClick().
1.you may use <input type="button"/>, without event.preventDefault()
your updated code > JSBin
<input type="button" value="remove" onClick={this._removeFile.bind(this, x)}/>
in React documentation's examples you may notice that they prefer to use <input type="submit"/> and <input type="button"/>
2.in your map's callback you may use arrow func, in order to not bind
var files = this.state.fileDetails.map((f, x)=>
<div key={x}>
<div className="">
<button onClick={this._removeFile.bind(this, x)}>Remove</button>
</div>
</div>
);
Any button will submit its parent form. This is what buttons do :)
If you need a button but want to prevent the default action you need to use event.preventDefault().
Since you prepopulate an argument to the function using .bind, the event object will be passed as the second argument:
_removeFile: function(num, e){
// do stuff with num
e.preventDefault();
},
working demo: http://jsfiddle.net/69z2wepo/47187/

Formless "form" submission using enter button

We are currently building an application using Dojo Mobile and there are several areas where we have input fields and submit buttons. These input fields and submit buttons do are not in a form, and we just use onclick events to "submit" the values in the fields to be utilized in the javascript. Is there a way to make it so that when we press "enter", or, in the case of mobile applications, when the user presses "search" or "go" on their soft keyboard, it will trigger that particular button? We could potentially have multiple submit buttons on the same page.
...
<div>
<input dojoType="dijit.form.TextBox" />
<button dojoType="dijit.form.Button" type="submit">
Filter
</button>
<div>
...
Place your related fields in a form. Register an "onsubmit" event handler and make it the same as your "onclick" handler for the button. When you return from the event handler, you should either return false or you should call event.preventDefault(). This will prevent the form from being submitted (via POST) to the server.
solution in JQuery:
//when you a key on an input
$("input").keyup(function (e) {
//if it is enter
if (e.keyCode == 13) {
//look for the next submit button a trigger a click
$(this).next("button[type='submit']").click();
}
});
I'm not a dojo-coder but the documentation seems quite good:
http://dojotoolkit.org/documentation/tutorials/1.6/key_events/
http://dojotoolkit.org/api/1.6/dojo/keys/ENTER
see here for related answer:
Enter key press event in JavaScript
http://dojo-toolkit.33424.n3.nabble.com/want-enter-key-in-ValidationTextBox-to-submit-the-form-td977303.html
Overriding the Default Form Submit Action
You can override the default submit action on a form. It's semantically wise to keep your forms within <form> tags, even when you want to override the default behavior, and do what you want, as the strong, independent black woman that you are.
jsFiddle
HTML:
<form id="myForm">
<input type="text" />
<button type="submit">Submit</button>
</form>
JavaScript:
var myForm = document.getElementById('myForm');
myForm.addEventListener('submit',function(event){
alert('submit pressed -- do as you please');
event.preventDefault(); // cancels form submission
});
//Chase.

Categories

Resources