I am using the following html
<input type="button" value="Get" onClick="get();">
get(); it is some function declared earlier using javascript
I know if the input type is submit it works, but how to make it work for the following?
Enter on Key Board.
get function
function get() {
$.post('ass.php', { name: form.name.value },
function(output){
$('#age').html(output).show();
});
}
What are you trying to do is against standards: http://www.w3.org/wiki/HTML/Elements/input/button "The button state represents a button with no default behavior."
The only solution is to catch keyPress action, with appropriate button code.
jQuery has a keyup method, but I'm not sure it will do what you want -- it will detect whether a key has released when the button has focus. The only way to intercept the enter key and prevent it from making the form submit will be to use submit.
Related
I've been learning ReactJS and made an app using Web Dev Simplified's video. As a next step I would like to add a keyUp or event listener (whichever works best) so the enter key can be pressed to Add Todo OR by pressing the add button.
Here is the function that adds the input to the list.
function handleAddTodo(e) {
const name = todoNameRef.current.value
if (name === '') return
setTodos(prevTodos => {
return [...prevTodos, { id: uuidv4(), name: name, complete: false}]
})
todoNameRef.current.value = null}
As I was looking for a solution, I found that hooks might do the trick, but I am not sure where or how to add one.
<button class="add" onClick={handleAddTodo}>Add ToDo</button>
And this is the button itself. I thought about adding onKeyup next to onClick but I don't know how to specify the enter key - as in I know it's keycode is 13 but I don't know how to relate that to the function.
What you are trying to do is have a submit action.
Simply add a html form of type submit with action arround you input field and you are good to go.
Also change the button to type submit.
On pressing enter the form would be posted back.
Take a look here. https://reactjs.org/docs/forms.html
I know that this question has been asked before but I'm having particular trouble submitting my form when I press the enter key. I've tried multiple solutions but none have worked. When I try to press enter, the page refreshes and my typing is gone.
This is my HTML:
form class="nput">
<h1 class= "header">Member Login</h1>
<label class="text" for="pswd">Enter your password: </label>
<input class="form" type="password" id="pswd">
<input id="yeet" class="bttn" type="button" value="Submit" onclick="checkPswd();" />
</form>
And this is my Javascript:
<script type="text/javascript">
function checkPswd() {
var confirmPassword = "password";
var password = document.getElementById("pswd").value;
if (password == confirmPassword) {
window.location="members.html";
}
else{
alert("Password incorrect. Please try again.");
}
}
// Get the input field
var input = document.getElementById("pswd");
input.addEventListener("keyup", function(event) {
if (event.keyCode === 13) {
alert("hi there");
event.preventDefault();
document.getElementById("yeet").click();
}
});
</script>
I cannot figure out this small issue and I would appreciate any help! Thanks!
EDIT: I just wanted to let everyone know that I do in fact know that there is little security that comes with this method but I mostly want the password for looks not function.
You got something backwards there - you are submitting the form with Enter. This is exactly the problem though, it seems as if you don't want to submit it, instead you want to run your client-side handler checkPswd. (You do know that everyone can read the correct password in their browser console though, right? So it's no protection.)
What you want to do is change the onclick on the button to an onsubmit on the form itself! Then your code will run no matter in what way (keyboard or mouse) the form is submitted.
You can delete the whole keyup stuff then.
(The reason your attempt to "click" the button in JavaScript wasn't working is because unlike jQuery's click method, the vanilla click will only execute the default action and not any attached click event handlers like yours. Also, it is kinda backwards because you should react on the common ground of both clicking the button and pressing Enter, which is submitting the form.)
To echo a comment above - you want to use the onsubmit handler on the <form> element - this will allow users to submit the form both by clicking the <button type="submit> button, and by hitting the enter key in one of the forms <input> elements.
You can probably ditch the input.addEventListener("keyup", function(event) {...} altogether by just using the obsubmit handler.
You can learn more about the HTML <form> element's onsubmit behavior here:
https://www.w3schools.com/tags/ev_onsubmit.asp
No need to put handlers on button element. You should use either input type as submit or button type as submit. onsubmit handler can be given to form element where you can actually prevent default event and go ahead with password validation .
Hope this gives you an idea.
If I were you, I would do two things:
1) I would check the Chrome debugger to see if there are any issues with your code
2) Instead of input.addEventListener("keyup", function(event) {, I would try input.onkeyup = function(event) { and see if that works.
Hope this helps.
Imagine this :
<form id="form">
<input type="text">
<button type="submit" name="submit1" value="1">something1</button>
<button type="submit" name="submit2" value="2">something2</button>
<button type="submit" name="submit3" value="3">something3</button>
</form>
First of all when I write $('#form').submit() which submit value will be sent? the first one?
Second of all How can I submit the form without the click trigger event with the value I want? Is it possible at all? For example submitting the form with the 2 submit value.
The reason I want do this is to have confirmation popup with sweetalert before sending my form so here it is :
$('form').on('submit',function(e){
form = $(this);
e.preventDefault();
swal({'some dialog'},function(isConfirm)
{
if(isConfirm)
form.submit;
\\If I use the click trigger I will get stuck in here again.
})
});
There is an alternative - use the FormData You can create an instance of a FormData, add your html form, modify entries, and send it. Everything is under your control here then.
EDIT: Based on your edit, it seems you have the problem of resubmitting the form. You can handle it like this.
var form = document.querySelector('form');
form.addEventListener('submit', {
confirmed: false,
handleEvent: function (event) {
if (this.confirmed)
return;
event.preventDefault();
doconfirm((confirmed) => {
if (confirmed) {
this.confirmed = true;
form.submit();
}
})
}
}, false);
Or you can solve your problem by unbinding the submit handlers after validation and submit it again: $('form').off('submit').submit()
As #Scott Marcus explained, the value of named buttons will be submitted when the form is sent to the server. However in your case, this won't help because you want to perform some logic before submitting it to the server.
The issue is that jQuery has no way to determine which button was clicked because it doesn't provide the submit button values when you look at the form data via $.serialize(), and there is no easy cross-browser friendly way to check the button that triggered the $.submit() event without using click.
So, the only workaround would be to handle the click event of the 3 buttons and store some value that is checked before you submit the form as described in this answer: How can I get the button that caused the submit from the form submit event?
Example: http://codeply.com/go/Wj85swRyfX
Let's take your questions one at a time...
First of all when I write $('#form').submit() which submit value will
be sent? the first one?
When a form is submitted, ALL form elements that nave a NAME attribute will submit their value (even if the value is an empty string) to the form's ACTION destination. So, in your case, all 3 of your buttons have a name attribute and so all 3 buttons will submit their name/value pairs.
Usually, we don't put a name attribute on the submit button because we only want it to trigger the submit, not actually use it as a data container. And, we usually include only a single submit button under most circumstances.
Second of all How can I submit the form without the click trigger
event with the value I want? Is it possible at all? For example
submitting the form with the 2 submit value
You would use:
$('#form').submit()
to manually cause the submit, but you'd need to have an if() statement that has logic that determines which value is appropriate to submit. Instead of the value being stored in a button, you could use a hidden form field, like this:
<form id="form">
<input type="text">
<input type="hidden" name="hidden" value="">
<button type="submit">something3</button>
</form>
JavaScript:
$("#form").on("submit", function(evt){
// Stop the form submission process
evt.preventDefault();
// Logic that sets hidden input field to correct value:
if(condition1){
$("input[type=hidden]").attr("value", "1");
} else if(condition2) {
$("input[type=hidden]").attr("value","2");
} else {
$("input[type=hidden]").attr("value","3");
}
// Manually submit the form
$("#form").submit();
});
I suggest to use hidden input tag to make the logic clear.
I have a form in that I have User Id availability check. So if Id is already in DB it will show a message "Id is already in use". In that case I have to avoid submitting the form. For that my html is as follow,
<div>
<label><strong>Teacher Id:</strong></label>
<input type="text" name="teacherId" id="teacherId" placeholder="Enter Teacher Id" >
</div><span class="status" id="status"></span>
Here span will have the text about availability,
The value to span comes form jquery post call,
$.post('<%=request.getContextPath()%>/controller/TeacherIdCheckController',
{'teacherId':teacherId},
function(data)
{
$('.status').html(data);
});
}
This works fine, to prevent submitting I wrote javascript function as,
function checkTeacherId(){
alert(" in checkTecherId()");
var status=$("#status").text();
alert(status);
if(status=="Id in use try another")
preventDefault();
else
return true;
}
Everything works fine but this javascript function is not working fine so I cant able to prevent submit in case of Id already exist in DB. So please anyone help me in this.
Just because you need to pass the event in the function's arg:
function checkTeacherId(e){ // <---pass the event here
.....
if(status=="Id in use try another")
e.preventDefault(); // and stop it here using dot notation
else
return true;
}
As per your comment you can pass the event to your function in your onclick handler:
onclick="checkTeacherId(event);"
Fiddle
Okay! As #Sanjeev tried commenting on best approach for this work then as you are using jQuery then you can just do this as per best approach like Unobrusive Javascript (removing this inliner scripts just like above posted):
function checkTeacherId(e){ // <---pass the event here
.....
if(status=="Id in use try another")
e.preventDefault(); // and stop it here using dot notation
else
return true;
}
$(function(){
$('#yourformid').on('submit', function(e){
checkTeacherId(e);
});
});
Use this approach if you want to externalize your scripts as declare the function in global scope and put your event handler in doc ready with submit event.
Updated fiddle with unobtrusive way.
Solution as per best practice for form validation:
You have implemented form submit via Submit button and not through js like document.getElementById("myForm").submit();
I don't see any point in using onclick handler on submit button for validation, use the native onsubmit Event Attribute, else you will keep on breaking submit flow.
onsubmit is made for validating form and stopping form submission if validation fails.
This will work sure shot in all browsers and is the correct approach for form validation
Example:
<form action="demo_form.asp" onsubmit="return checkTeacherId()">
function checkTeacherId(){
var status=$("#status").text();
if(status==="Id in use try another"){
return false
}
else{
return true;
}
}
I have a simple search page with a single input box.
I want to be able to trigger the search action either by clicking "Go" or by pressing Enter in the input box. I did it like this:
$("input[name='entry']").keyup(function (event) {
if (event.keyCode == 13) {
search_phone();
}
});
$('a#go').click(function () {
search_phone();
});
Is there a more elegant way to do this? Like with bind and trigger, or fling. If so, how?
Not much can you improve here. Your code is pretty good.
You could skip the anonymous function for the click event.
$('a#go').click(search_phone);
I would just make your "go" link the submit button
<input type="submit" name="submit" value="go"/>
And then just bind your function to the submit (which would happen either from pressing enter while in the text box or by clicking the go button.
$('#my_form').submit(search_phone);