input cannot be empty but console.log is still running - javascript

The code is works but how can I stop the console when input empty is? Console side responds in all conditions.
<label>Enter your name: </label> <br>
<input type="text" id="myText"> <br>
<button type="button" onClick="click()"id="myButton">Submit</input>
document.getElementById("myButton").onclick = function() {
var myName = document.getElementById("myText").value;
console.log("Hello", myName);
}
var input = document.getElementById("myText");
addEventListener("keyup", function(event) {
if (event.keyCode === 13) {
event.preventDefault();
document.getElementById("myButton").click();
if (document.getElementById("myText").value.length == 0) {
alert("You must write something!")
return;
}
}
});

The console.log call is inside the onclick function, which you call before you check whether there was any content in the input.
It would make more sense to do your if statement inside the onclick function to get the desired result.
document.getElementById("myButton").onclick = function(){
var myName = document.getElementById("myText").value;
if (myName.length == 0) {
console.log("Hello",myName );
alert("You must write something!")
}
}
var input = document.getElementById("myText");
addEventListener("keyup", function(event) {
if (event.keyCode === 13) {
event.preventDefault();
document.getElementById("myButton").click();
}
});

Because you are checking if myText is empty after print it to console.
I think this should be work :
if (event.keyCode === 13) {
if(document.getElementById("myText").value.length == 0)
{
alert("You must write something!")
return ;
}else{
event.preventDefault();
document.getElementById("myButton").click();
}
}

We need a couple of changes
// JavaScript code needs to run after dom has fully mounted
window.addEventListener('DOMContentLoaded', (event) => {
const myButton = document.getElementById(“myButton”);
const myText = document.getElementById(“myText”);
// event listeners
myButton.addEventListener(“click”, eventForButton);
myText.addEventListener(“keydown”, (e)=> {
if (event.keyCode === 13) {
e.preventDefault();
// if input doesn’t have a value some browsers return null
// that’s why is better to have a falsely comparison
if(!e.target.value) {
alert("You must write something!")
return ;
}
// you need to click the button after the validation, not before as you have it
myButton.click();
}
});
});

Related

How to get a key press to correspond to the function that gets called first in javascript

So I'm trying something out, if you have two functions you want to call after the same key press like so:
var plus = function () {
document.addEventListener("keyup", function(e) {
if (/[+]/g.test(e.key)) {
console.log("plus");
}
})
}
plus();
var minus = function() {
document.addEventListener("keyup", function(e) {
if (/[-]/g.test(e.key)) {
console.log("minus");
}
});
}
minus();
function check() {
document.addEventListener("keyup", function(e) {
if(plus) {
if (e.keyCode == 13) {
console.log("enter pressed after plus");
plus = false;
minus = function() {
document.addEventListener("keyup", function(e) {
if (/[-]/g.test(e.key)) {
console.log("minus");
}
});
}
}
} else if(minus) {
if (e.keyCode == 13) {
console.log("enter pressed after minus");
minus = false;
plus = function () {
document.addEventListener("keyup", function(e) {
if (/[+]/g.test(e.key)) {
console.log("plus");
}
})
}
}
}
});
}
check();
If you press minus first then enter console.log("enter pressed after plus") always gets called first because of the code's order, even though what I want to do is that I want the enter to correspond to the key I'm pressing first, if I press plus first then I want console.log("enter pressed after plus") to get called, and if I press minus first then I want console.log("enter pressed after minus") to get called.
Any help would be appreciated and thanks in advance.
Oh also sorry about the stupid title, couldn't think of a better one.
To clean this up a bit (keep it DRY) you can move all the event handler logic into a single function and use a single listener.
To keep track of the last pressed key we can use a variable defined in the function's outer scope. And, update it after each event. Then, when "Enter" is pressed we can check what the last key was and log accordingly.
Also, the KeyboardEvent.keyCode property is depreciated. You should use KeyboardEvent.code property instead.
Example
const input = document.querySelector('input')
const log = document.getElementById('log')
function check() {
let lastKey = null
input.addEventListener('keyup', ({ key }) => {
if (['+', '-', 'Enter'].includes(key)) { // we only care about these keys
if (key === '+') log.textContent = 'plus'
if (key === '-') log.textContent = 'minus'
if (key === 'Enter') { // `Enter` was keyed, what was keyed last?
if (lastKey === '+') log.textContent = 'enter pressed after plus'
if (lastKey === '-') log.textContent = 'enter pressed after minus'
}
lastKey = key // current key becomes last key
}
})
}
check()
<input placeholder="Click here, then press and release a key." size="40">
<p id="log"></p>

jQuery or javascript prevent event from input keypress

CODE:
var appender = $('<input class="form-control" placeholder="Search" id="search_made" type="text">')
appender.find('#search_made').on('keypress', function(e) {
e.preventDefault()
console.log('keypress!')
if (e.keyCode == 13 && !e.shiftKey) {
console.log('not shift enter')
var passed_value = $(this).val()
if (passed_value === '') {
console.log('nothing was passed on input tag')
return false;
}
console.log('passed value: ' + passed_value)
}
})
$('body').append(appender)
I want to add input tag dynamically by jQuery.
Using those code, I can only add input tag seemingly but other functions that has to be bound was not bound well.
So when I type some words on input tag and click enter key, It refreshes page but does not execute any console.log() lines.
How can I fix it to make it do other bound functions(include console.log()) well?
Change the selector from:
appender.find('#search_made').on('keypress', function(e) {
To
$(document).on('keypress','#search_made', function(e) {
OR: Simply
appender.on('keypress', function(e) {
Working Code Example:
var appender = $('<input class="form-control" placeholder="Search" id="search_made" type="text">')
$(document).on('keypress','#search_made', function(e) {
e.preventDefault()
console.log('keypress!')
if (e.keyCode == 13 && !e.shiftKey) {
console.log('not shift enter')
var passed_value = $(this).val()
if (passed_value === '') {
console.log('nothing was passed on input tag')
return false;
}
console.log('passed value: ' + passed_value)
}
})
$('body').append(appender)
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

Detecting that a button/submit returning false

I have this simple javascript:
window.onclick = function test(e) {
if(e.which == 1)
{ if(e.target.type == 'submit')
{ // Actions here
}
}
}
And I have a (submit) button somewhere on the page which has attribute onclick
that returns true on certain conditions and returns false on others.
Is there a way detect when the button/submit button is pressed,
If it is successfully executing all the onClick/onSubmit/onChange attributes attached to it?
Or, if it fails and terminated by any conditions? (in my case, the return false statement)
A workaround solution (by declaring a globally-scoped javascript variable) -
<input type="submit" onclick="SubmitOnClick();" id="myBtn" value="Click" />
javascript code:
<script type="text/javascript">
var g_isSuccessfulSubmit = null;
window.onclick = function test(e) {
if(e.which == 1)
{
if (e.target.type == 'submit')
{
var isSuccessful = g_isSuccessfulSubmit;
g_isSuccessfulSubmit = null;
// Actions here
}
}
}
function SubmitOnClick() {
var isSuccessful = false;
//if (successfully executing)
//{
// isSuccessful = true;
//}
g_isSuccessfulSubmit = isSuccessful;
return isSuccessful
}
</script>

jquery textbox focus event on infinity loop

i am using jquery to validate textbox value.
I have 2 textbox, txt1 & txt2. now, i wrote a jquery function.
$("#txt1").blur(function () {
if ($("#txt1").val() == "") {
$("#scarriername").show();
$("#txt1").focus();
}
else {
$("#scarriername").hide();
}
});
$("#txt2").blur(function () {
if ($("#txt2").val() == "") {
$("#sscaccode").show();
$("#txt2").focus();
}
else {
$("#sscaccode").hide();
}
});
Now, issue is. when i run the project. my position is on txt1 and when u use Tab to go txt2 with null or blank value. Focus event fire for both one & browser become hang due to infinite loop of FOCUS.
so, how can i handle it?
You should insert a setTimeout in order to set the focus after the blur event.
Second, you should insert a semaphore in order to avoid a loop (see code and comments):
var status = "valid"; // semaphore
$("#txt1").blur(function (e) {
// if we are in programmatically focus, ignore this handler
if(status == "invalid")
return ;
if ($("#txt1").val() == "") {
$("#scarriername").show();
// set semaphore
status = "invalid";
// use setTimeout in order to set focus in the right moment
setTimeout(function() {$("#txt1").focus(); status = "valid"},0);
}
else {
$("#scarriername").hide();
}
});
// same as txt1
$("#txt2").blur(function () {
if(status == "invalid")
return ;
if ($("#txt2").val() == "") {
$("#sscaccode").show();
setTimeout(function() {$("#txt2").focus(); status = "valid"},0);
}
else {
$("#sscaccode").hide();
}
});
DEMO http://jsfiddle.net/SszUf/
try this
<input type="text" id="txt1" />
<input type="text" id="txt2" />
$("#txt2").focus(function () {
if ($("#txt1").val() == "") {
$("#scarriername").show();
$("#txt1").focus();
}
//alert(1);
});
hope this help you
Apparently when you hit the tab button you trigger blur event for both text boxes. With your code when txt1 gets blurred and has no content you get the focus on txt1, but when you do that you also trigger the blur event for txt2 and since it does not have any text in it you get the focus back to txt2. This keeps on going and going, focusing on txt1 and then txt2 and then txt1 and then txt2... You could put a simple if check on the second blur event handler to see if txt1 is still empty, and if so keep the focus on txt1 not allowing the client to pass to txt2:
$("#txt1").blur(function () {
if ($("#txt1").val() == "") {
$("#scarriername").show();
$("#txt1").focus();
}
else {
$("#scarriername").hide();
}
});
$("#txt2").blur(function () {
if ($("#txt2").val() == "" && $("#txt1").val() != "") {
$("#sscaccode").show();
$("#txt2").focus();
}
else {
$("#sscaccode").hide();
}
});
This is also one of the approach to solve your problem on pressing tab key.
$("#txt1").bind('keydown',function(e)
{
if(e.keyCode == 9)
{
if ($("#txt1").val() == "") {
$("#scarriername").show();
return false;
}
else {
$("#scarriername").hide();
}
}
});
$("#txt2").bind('keydown',function(e)
{
if(e.keyCode == 9)
{
if ($("#txt2").val() == "") {
$("#sscaccode").show();
return false;
}
else {
$("#sscaccode").hide();
}
}
});
$("#txt1").blur(function () {
if ($("#txt1").val() == "") {
$("#scarriername").show();
if ($("input:focus").length == 0)
$("#txt1").focus();
}
else {
$("#scarriername").hide();
}
});
Just add a line can solve this problem
By the way, the #scarriername should not be something like popup window, which will trigger other blur events
You can test the file below:
<!doctype html>
<html>
<head>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
</head>
<body>
<input id="txt1"><input id="txt2"><input id="txt3"><input id="txt4">
<hr>
<h1 id="h1"></h1>
</body>
<script type="text/javascript">
$(function(){
$("input").blur(function () {
if ($(this).val() == "") {
document.getElementById("h1").innerHTML += "123";
$(this).focus();
}
});});
</script>
</html>

Why input value can not be changed when pressing escape

I have an input (outside form) that captures name of an image. User should fill in a new name and hit enter. Ajax callback renames the image. This works.
I'd like to add ability to 'reset' the input content when the user presses escape (#27). But I'm not able to fill the value of the input with my value.
The code is
<input id="escapeInput" value="this is test" /> <input type="button" id="setDetaultToEscapeInput" value="Set default" />
jQuery(document).ready(function() {
jQuery("#escapeInput").keydown(function(evt) {
if (evt.keyCode == 27) {
var input = jQuery(this);
input.val('some default value') // doesn't work
input[0].value = 'some default value 2'; // doesn't work
input.parent().append('changed');
}
});
jQuery("#setDetaultToEscapeInput").click(function() {
var input = jQuery("#escapeInput");
input.val('some default value') // works ok
});
});
The interesting thing is that if I test e.g. for 'A' character ( if (evt.keyCode == 65)), the code works.
Any idea how to handle it? It doesn't work only in FF (Opera and IE8 are OK).
Try using the keyup event instead.
$(function() {
$("#escapeInput").keyup(function(e) {
if (e.keyCode == 27) {
$(this).val("some default value");
}
});
});
Try this
$(document).ready(function () {
$("#escapeInput").keypress(function (evt) {
var keycode = null;
if (evt.keyCode) {
keycode = evt.keyCode;
} else {
keycode = evt.which;
}
if (keycode == 27) {
$(this).val("some default value");
}
});
});

Categories

Resources