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>
Related
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();
}
});
});
In registration form I have a 2 radio button, when one button is selected a dropdown list appears. But after register fails, the selected radio button remains but the dropdown list is not shown anymore, I want the dropdown list to be shown after register fail. There should be a solution with local storage but I dont know exactly how to write it.
here is the code, what I should add to make it happen?
$(document).ready(function() {
$('input[type=radio][name=rdUserType]').change(function() {
if (this.value == '1') {
$('#cityClient').show();
$('#cityLawyer').hide();
}
else if (this.value == '0') {
$('#cityClient').hide();
$('#cityLawyer').show();
}
});
});
So I found the solution finally, I tried and made it :
<script>
$(document).ready(function() {
$('input[type=radio][name=rdUserType]').change(function() {
if (this.value == '1') {
$('#cityClient').show();
$('#cityLawyer').hide();
}
else if (this.value == '0') {
$('#cityClient').hide();
$('#cityLawyer').show();
}
localStorage.removeItem("last");
});
});
function fix(){
var check = localStorage.getItem("last");
console.log(check);
if (check === 'a') {
$('#cityClient').hide();
$('#cityLawyer').show();
}
else{
$('#cityClient').show();
$('#cityLawyer').hide();
}
}
function save(){
// rdAttorney is a id of the selected radio
if (document.getElementById('rdAttorney').checked) {
localStorage.setItem('last', 'a');
}
else{
localStorage.setItem('last', 'b');
}
}
window.onload = fix();
</script>
so I tried making a simple on change fiddle. I can't get it to work. No matter what I do. WHY?
HTML CODE
<div id="status" style="display:none">0</div>
<button class="start">GO</button>
Javascript CODE
var cntTo = 2;
var cnt = 0;
$('#status').change( function() {
console.log('status changed');
if ($(this).text() == '1'){
if(cnt <= cntTo){
getNext(cnt);
}
}
});
$('.start').click(function(){
console.log('start clicked');
console.log('text of status now: ' + $('#status').text());
if($('#status').text() != '1'){
console.log('setting text');
$('#status').text('1');
console.log('text of status now: ' +$('#status').text());
}
});
function getNext(cnt){
$('#status').text('0');
console.log('getting details');
}
https://jsfiddle.net/hakz47vg/
The .change() function is limited to input, textarea, and select.
Source: https://api.jquery.com/change/
Use this
$('#status').bind("DOMSubtreeModified",function(){
var cntTo = 2;
var cnt = 0;
$(document).ready(function() {
$('.start').click(function() {
if ($('#status').text() != '1') {
$('#status').text('1');
}
});
$('#status').bind("DOMSubtreeModified",function(){
console.log('fired');
if ($(this).text() == '1') {
if (cnt <= cntTo) {
getNext(cnt);
}
}
});
});
function getNext(cnt) {
$('#status').text('0');
console.log('getting details');
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="status" style="">0</div>
<button class="start">GO</button>
You can embed onchange function code directly with GO button click event like this:
$('.start').click(function(){
if($('#status').text() != '1'){
$('#status').text('1');
}
else
{
if(cnt <= cntTo){
getNext(cnt);
}
}
});
You are using change event which does not watch or respond to div content.Use DOMSubtreeModified event and trigger action on that event.
var cntTo = 2;
var cnt = 0;
$('#status').on("DOMSubtreeModified", function() {
if ($(this).text() == '1') {
if (cnt <= cntTo) {
getNext(cnt);
}
}
});
$('.start').click(function() {
if ($('#status').text() != '1') {
console.log('setting text');
$('#status').text('1');
console.log('text of status now: ' + $('#status').text());
}
});
function getNext(cnt) {
$('#status').text('0');
console.log('getting details');
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="status" style="display:none">0</div>
<button class="start">GO</button>
If you want to do some action when the content modified inside the div element you have to use the event called DOMSubtreeModified like below.
$("body").on('DOMSubtreeModified', "#status", function() {
UPDATED FIDDLE
Reference:
For more information read out the thread already discussed about this in stack overflow.
jQuery Event : Detect changes to the html/text of a div
Use DOMSubtreeModified event
DOMSubtreeModified This is a general event for notification of all changes to the document. It can be used instead of the more specific mutation and mutation name events. Reference
$('#status').bind("DOMSubtreeModified",function(){
alert('changed');
});
Working fiddle
another simple solution
when text in #text changes in script fires a trigger and you can bind it to change event
var cntTo = 2;
var cnt = 0;
$('#status').bind('change', function () {
console.log('fired');
if ($(this).text() == '1'){
if(cnt <= cntTo){
getNext(cnt);
}
}
});
$('.start').click(function(){
if($('#status').text() != '1'){
$('#status').text('1');
$('#status').trigger('change');
}
});
function getNext(cnt){
$('#status').text('0');
console.log('getting details');
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="status" style="display:none">0</div>
<button class="start">GO</button>
$("start").click function put inside in ready Function
I have just begun my exploration of javascript and jquery, and would sincerely appreciate any help with my current dilemma. The feature that I am trying to build involves a number of steps:
The 'enter' key triggers an event.
The appropriate value ('About', 'Contact', or 'Extra') within the input field will open a new page.
The input field (residing within a <p> element) is then cloned and inserted, allowing the user to input another value.
My dilemma involves binding. Once the input field has been cloned, the page that was first opened will continue to open regardless of a new input value. Meaning, if the 'About' page was first opened, then the 'About' page will continue to open even when a new value ('Contact' or 'Extra') is added to the inserted input field. Here is the code that I have written:
javascript
$(function() {
function cloneInput() {
var clonedElement = $("p").last().clone(true);
$("input").last().prop("disabled", true);
clonedElement.insertAfter($("p").last()).prop("id", "seven");
$("input").last().prop("value", "").focus();
}
$("#input-text").keydown(function(event) {
var keypressed = event.keyCode || event.which;
var text = $("#input-text").val();
if (keypressed == 13) {
if (text == "About") {
window.open("about.html", "_blank");
cloneInput();
} else if (text == "Contact") {
window.open("contact.html", "_blank");
cloneInput();
} else if (text == "Extra") {
window.open("extra.html", "_blank");
cloneInput();
} else {
$("<p>Command not found</p>").insertAfter("#six").prop("id", "error");
}
}
});
});
html
<!DOCTYPE html>
<html>
<head>
<link href="css/stylesheet.css" type="text/css" rel="stylesheet"/>
<script src="js/jquery-3.1.0.js"></script>
<script src="js/scripts.js"></script>
</head>
<body id="index-body">
<p id="one">Hello friend. My name is $%^&*$^%. Welcome to ##$%%%*&.</p>
<p id="two">To learn more, please enter a command:</p>
<p id="three">> About</p>
<p id="four">> Contact</p>
<p id="five">> Extra</p>
<p id="six">> %<input type="text" maxlength="40" autofocus id="input-text"></p>
</body>
</html>
result
<p id="six">
<input type="text" maxlength="40" autofocus id="input-text" disabled>
</p>
<p id="seven">
<input type="text" maxlength="40" autofocus id="input-text">
</p>
I have searched stackoverflow and learned about .on(), .off(), and .change(). In addition, I have utilized these methods when refactoring my code. Still, I cannot find a solution. Thank you in advance.
Note: I am aware that my naming conventions need to be cleaned up.
bind your event on document itself not on the element you want to trigger
$(document).on('keydown', "#input-text", function(event) {
e.preventDefault();
// all your code..
});
see my other answer.
If you want to call a function on dynamically created elements, you should use
$(document).on(<event>, <object>, function(event) {
});
Example : This will perform the action on clicking the elements with class class1 ( even on dynamically created elements )
$(document).on('click', '.class1', function(event) {
/* do something here */
});
In your case :
$(document).on("click", "#input-text", function(event) {
var keypressed = event.keyCode || event.which;
var text = $("#input-text").val();
if (keypressed == 13) {
if (text == "About") {
window.open("about.html", "_blank");
cloneInput();
} else if (text == "Contact") {
window.open("contact.html", "_blank");
cloneInput();
} else if (text == "Extra") {
window.open("extra.html", "_blank");
cloneInput();
} else {
$("<p>Command not found</p>").insertAfter("#six").prop("id", "error");
}
}
});
Everything is looking good only one issue is accessing filed value instead of $('#input-text').val() use $(this).val() always gets current element value..
$(function() {
function cloneInput() {
var clonedElement = $("p").last().clone(true);
$("input").last().prop("disabled", true);
clonedElement.insertAfter($("p").last()).prop("id", "seven");
$("input").last().prop("value", "").focus();
}
$("#input-text").keydown(function(event) {
var keypressed = event.keyCode || event.which;
var text = $(this).val();
if (keypressed == 13) {
if (text == "About") {
window.open("about.html", "_blank");
cloneInput();
} else if (text == "Contact") {
window.open("contact.html", "_blank");
cloneInput();
} else if (text == "Extra") {
window.open("extra.html", "_blank");
cloneInput();
} else {
$("<p>Command not found</p>").insertAfter("#six").prop("id", "error");
}
}
});
});
I have a keyup function on my script and when I type into one of my text boxes it triggers my hotkey which hides the text box so it makes it impossible to type in it. Please help.
$(document).keyup(function(e){
if(e.which == 67){
if($('#main').css('opacity') == 0) {
$("#cHideChat").click();
}
}
});
I want something like this but I don't know the right word to put here.
$(document).keyup(function(e){
if(e.which == 67){
if($("#chat-input").is("clickedOn")){
return false;
}
else{
if($('#main').css('opacity') == 0) {
$("#cHideChat").click();
}
}
}
});
you can do it by checking the active element in jquery . The code should be like $(document.activeElement).attr("type") == "text" || $(document.activeElement).attr("id") == "chat-input")
Please let me know if it solves your problem
Try the following:
$(document).keyup(function(e) {
if(e.which == 67){
if (e.target.id == "chat-input") {
return false;
}
}
else {
if ($('#main').css('opacity') == 0) {
$("#cHideChat").click();
}
}
}
});