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.
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 have a question. I have made a small site in HTML and vanilla JS to act as a counter. It is working fine, but I wanted to add a function that would allow the user to add or subtract 1 from the counter by pressing "+" or "-", in the numpad or not.
What is the easiest way to do this in vanilla JS?
Sure, just attach to the keyup events and increment or decrement the value when the proper key is pressed.
var value = 0;
document.addEventListener("DOMContentLoaded", function(event) {
document.querySelector(".valueHolder").innerHTML = value;
});
document.addEventListener("keyup", function(event) {
if (event.which == "187" || event.which == "107") { // + key
value++;
}
if (event.which == "189" || event.which == "109") { // - key
value--;
}
document.querySelector(".valueHolder").innerHTML = value;
console.log(event.which);
});
<div class="valueHolder"></div>
You will want to add an event listener on the document
document.addEventListener('keydown', myFunction);
function myFunction(e) {
var keyCode = e.keyCode();
...
}
You'll want to look up the keycodes for the keys you will be using (+ and -) and compare that value to keyCode. Then use a conditional to execute your adding or subtracting.
You would create an event handler, which would add or subtract from a global variable based on the key pressed, like this:
window.counter=0;
function key(ev){
if(ev.keycode==107) window.counter++;
if(ev.keycode==109) window.counter--;
}
document.onkeypress = key;
I have a autocomplete textbox in a form and I want to detect whether user has focussed on the textbox from navigating through tab key press.I mean tabindex has been set up on different form fields and user can navigate fields by pressing tabs.Now I want to perform some action when user directly mouse click/foxus on the textbox and some other action when user has focussed on the textbox through tab.
Below is the code I was trying.But no matter everytime code is 0.
$('#tbprofession').on('focus', function (e) {
var code = (e.keyCode ? e.keyCode : e.which);
if (code == 9) {
alert('Tabbed');
}
else
{
alert('Not tabbed');
}
});
This code does not work.
Note:Before marking duplicate it will be good if you understand the question correctly.Else I can make it more clear with more elaborated description.
Anyone can show me some light?
You can try something like that :
$(document).on("keyup", function(e) {
if ($('#tbprofession').is(":focus")) {
var code = (e.keyCode ? e.keyCode : e.which);
if (code == 9) {
alert('I was tabbed!');
} else {
alert('not tabbed');
}
}
});
fiddle : https://jsfiddle.net/xc847mrp/
You can use keyup event instead:
$('#tbprofession').on('keyup', function(e) {
var code = (e.keyCode ? e.keyCode : e.which);
if (code == 9) {
console.log('I was tabbed!', code);
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input autofocus>
<input id='tbprofession'>
You could have an array of key events triggered anytime a user presses a key while on your page. Although this makes you think of a keylogger.
Or just keep the last key.
Or a boolean saying if the last key pressed was a TAB or not.
And on focus you can look at that variable.
I'm trying to create a note system. Whatever you type into the form gets put into a div. When the user hits Enter, they submit the note. However I want to make it so when they hit Shift + Enter it creates a line break a the point where they're typing (like skype). Here's my code:
$('#inputpnote').keypress(function(event){
var keycode = (event.keyCode ? event.keyCode : event.which);
if(keycode=='13' && event.shiftKey){
$("inputpnote").append("<br>");
}
else if(keycode == '13'){
var $pnote = document.getElementById("inputpnote").value;
if ($pnote.length > 0) {
$("#pnotes-list").append("<div class='pnote-list'><li>" + $pnote + "</li></div>");
$('#inputpnote').val('');
}
}
});
#inputpnote is the form where the user enters their note and #pnotes-list is the place where the notes are being appended to. Thank you in advance!
I think for this you'd have to set two global variables, 1 for shitftKeyPress and 1 for enterKeyPress and then you'd need a keydown and a keyup to set those values and then you check to see if they are both true, because your logic is saying, when a key is pressed, execute this code, if you press a key and then press another key, the only that will happen is the function will be called twice.
EDIT:
Example code of what it should look like:
var hasPressedShift = false;
var hasPressedEnter = false;
$('#inputpnote').keydown(function(event){
if(shiftkey) {
hasPressedShift = true;
}
if(enterKey) {
hasPressedEnter = true;
}
});
$('#inputpnote').keyup(function(event){
if(shiftkey) {
hasPressedShift = false;
}
if(enterKey) {
hasPressedEnter = false;
}
});
$('#inputpnote').keypress(function(event){
if(hasPressedShift && hasPressedEnter) {
// Do something
}
});
This was a quick mock up, but it's similar to how it should look
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.