The function runs when the user presses enter in the textbox (KeyCode === 13) but i cant get it to work with searchButton
function myFunction(e) {
if(e.keyCode === 13 || document.getElementById("searchButton").click()){
e.preventDefault();
var searchValue = document.getElementById("mySearch").value;
for(var i = 0; i < users.length; i++){
if(users[i]['last_name'] === searchValue){
document.getElementById("return").innerHTML = JSON.stringify(users[i]);
return;
}
}
}
}
<input type="search" id="mySearch" onkeypress="myFunction(event)" />
<button id="searchButton" onclick="myFunction(e)">SEARCH</button>
Is the problem the || expression? The function should run either when the user presses searchButton or presses enter.
The call to document.getElementById("searchButton").click() is a programmatic way to simulate a click.
What you probably mean to do is:
function myFunction(e) {
if((e.target.id === 'mySearch' && e.keyCode === 13) || e.target.id === 'searchButton'){
}
}
Ok so when you press the enter key myFunction is called with an event which has the keyCode property, so that is all good.
When you click the button though, the event does not have a keyCode property, and therefore the right side of your conditional document.getElementById("searchButton").click() runs. click is a method that simulates a mouseclick, returning undefined. So the conditional resolves to false, and the rest of the function body will not be run.
You could instead check the type of the event.
Related
First time we press keyboard enter key should execute button(id="botonCorregir"). But the second time we press enter key should execute url().
I use cont, for the first time execute one part of the javascript code, and after when de cont value is 1, execute the second part of javascript code.
For some mistake, it doesn´t work.
thanks!
HTML:
<input id="respuestaUsuario"></input>
<button id="botonCorregir">Reply</button>
<a id="enlaceSiguiente" href="nextQuestion.html">Next question</a>
JAVASCRIPT:
<script>
var cont=0;
if(cont==0){
//Should enter the first press of enter
var input = document.getElementById("respuestaUsuario");
console.log('input: ', input)
input.addEventListener("keyup", function(event) {
if (event.keyCode == 13) {
event.preventDefault();
document.getElementById("botonCorregir").click();
}
});
cont++;
}else{
//Should enter the second press of enter
if (event.keyCode == 13) {
event.preventDefault();
document.getElementById("enlaceSiguiente").click();
}
}
</script>
You have a few mistakes in the code.
You are assigning the event based on the value of cont so always will have that functionality. Javascript does not re-interpret the code once the value of cont is changed.
I mean, Javascript check only one time the condition:
if(cont==0){}
This is a solution that works:
var cont=0;
var input = document.getElementById('respuestaUsuario');
input.addEventListener('keyup', function (event) {
event.preventDefault();
if (event.keyCode == 13) {
if(!cont){
alert('uno');
document.getElementById("botonCorregir").click();
cont++;
}else{
document.getElementById("enlaceSiguiente").click();
}
}
});
I guess you were on the right track, but the problem is that your Javascript only gets executed once. So, the else case will never be triggered. I refactored your code to use the check in the event listener:
var cont = 0;
var input = document.getElementById("respuestaUsuario");
input.addEventListener("keyup", function (event) {
if (event.keyCode == 13) {
event.preventDefault();
if (cont == 0) {
cont++;
document.getElementById("botonCorregir").click();
} else {
document.getElementById("enlaceSiguiente").click();
}
}
});
I also created a codepen for you to check out.
I know how to trigger a function with a textbox:
<input onkeyup="if (event.keyCode == 13) check(this)" type="text">
But what if I'm not focused on any textboxes, but I still need to call a js function with a space button for example?
Particular context:
I'm trying to write an interactive test, and I want users to be able to switch to the next question not only with the button on the page:
<button id="nextButton" onclick="nextQuestion()">Next</button>
but also with a space button, so they can change questions more quickly. To arrange that, I need to call the nextQuestion() function everytime a user presses space on a keyboard.
Try binding the event to the window
window.onkeyup = function(event){
if (event.keyCode== 32) nextQuestion()
}
With jquery you can do something like
$(window).keypress(function(e) {
if (e.keyCode == 32 || e.keyCode == 0) {
nextQuestion()
}
});
or if you prefer vanilla javascript i recommend
window.addEventListener("keyup", keyPressed(e));
function keyPressed(e) {
if(e.keyCode == 32) nextQuestion();
}
can call keyup on body tag or window object
$("body").keyup(function(event){
alert("KeyCode is : " + event.keyCode);
if(e.keyCode == 32){ nextQuestion()}
});
I want to write a code that if a user press a key, It changes the keyCode or charCode of the User event and trigger the event with a new charcode,
I wrote this code in jsfiddle but this code doesn't work because of too much recursion.
function convert(e, elem) {
function getKey(event) {
if (event.which == null) {
return event.keyCode // IE
} else if (event.which != 0 && event.charCode != 0) {
return event.which // the rest
} else {
return null // special key
}
}
var key = getKey(e);
key++;
return key;
}
$(".myInput").keypress(function (e) {
var returnedKey = convert(e, this);
e.which = e.keyCode = returnedKey;
$(this).trigger(e);
});
<input type="text" class="myInput" />
any Idea that help my code work would be appreciated.
Thanks alot.
Regarding the recursion issue, you need to add a stopping condition, for example:
$(".myInput").keypress(function (e) {
var returnedKey = convert(e, this);
e.which = e.keyCode = returnedKey;
if(!e.isSecondTrigger){
e.isSecondTrigger = true;
$(this).trigger(e);
}});
This way, you only change the value once. However, as was stated by LShetty in the comments section, the event values are read only - you can't change the value of the button that was already pressed and in that way change the input text. In order to do this, you need to manually change the value of the input text after each user action (i.e. hold the value of the input text at each key press, modify it when the user presses a key, and then overwrite the input field value with the output).
I have to prevent the form submit if the newVal and oldVal are equal. Else I need to execute the Javascript function. - While pressing Enter key from the key board for the dynamically generated textboxes.
For this case, While pressing enter key the alert is coming repeatedly.
ie, first time one alert. Two alerts for second time.And the expected result is not getting.
What is expected: If I enter a value equals to the curValue then form doesn't have to submit.Else need to call the function myFun(); What is wrong with me?
function pressEnter(id,newValue,i)
{
var newId = '#'+id;
$(newId).keydown(function(event) {
var curValue= '<%=currentVal%>';
var keycode = (event.keyCode ? event.keyCode : event.which);
if(keycode == '13'){
alert(newValue+"-"+curValue);
if(newValue== curValue)
{
event.preventDefault();
}
else
{
myFun(i);
}
}
});
}
You have to unbind previous keydown handler:
$(newId).off('keydown').keydown(function(event) {...});
You can do this comparison on form submit event rather than pressing enter key. Because user can use mouse and click the submit button.
Restrict user on form submit as follows,
$("#your_form_id").submit(function() {
var newValue = $(".your_textbox").val();
var curValue= '<%=currentVal%>';
if(newValue== curValue)
{
event.preventDefault();
//Or use return false;
} else{
myFun();
}
});
Here, we can avoid unwanted bind and unbind operations.
And we can achieve this on enter press, just write without function as follows,
$("#your_text_box_id").keydown(function(event) {
var newValue = $(".your_textbox").val();
var curValue= '<%=currentVal%>';
var keycode = (event.keyCode ? event.keyCode : event.which);
if(keycode == '13'){
alert(newValue+"-"+curValue);
if(newValue== curValue)
{
event.preventDefault();
}else{
myFun();
}
}
});
Note: If you scope this jQuery code within a function,then javascript add handler for same event on every function call. Result is your code(Code in "keydown" callback) run multiple time. To avoid you have to unbind the event.
I need to submit the content of a form when I press the Enter key, but only if the form has no error message. I built up the following function:
$(targetFormID).submit(function (e) {
var mess = error_m(targetDiv);
if (e.keyCode == 13 && mess.length > 0) {
e.preventDefault();
e.stopPropagation();
}
if (mess.length == 0 && e.keyCode == 13) $(targetFormID).submit();
});
In this function the mess variable is getting the error message returned by function error_m, the rest is simple code condtion but it doesn't work.
Need some help with this!!
Submitting the form when the Enter key is pressed is default browser behaviour. Don't mess with it. Just validate the form in the submit event.
$(targetFormID).submit(function (e) {
var mess = error_m(targetDiv);
if (mess.length > 0) {
e.preventDefault();
}
});
One other possible problem: what is targetFormID? If it's actually a string containing an element ID, you'll need
$("#" + targetFormID).submit(/* Same function as above */);
If it's a reference to the form element then $(targetFormID) is fine but your variable is misleadingly named.