Check input elements responsively when changed - javascript

I have this code. It obviously calls function when selected element is focused. The function then checks if selected element has length less than 3, and if it does it changes background color of the element.
$('#register-form input[type="text"]').focus(function(){
if ($(this).length < 3) {
$(this).css('background','#f00');
}
});
Now the problem is that when there are more than 4 characters within input, color still remains. The problem is that it calls function when element is focused. After that, it doesn't check the if statement anymore, as obviosuly function is never called again.
The solution I seek; I want it to check if the IF statement is still legit once the input element value is changed. Or any other smooth way to check IF statements and calls functions in a live time.
The answer to this question is simple and well known. However, as you answer please provide some information related to this question; What are the best ways to check various changes in statements lively? What are the best ways to make website 'alive' and respond to any actions immediately?

Give the error a class and use onkeyup (and change if you wish - which triggers on blur too)
Also test the .val().length instead:
<style>
.error { background-color:red }
</style>
$('#register-form input[type="text"]').on("keyup,change",function(){
$(this).toggleClass("error", $(this).val().length < 3);
}).keyup(); // trigger on load
$(function() {
$('#register_form input[type="text"]').on("keyup", function() {
$(this).toggleClass("error", $(this).val().length < 3);
console.log("error")
}).keyup(); // initialise in case of reload
});
.error {
color: red
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<form id="register_form">
<input type="text" />
<input type="text" />
<input type="text" />
</form>

Try this:
$('#register-form input[type="text"]').on("focus input", function(){
$(this).css('background', $(this).val().length < 3 ? '#f00' : '#fff');
});
EDIT
Personally, I use AngularJS alot for web applications that have alot of these. E.g. you can do this:
<input type="text" ng-model="myValue" ng-style="{'background-color', myValue.length < 3 ? '#f00' : '#fff'}"/>

Related

hide sign in form after 10s if cookie not set and no inputs are selected

I'm developing a little function for my site where a sign in form is automatically shown in the navbar when the site is opened up, but only if a certain cookie has not been set. Then, after 10 seconds has passed, the form will disappear.
It is also supposed to stay open if the user has selected one of the form inputs OR if one of the inputs contain contents. (#user-pest or #pass-pest).
Most of it is working the way it is supposed to, however, even when one of the inputs is selected or contains contents, once 10 seconds has passed, the form will disappear from the page.
The following is the JavaScript (and jQuery) code that I am using (updated).
$(document).ready(function(){
// hide sign in form
function hideForm(){ // function for updating elements
$("#darknet-login-nav").css("display", "none");
$(".index-outer").css("height", "100px");
$(".index-inner").css("width", "438px");
$(".index-inner").css("top", "-10px");
$("#darknet-mast").css("font-size", "97px");
}
function hideFormSet(){ // function used for updating elements and setting cookie
hideForm();
document.cookie = "signinNav=set";
}
var checkDisplayed = getCookie("signinNav"); // get cookie contents
if(checkDisplayed == "set"){
hideForm(); // if cookie is set, hide the form
} else { // if it isn't
var hideInterval = setInterval(hideFormSet, 10000); // after 10 seconds, call hideFormSet function
if($("#user-pest").is(':focus') || $("#pass-pest").is(':focus')){
clearInterval(hideInterval); // if one of the inputs are focused on, stop the interval
} else {
hideInterval; // if they aren't focused, start the interval
}
}
});
and this is my simplified markup.
<div class="darknet-nav-login-form" id="darknet-login-nav">
<form action="" method="post">
<input type="text" name="username" id="user-pest" placeholder="Username" autocomplete="off"><br>
<input type="password" name="password" id="pass-pest" placeholder="Password" autocomplete="off"><br>
</form>
</div>
I'm still very new to JavaScript, so any pointers and fixes will be greatly appreciated.
EDIT: please check my above updated code.
Even when on of the inputs are focused, the interval will still continue, rather than stopping.
Thanks
If I understand your goal correctly, you also want to hide the form 10 seconds after the inputs lose focus.
In that case it's easier to bind to the focusin/focusout events to restart the timeout, otherwise when leaving an input just before the interval fires it is hidden much earlier than the timeout.
var inputs = $('#user-pest, #pass-pest'),
hideTimeout,
checkFocus = function(){
var hide = !inputs.is(':focus');
if(hide===!!hideTimeout)return;
if(hide)
hideTimeout = setTimeout(hideFormSet, 10000);
else
hideTimeout = clearTimeout(hideTimeout);
};
inputs.focusin(checkFocus).focusout(checkFocus);
checkFocus();
Sidenote, jQuery's is method checks if any of the elements in the jq array corresponds to the selector, so instead of a separate and/or, you can do: $('#user-pest, #pass-pest').is(':focus')
example Fiddle
Sidenote2, the (re)binding will occur twice because one input loses focus before the next one gains focus. This is not a problem in itself, but if the form only contains those 2 inputs, using event bubbling to check focus on the form itself might be one little step further optimized: inputs.parent().focusin(checkFocus).focusout(checkFocus);
You need an && in this line.
if(!$("#user-pest").is(':focus') || !$("#pass-pest").is(':focus')){
What you had before was
if( user-pest is not focused OR pass-pest is not focused)
A user can't focus both of them at once, thus this will always evaluate to true and hide will be set to true. Use the following:
if(!$("#user-pest").is(':focus') && !$("#pass-pest").is(':focus')){
Alternatively you could also use the following
if($("#user-pest").is(':focus') || $("#pass-pest").is(':focus')){
var hide = false;
} else {
var hide = true;
}
As pointed out in your comment there is also another problem, which I missed the first time.
The hide variable is set on page load, which happens instantly, and you most likely won't have had the time to focus either object yet. You should move the code that checks if it's focused to inside the timeout callback.
See this jsFiddle for the full code of a working example. Basically your timeout should check if the inputs are focused when run, not on page load, as seen in the following snippet.
setTimeout(function() {
if (!$("#user-pest").is(':focus') && !$("#pass-pest").is(':focus')) {
$("#darknet-login-nav").css("display", "none");
$(".index-outer").css("height", "100px");
$(".index-inner").css("width", "438px");
$(".index-inner").css("top", "-10px");
$("#darknet-mast").css("font-size", "97px");
document.cookie = "signinNav=set"; // set the cookie so the form doesn't appear when they come back later
}
}, 2000);
Here's a solution which ensures that the inputs are each empty and that they're not focused. Behaviour beyond the initial 10s timeout wasn't specified, so I've left the interval active - the hide behaviour will be invoked any time the timeout elapses and the conditions for hiding the header are met.
If you wish to make it a 'one-shot' timer, simply clearInterval in the intervalHandler function.
window.addEventListener('load', onDocLoaded, false);
var intervalHandle;
function onDocLoaded(evt)
{
intervalHandle = setInterval(intervalHandler, 2000);
}
function hideHeader()
{
document.getElementById('darknet-login-nav').classList.add('hidden');
}
// returns true/false
// true if the header should be hidden, false otherwise.
// Things that will prevent the header from being hidden area
// 0) content in the #user-pest input
// 1) content in the #pass-pest input
// 2) focus of either #user-pest or #pass-pest elements
function shouldHideHeader()
{
if (document.getElementById('user-pest').value != '')
return false;
if (document.getElementById('pass-pest').value != '')
return false;
if (document.activeElement == document.getElementById('user-pest'))
return false;
if (document.activeElement == document.getElementById('pass-pest'))
return false;
return true;
}
function intervalHandler()
{
if (shouldHideHeader())
hideHeader();
}
.darknet-nav-login-form
{
height: 42px;
}
.hidden
{
height: 0px;
overflow: hidden;
transition: height 2s;
}
<div class="darknet-nav-login-form" id="darknet-login-nav">
<form action="" method="post">
<input type="text" name="username" id="user-pest" placeholder="Username" autocomplete="off"/><br>
<input type="password" name="password" id="pass-pest" placeholder="Password" autocomplete="off"/><br>
</form>
</div>

Multiple conditions on single checkbox

I wanted to have a single checkbox in a form but i need to implement multiple scenarios but not sure if this is possible using a single checkbox or if i need radio buttons . Please advise
box shown and checked: Accepted / yes
(hidden)Box shown and not checked: Declined / no
Box not shown: Not Shown / blank
not sure if this is possible using a single checkbox
box shown and checked: Accepted / yes
(hidden)Box shown and not checked: Declined / no
Box not shown: Not Shown / blank
if the requirements 1/2/3 can be met using a single checkbox .The reason i ask is a single checkbox can hold only one value and if there is a way i can alter the value in Jquery dynamically still satisfying all the requirements.
Yes, it is possible. You can create an object having properties set to selectors :checked, :not(:checked, :hidden), :hidden; with corresponding values set to yes, no, blank. Set variable at change event handler using for..in loop, .is()
var obj = {
":checked": "yes",
":not(:checked, :hidden)": "no",
":hidden": "blank"
};
var curr;
$(":checkbox").change(function() {
for (var prop in obj) {
if ($(this).is(prop)) {
curr = obj[prop]; break;
}
}
// do stuff with `curr`
console.log(curr);
});
// check `:hidden`
$(":checkbox").prop("hidden", true)
.change() // `curr` should log `blank`
.prop("hidden", false);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js">
</script>
<input type="checkbox" />
I have created one sample onchange function where you can handle mutiple events
codepen URL for reference:
http://codepen.io/nagasai/pen/xOGNYW
<input type="checkbox" id="checkTest" onchange="myFunction()">
<input type="text" id="myText" value="checked">
#myText
{
display:none;
}
function myFunction() {
if (document.getElementById("checkTest").checked) {
document.getElementById("myText").style.display = "block";
} else {
document.getElementById("myText").style.display = "none";
}
}

Animated form, how to check input value on page refresh?

I have a form which uses dynamic styling. Consider this html
<div class="field-name field-form-item">
<label class="placeholder" for="name">Name</label>
<input class="form-input" id="name" type="text" name="name" maxlength="50" size="30">
</div>
The label is ABOVE the input, with CSS. When you click the label :
$('.placeholder').on('click focus', function() {
$(this).addClass('ph-activated');
$(this).siblings('input').focus();
})
Then the label is animated and let the user type in the input.
If the user dont wan't to write anything, the animation goes back, and hide input field :
$('input').on(' blur', function(){
if ($(this).val().length === 0) {
$(this).siblings('label').removeClass('ph-activated');
}
});
That's alright.
But when a user fill the input, THEN refresh the page and its browser didn't reset input fields(ie firefox) : the label is above the input, even if the latter is not empty.
I tried this :
$(document).ready(function() {
if ($('input').val().length) {
$(this).siblings('label').addClass('ph-activated');
}
})
But it doesn't seem to trigger, I tried several ways to write this function. Up to now I never managed to give the class ph-activated to a label with a filled input on page refresh.
Sorry I can't fiddle this. I just have far too much html/css/js/php to copy paste
Well you are targeting wrong element in $(document).ready because you are referring label with this thinking that $(this) is input whereas it is document. So try applying below code and I hope there will be multiple input elements in page, so I've used $.each and looping through all the inputs
$(document).ready(function() {
$('input').each(function(){ //loop through each inputs
if ($(this).val().length) {
$(this).siblings('label').addClass('ph-activated');
}
});
})
DEMO - Inspect the label and you will find ph-activated class added to label
Try this one:
$(document).ready(function() {
var length = $('input').filter(function( index ) {
return ($(this).val() !== '');
}).length;
if (length > 0) {
$(this).siblings('label').addClass('ph-activated');
}
})

Auto capitalization of input and TextArea Fields [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 8 years ago.
Improve this question
I have my input Field and is using onKeyup and onKeyPress to return number & characters and then to move to the next field.
<input name="aendcodeM" id="aendcodeM" type="text" size="25" maxlength="4" onKeyPress="return numchar(event)" onKeyup="autotab(this, document.form1.bendcodeM)"/>
<input name="bendcodeM" id="bendcodeM" type="text" size="25" maxlength="4" onKeyPress="return numchar(event)" onKeyup="autotab(this, document.form1.bndwdM)"/>
I am trying to use feature of auto-capitalization also for which the code witten as -
<script type="text/javascript" src="js/jquery.min.js"></script>
<script>
$(document).ready(function() {
$("input").keyup(function() {
var val = $(this).val()
$(this).val(val.toUpperCase())
})
})
</script>
<script>
$(document).ready(function() {
$("textarea").keyup(function() {
var val = $(this).val()
$(this).val(val.toUpperCase())
})
})
</script>
<script>
$(input[type="text"]).on('keypress', function() {
var $this = $(this), value = $this.val();
if (value.length === 1) {
$this.val( value.charAt(0).toUpperCase() );
}
});
</script>
But is of no use since the characters not getting automatically capitalized as desire. Any help in this regard is obliged please.
Thanks & Reagrds
Use css text-transform: uppercase for your input's text & textarea elements as:
input, textarea{
text-transform: uppercase;
}
This will work for you.
Many errors in your code:
why calling function when it isn't initialized?
Uncaught ReferenceError: autotab is not defined error in demo.
<input name="aendcodeM" id="aendcodeM" type="text" size="25" maxlength="4" onKeyPress="return numchar(event)" onKeyup="autotab(this, document.form1.bendcodeM)"/>
^^^^^ ^^^^
Here also ' is missing:
$('input[type="text"]').on('keypress', function() {
^ ^
Working DEMO
How to check Error in console
You should be using only one $(document).ready( ... ) in your Javascript.
Working demo of your code (fixed)
JS:
$(document).ready(function() {
$("input, textarea").keyup(function() {
var val = $(this).val()
$(this).val(val.toUpperCase());
});
$('input[type="text"]').on('keypress', function() {
var $this = $(this), value = $this.val();
if (value.length === 1) {
$this.val( value.charAt(0).toUpperCase() );
}
});
});
Check the demo
Jquery Code
$('[type=text]').keyup(function(){
if($(this).val()!=''){
$(this).val( $(this).val().toUpperCase());
}
});
Doing it that way is unnecessary. I strongly suggest you force uppercase by using the text-transform CSS property.
CSS
input{
text-transform: uppercase;
}
This will force clients to render text in uppercase at all times.
However
Be careful as the values are not. When you proccess your action it is important at that point you convert your value to uppercase either client side or server side.
try this
$( "#aendcodeM" ).bind( "input", function() {
$("#aendcodeM").val($("#aendcodeM").val().toUpperCase());
});
two things
You have to put semi-colon and also check if this is pointing properly
var val = $(this).val();//notice semicolon here
$(this).val(val.toUpperCase());//notice semicolon here
Here is your problem. You need to understand the concepts better. You are trying to register event handler both in javascript and jquery. autocad and numchar functions are not defined and since these are event handlers using javscript, when they get hit it wont work.
Find below the code and also check with this fiddle http://jsfiddle.net/wishy/qbfkhz88/
<input name="aendcodeM" id="aendcodeM" type="text" size="25" maxlength="4" />
<input name="bendcodeM" id="bendcodeM" type="text" size="25" maxlength="4" />
and javascript is
$(document).ready(function() {
$("input").keyup(function() {
var val = $(this).val();
$(this).val(val.toUpperCase());
});
});
$("textarea").keyup(function() {
var valtext = $(this).val()
$(this).val(valtext.toUpperCase())
});
Demo
The above code is works on all the textarea of the page.Firstly we will take take the value of textarea where user is start typing then make it Upper case using inbuilt function of jquery and assign to the textarea.
Sometimes i found that when you use variable name same as function name or same as any keyword, then it throws error
so try to do one thing. Also use ids.
$(document).ready(function() {
$("#text_area").keyup(function() {
var valtext = $(this).val()
$(this).val(valtext.toUpperCase())
})
})
Just have a test with this. May be this is the scenario happening on your case
Also use ids.
see the fiddle http://jsfiddle.net/36bqfms6/

Hiding Drop Down Boxes if Radio Button other than default is Clicked

I swear I'm going to learn more JavaScript...
I have this page (which really an include file in another ASP page, but I copied the correct HTML and made it so it'd load by itself for my testing purposes):
FO Samples
This is how it should show when they first load it. If they choose one of the other radio buttons, it should HIDE the 2 dropdown boxes. Using this code (something I found from someone else's question on here), its working.
<script type="text/javascript">
function ChangeDropdowns(value) {
if (value == "0") {
document.getElementById('SAMPLEDROPDOWN').style.display = 'block';
}
else {
document.getElementById('SAMPLEDROPDOWN').style.display = 'none';
}
}
</script>
But I can't figure out how to make it show them again if they go back to the "I wanna pick my own!" radio. The value of SAMPGROUP is the ID from the database of that sample category group. So it won't necessarily be in numerical order, it might skip #'s (if we delete a category or something). Basically, it should show the dropdowns if SAMPGROUP = 0 and not if its anything else!
I tried changing my code to this (95 being the value of SAMPGROUP for the "Autumm" option), but it doesn't seem to have made a difference.
<script type="text/javascript">
function ChangeDropdowns(value) {
if (value == "0") {
document.getElementById('SAMPLEDROPDOWN').style.display = 'block';
} else if (value == "95") {
document.getElementById('SAMPLEDROPDOWN').style.display = 'none';
}
else {
document.getElementById('SAMPLEDROPDOWN').style.display = 'none';
}
}
</script>
Any help would be greatly appreciated!!
Mahalo!
You are not setting the "value" in your onchange event, thus it's never equal to 0. Try changing this:
<input type="radio" name="SAMPGROUP" value="0" OnChange="Javascript:ChangeDropdowns()" checked />
to
<input type="radio" name="SAMPGROUP" value="0" OnChange="Javascript:ChangeDropdowns(0)" checked />
Here is the fiddle.
Good luck.
You may not be passing any value to the parameter "value" on calling the function ChangeDropdowns. Please ensure you pass the value like ChangeDropdowns(0) etc..

Categories

Resources