Prevent actions if validation fails on blur event - javascript

On blur of an input field I want to run a validator. If validation fails I need to set focus back in to the field and cancel out the next intended operation.
I am able to achieve the first part, to set the focus back into the field, but the next operations (button click, link click) are also executing. I need help in restricting actions if validation fails in blur.
Following is the code snippet replicating this behavior. Focus on the field and then try to click on the link/button. Their callbacks are getting executed, which I need to restricted if there is an error on blur event handler of the input field.
$(document).ready(function() {
$('.form-control').blur(function(e) {
var $this = jQuery(this),
hasError = true;
if (hasError) {
setTimeout(function() {
$this.focus();
}, 0);
return false;
}
});
$('.link').click(function(e) {
console.log('link clicked');
});
$('.button').click(function(e) {
console.log('button clicked');
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="container">
<input type="text" class="form-control" />
<br/><br/>
Link
<br/><br/>
<button class="button">Submit</button>
</div>

You can try with pointer-events
$(document).ready(function() {
$('.form-control').blur(function(e) {
var $this = jQuery(this),
hasError = $this.val().trim()== ''?true:false;
if(hasError) {
setTimeout(function() {
$this.focus();
}, 0);
$('.link, .button').css('pointer-events','none');
}
else $('.link, .button').css('pointer-events','');
});
$('.link').click(function(e) {
console.log('link clicked');
});
$('.button').click(function(e) {
console.log('button clicked');
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width">
<title>JS Bin</title>
</head>
<body>
<script src="https://code.jquery.com/jquery-3.1.0.js"></script>
<div class="container">
<input type="text" class="form-control" />
<br/><br/>
Link
<br/><br/>
<button class="button"> Submit</button>
</div>
</body>
</html>

Related

Stop event propagation by clicking inside input element

I am encountering a weird problem here, I have a div having an click event attached to it, and a input having on-blur event and button having click event attached to it.
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width">
<title>JS Bin</title>
</head>
<body>
<div onClick='div()'>
<input onBlur='input()' />
<button onClick='button(event)'> ABCD </button>
</div>
</body>
</html>
Here are the functions that gets called when buttons are clicked.
function input(event){
console.log('input')
event.stopPropagation();
}
function button(event) {
console.log('button')
event.stopPropagation();
}
function div(){
console.log('div')
}
The problem that I am encountering here is that, if I click inside the input box then it is logging what is inside the div function, I tried event.stopPropagation(), but it doesn't seem to work is there any way to make it work? i.e - not logging what is inside div on clicking the input.
Here is a Bin for the same.
You have to set stop propagation for input click not on blur ,
so the div click will not be propagated :
see below snippet
function input(){
console.log('input')
event.stopPropagation();
}
function inputStopPropagation() {
event.stopPropagation();
}
function button(event) {
console.log('button')
event.stopPropagation();
}
function div(){
event.stopPropagation();
console.log('div')
}
<div onClick='div()' style="padding:5px; background :green">
<input onBlur='input()' onClick='inputStopPropagation()' />
<button onClick='button(event)'> ABCD </button>
</div>

Combining mouse click and enter key press in the same event listener

I have a div that I made focusable with tabindex, and I want it to act like a button, doing something on both mouse click and enter key press. Can you do this with a single event listener, combining the following into one?
document.getElementById("myId").addEventListener("click", function() {
console.log("click");
});
document.getElementById("myId").addEventListener("keyup", function(e) {
if(e.keyCode === 13) {
console.log("click");
}
});
You can put the events to handle in an Array and use forEach to add the event listener to the element.
<div tabindex="-1" style="width: 100px; height: 100px; border: 1px solid black; background-color: #f0f"></div>
<script>
var div = document.querySelector('div');
["click", "keypress"].forEach(ev=>{
div.addEventListener(ev, function(e){
if(ev=="click"){
console.log("click");//clicked
}
if(e.keyCode==13){
console.log("click");//enter key pressed
}
});
});
</script>
You can also define a function that both of the event listeners call.
<div tabindex="-1" style="width: 100px; height: 100px; border: 1px solid black; background-color: #f0f"></div>
<script>
var div = document.querySelector('div');
["click", "keypress"].forEach(ev=>{
div.addEventListener(ev, handleEvent);
});
function handleEvent(e){
if(e.type=="click"){
console.log("click");//clicked
}
if(e.keyCode==13){
console.log("click");//enter key pressed
}
}
</script>
No, you need to use two listeners, but as you have to pass a function to the listener which is called and gets all the necessary arguments you can create a single function for both cases like this:
function handleEvent(e){
if(e //make sure a mouseEvent has been passed as argument
&&
e.keyCode === 13 //check for the correct key
){
console.log("click");
}
}
document.getElementById("myId").addEventListener("click", handleEvent);
document.getElementById("myId").addEventListener("keyup", handleEvent);
If you'd like just take the enter key, click, you can use the "click" event that will trigger the following inputs: "Enter", "Space" and "Click"
You can test it here:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>TEST</title>
</head>
<body>
<button id="test">TEST</button>
</body>
<script>
const testBtn = document.getElementById("test");
testBtn.addEventListener("click", (event) => {
console.log("Hello world");
});
</script>
</html>
I thinks this is the best answer
<form>
<input id="myInput" placeholder="Some text.." value="">
<input type="submit" id="myBtn" value="Submit">
</form>
<script>
var input = document.getElementById("myInput");
input.addEventListener("keyup", function(event) {
if (event.keyCode === 13) {
event.preventDefault();
document.getElementById("myBtn").click();
}
});
</script>

How do I remove a appended element with jQuery?

In jQuery I want to be able to add and remove an element. I got the code for appending an element. Now I want to remove that same element when I click on it.
What is the best way to make this so called ToDo list in jQuery?
$(document).ready(function () {
$("#add").click(function () {
var newToDo = $("#newToDo").val();
if(newToDo.length > 0){
$("#toDoList").append("<p>" + newToDo + "</p>");
$("#newToDo").val(" ");
}
});
});
<h1>Todo list</h1>
<form name="form" action="#">
<input id="newToDo" type="text" name="in">
<button id="add">Add!</button>
</form>
<div id="toDoList"></div>
You should use event delegation to attach event to dynamically created elements like :
$("#toDoList").on('click', 'p', function() {
$(this).remove();
});
NOTE : Any button tag inside a form will be considered as submit button so it will refresh you page, to avoid that you should add type="button" to your button, like :
<button type="button" id="add">Add!</button>
Hope this helps.
$(document).ready(function() {
$("#add").click(function() {
var newToDo = $("#newToDo").val();
if (newToDo.length > 0) {
$("#toDoList").append("<p>" + newToDo + "</p>");
$("#newToDo").val(" ");
}
});
$("#toDoList").on('click', 'p', function() {
$(this).remove();
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<h1>Todo list</h1>
<form name="form" action="#">
<input id="newToDo" type="text" name="in">
<button type="button" id="add">Add!</button>
</form>
<div id="toDoList"></div>
You can simply store the element in a variable:
$(document).ready(function () {
$("#add").click(function () {
var newToDo = $("#newToDo").val();
if(newToDo.length > 0){
var anotherToDo = $("<p>" + newToDo + "</p>");
$("#toDoList").append(anotherToDo);
$("#newToDo").val(" ");
// later when you want to delete it
anotherToDo.remove();
}
});
});
Or give it an ID and then remove it using that:
$(document).ready(function () {
$("#add").click(function () {
var newToDo = $("#newToDo").val();
if(newToDo.length > 0){
var anotherToDo = $("<p>" + newToDo + "</p>").attr('id', '#someid');
$("#toDoList").append(anotherToDo);
$("#newToDo").val(" ");
// later when you want to delete it
$('#someid').remove();
}
});
});
Looks like it's already been answered for you, but here's an easy way to do what you want in jQuery:
// external.js
$(function(){
var todo = $('#todo');
function todos(){
$('#todos>li').click(function(){
todo.val($(this).text());
});
}
function remove(){
$('#todos>li').remove(":contains('"+todo.val()+"')");
}
function add(){
var tv = $.trim($('#todo').val());
if(tv !== ''){
remove(); $('#todos').append('<li>'+tv+'</li>'); todos(); todo.val('');
}
}
todo.focus(function(){
todo.val('');
});
$('#frm').submit(function(e){
add(); e.preventDefault();
});
$('#add').click(add);
$('#rmv').click(function(){
remove(); todos();
});
});
/* external.css */
html,body{
padding:0; margin:0;
}
.main{
width:940px; padding:20px; margin:0 auto;
}
label{
margin-right:4px;
}
#todos>li{
cursor:pointer;
}
<!DOCTYPE html>
<html xmlns='http://www.w3.org/1999/xhtml' xml:lang='en' lang='en'>
<head>
<meta http-equiv='content-type' content='text/html;charset=utf-8' />
<meta name='viewport' content='width=device-width' />
<title>Add Remove to List - jQuery</title>
<link type='text/css' rel='stylesheet' href='css/external.css' />
<script type='text/javascript' src='https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js'></script>
<script type='text/javascript' src='external.js'></script>
</head>
<body>
<div class='main'>
<form id='frm' name='frm'>
<label for='todo'>New To Do</label><input id='todo' name='todo' type='text' /><input id='add' name='add' type='button' value='add' /><input id='rmv' name='rmv' type='button' value='remove' />
<ol id='todos'></ol>
</form>
</div>
</body>
</html>
It the New To Do input (without the quotes, of course): Type "Go to the Store". Hit Enter. Type "Do my Hair". Hit Enter. Type "Go on a Bike Ride". Hit Enter. Click on the list now where you want to remove then press the remove button. If it was an accident, you can press add again, but focusing on the input clears the text, for your next input, with this design. It's also form ready for database implementation.

JQuery .attr('disabled',true) not working in chrome

I tried some methods in old questions but it is not working in chrome.
Can please any one suggest me the solution.i'm using php for validation.
if i click submit button twice it through an error so restrict the issue i disable the submit button but it not working in chrome.
<script>
jQuery(document).ready(function () {
jQuery('#submit_button').click(function () {
jQuery('#submit_button').attr('disabled','disabled');
});
});
</script>
You could use prop jquery method, or just set the disabled attribute to true.
$(document).ready(function(){
$('#submit').on('click', function(e){
//$(this).prop('disabled', true);
this.disabled = true;
})
});
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width">
<title>JS Bin</title>
</head>
<body>
<button id="submit">submit</button>
<script src="https://code.jquery.com/jquery-3.1.0.js"></script>
</body>
</html>
It could be that there are multiple submit buttons on the page. You can try using this code.
jQuery(document).ready(function () {
jQuery('#submit_button').click(function () {
// It is best practice to use `true` instead of
// any true-y kind of value like non-empty string.
jQuery(this).attr('disabled', true);
});
});
There are different ideas were given but the code seems working properly. Please make sure you imported the jQuery library.
The following code is the tested code.
<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
<script>
jQuery(document).ready(function () {
jQuery('#button').click(function () {
jQuery('#button').attr('disabled','disabled');
});
});
</script>
</head>
<body>
<input type="submit" id="button" value="If you click on me, I will be disabled."/>
</body>
</html>
Try, using the prop of element and making the attribute true, using
jQuery('selector').prop('disabled',true);
<script>
jQuery(document).ready(function () {
jQuery('#submit_button').click(function () {
jQuery('#submit_button').prop('disabled',true);
});
});
</script>
how i would add disabled:
<script>
$(document).ready(function(){
$('button').click(function () {
$('<input type="button id="submit_button" disabled>').insertBefore(this);
$(this).remove();
});
});
</script>
how i would change the button back to normal:
<script>
$(document).ready(function(){
$('button').click(function () {
$('<input type="button id="submit_button" >').insertBefore(this);
$(this).remove();
});
});
</script>
you can use $('selector').prop('disabled',true);

Submitting the closest form without a submit button?

I have page with many forms consisting of only a textarea and a hidden field with an id
I am trying to use jQuery to submit the form each time the user enters some text and hits command+enter on the keyboard.
For that I am using
$('textarea').keydown(function(e) {
if(e.keyCode == 13 && e.metaKey) {
That part works fine, but then when I try to submit my form the script stops execution. I am sure I am doing some mess with the closest('form') submit.
Here is my full code
$('textarea').keydown(function(e) {
if(e.keyCode == 13 && e.metaKey) {
$('textarea').closest('form').submit(function() {
$.post("someurl.php", $(this).serialize(), function(data) {
alert(data);
});
});
};
});
When I debug it never enters inside the $('textarea').closest('form').submit(function() {
Any idea how can I pass the content of the form for which command+enter was entered to my processing URL?
Any tips will be appreciated,
Thanks
UPDATE
HTML code for the forms
<form action="#">
<div class="col-xs-1">
<textarea class="form-control" rows="5" placeholder="Enter your answer"></textarea>
<input type="hidden" name="idval" value="xxxx">
</div>
</form>
EDIT 2
While debugging the code I see that the parameters are correctly passed but at one point jquery loses the values.
What is even stranger is that the fiddle posted below works fine in fiddle, but when I download the code and test it on my localhost it doesn't.
Here is the code
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="content-type" content="text/html; charset=UTF-8">
<meta name="robots" content="noindex, nofollow">
<meta name="googlebot" content="noindex, nofollow">
<script
src="https://code.jquery.com/jquery-2.2.4.js"
integrity="sha256-iT6Q9iMJYuQiMWNd9lDyBUStIq/8PuOW33aOqmvFpqI="
crossorigin="anonymous"></script>
<style type="text/css">
</style>
<title> by b</title>
<script type='text/javascript'>//<![CDATA[
window.onload=function(){
$('textarea').keydown(function(e) {
if(e.keyCode == 13 && e.metaKey) {
// e.preventDefault();
$.post($(this).closest("form").attr("action"), { html: $(this).closest("form").serialize()}, function(data) {
alert(data);
});
}
});
}//]]>
</script>
</head>
<body>
<form action="#">
<textarea name="area1"></textarea>
</form>
<form action="#">
<textarea name="area2"></textarea>
</form>
</body>
</html>
any clues?
You shouldn't define an event handler inside another event handler. You should just post the current form.
$('textarea').keydown(function(e) {
if(e.keyCode == 13 && e.metaKey) {
$.post($(this).closest("form").attr("action"), $(this).closest("form").serialize(), function(data) {
alert(data);
});
}
});

Categories