I want my input always has value so that focus is fixed to it until the values are typed and the cursor also can't escape the input.
I know the focus() function is existed but how can i deal with it? It is just an event isn't it? Is there any solution?
This is the html code which include the input.
<div class="col-xs-3 vcenter from-group" id="info">
<div class="form-group">
<label class="control-label" for="inputID">아이디</label><p style="display:inline; padding-left:60px; color:red; font-size: 12px">* 적어도 하나의 대문자, 소문자, 숫자를 포함한 6자~16자</p>
<div class="controls">
<input type="text" class="form-control" name="inputID" id="inputID" placeholder="내용을 입력해 주세요" required autofocus>
</div>
</div>
This is the script where the input is bound the events.
<script>
jQuery('#inputID').keyup(blank_special_char_validation);
jQuery('#inputID').focusout(function(){
if (!$(this).val()) {
var message = "no id";
error(this.id, message); // ** TODO : SET FOCUS HERE !!
} else {
id_form_validation(this.id);
}
});
Could you guys see the **TODO in code above? I want to add function that the focus is fixed until the value is written.
Please could guys give me some idea. Thank you.
=========================================================================
I want to focus my input depends on situation. For example, I want to focus it when the value isn't existed or the validation doesn't correct. However it has to focus out when the value is existed or the validation is true.
I can set focus it finally but how can i unfocus it? I mean i want to untrigger the focus event.
jQuery('#inputID').on('blur',function(){
if (!$(this).val()) {
var message = "아이디를 입력해 주세요";
error(this.id, message);
$(this).focus();
} else {
//$(this).focus();
if (!id_form_validation(this.id)) {
$(this).focus(); // TODO : FOCUS
}else {
$(this).off('focus'); // TODO : FOCUS OUT
$(this).off('blur');
}
}
});
You can use this code to do the same... I have used blur
//jQuery('#inputID').keyup(blank_special_char_validation);
jQuery('#inputID').focusout(function() {
if (!$(this).val()) {
$(this).focus();
var message = "no id";
error(this.id, message);
}else {
id_form_validation(this.id);
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="col-xs-3 vcenter from-group" id="info">
<div class="form-group">
<label class="control-label" for="inputID">아이디</label><p style="display:inline; padding-left:60px; color:red; font-size: 12px">* 적어도 하나의 대문자, 소문자, 숫자를 포함한 6자~16자</p>
<div class="controls">
<input type="text" class="form-control" name="inputID" id="inputID" placeholder="내용을 입력해 주세요" required autofocus>
</div>
</div>
Use $(this).focus() to focus your input.
focus() with no arguments will trigger that event on an element.
Related
What I am trying to achieve is track 20 inputs, if one is filled I want to add a class to a parent div of this input, if it becomes empty after I want the class to remove itself from the parent. This code does what I want when I run it in the console, how can I improve it so it can track the inputs and toggle the class?
$('.input').each(function() {
var $input = $(this);
if ($input.val()) {
var $parent = $input.closest('.card');
$parent.addClass('colored')
}
});
You can use an event to do so. For inputs, jQuery has the input event that fires every time the value of an input changes.
$(".input").on("input", function () {
if ($(this).val().length === 0)
$(this).closest('.card').removeClass("colored");
else
$(this).closest('.card').addClass("colored");
});
Your code checks for values at the initial run. You would need to attach events copy, paste, change, keypress, keydown, keyup and input. See example:
$('input').on('copy paste keydown keyup keypress change input', function(){
var $input = $(this);
if( $input.val() == '' ){
$input.parent('.form-group').addClass('empty');
} else {
$input.parent('.form-group').removeClass('empty');
}
});
.form-group {
margin-bottom:10px;
}
.form-group.empty > input {
border:2px solid red;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="form-group">
<input name="name" type="text" placeholder="name"/>
</div>
<div class="form-group">
<input name="email" type="text" placeholder="email"/>
</div>
<div class="form-group">
<input name="address" type="text" placeholder="address"/>
</div>
This is the snippet Here. An keyup() function and an if check done them all.
$("input[type='text']").on("keyup",function(){
if($(this).val()!="")
{
$(this).parent().addClass("active");
}else{
$(this).parent().removeClass("active");
}
})
.active{
background-color:red;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div>
<input type="text" >
</div>
Thank you all for the answers, this is what worked for me after trying all the solutions. Hope it helps someone else.
function checkInputs() {
$('.input').each(function(){
if($(this).val() === ""){
$(this).parent().parent('.unit-card').removeClass('filled');
} else {
$(this).parent().parent('.unit-card').addClass('filled');
}
});
}
I have a modal with ~20 input and select fields that the user is supposed to complete. I would like to a quick JavaScript check whether the field is empty or not after the user is navigating away / changing / etc. the field, but want to avoid having to copy paste the code below 20 times and personalize it for each field.
<!-- Holidex -->
<label>Holidex:</label>
<div class="input-group">
<span class="input-group-addon"><i class="fa fa-bars"></i></span>
<input type="text" class="form-control" maxlength="5" placeholder="What is your Holidex code?" id="addHolidex" name="addHolidex" style="text-transform:uppercase" />
</div>
<!-- /.Holidex -->
<script type="text/javascript">
$('#addHolidex').on('keyup keydown keypress change paste', function() {
if ($(this).val() == '') {
$('#addHolidex').removeClass('has-success').addClass('has-warning');
} else {
$('#addHolidex').addClass('has-success').removeClass('has-warning');
}
});
</script>
Is there any way to have the code above check for any select / input field on my NewUserModal?
Thank you!
EDIT
So I fiddled around with the suggested codes below but only the following managed to halfway work:
$('.input-group').on('keyup keydown keypress change paste', function() {
if ($(this).val() == '') {
$(this).removeClass('has-success').addClass('has-error');
} else {
$(this).addClass('has-success').removeClass('has-error');
}
});
Empty fields are being flagged correctly now, but fields with content do not have the has-success class added. Note that I have to apply this class to the <div class="input-group"> element instead of the input select fields.
Any suggestions? I am running on bootstrap 3 if that helps.
EDIT 2
Still no result and quite frankly have had enough for today.
- select fields are either ignored or incorrectly flagged with has-error if pre-populated
- individual input fields seem to work more or less
- grouped input fields nestled in one div all turn red if one field is empty (eg. phone number + phone country both turn red of there is not country code entered)
// highlight empty fields in red
$('.input-group input, select').on('keyup keydown keypress change paste',function(){
if ($(this).val() == '') {
$(this).parent().closest('.input-group').removeClass('has-success').addClass('has-error');
} else {
$(this).parent().closest('.input-group').removeClass('has-error').addClass('has-success');
}
});
I basically would have to redo the whole design of my modal and I quite frankly dont want to go down that road. Not a fan of JS/ Jquery today.
Not really sure this is what you're looking for but, why do not simply make your code more universal:
$('input').on('keyup keydown keypress change paste', function() {
if ($(this).val() == '') {
$(this).removeClass('has-success').addClass('has-warning');
} else {
$(this).addClass('has-success').removeClass('has-warning');
}
});
EDIT
If you would like to specify a precise form, add an ID to your form :
<form id="myForm">
<label>Holidex:</label>
<div class="input-group">
<span class="input-group-addon"><i class="fa fa-bars"></i></span>
<input type="text" class="form-control" maxlength="5" placeholder="What is your Holidex code?" id="addHolidex" name="addHolidex" style="text-transform:uppercase" />
</div>
</form>
$('#myForm input').on('keyup keydown keypress change paste', function() {
if ($(this).val() == '') {
$(this).removeClass('has-success').addClass('has-warning');
} else {
$(this).addClass('has-success').removeClass('has-warning');
}
});
Add a new class to the input
<input type="text" class="form-control Input-to-verify" maxlength="5" placeholder="What is your Holidex code?" id="addHolidex" name="addHolidex" style="text-transform:uppercase" />
and then in javascript:
$('.Input-to-verify').on('change',function(){
if ($(this).val() == '') {
$(this).removeClass('has-success').addClass('has-warning');
} else {
$(this).addClass('has-success').removeClass('has-warning');
}
});
I hope this works
I'm new to working with ng-message. I have an error message (form.$error below) showing up when I don't want it to, while a user is typing and changing their incorrect entry. how can I either a) use ng-focus properly or b) clear ng-messages in my controller when a user is typing? my attempt at a) using ng-focus is below but it isn't working. I also tried replacing ng-focus with ng-change but that still doesn't work. is it also possible to manually disable the error message from showing up in the controller by clearing ng-message?
my html. I attempt to set the form to valid when the user is typing.
<div class="col-xs-3">
<input ng-focus="setValid()"
class="form-control" required ng-blur="checkCodes()"
ng-model="code1">
</div>
further down in my html I have this other div where the error shows up when I don't want it to, when the user is typing.
<div ng-if="codeError"
ng-messages="form.$error">
<p ng-show="code1 === code2"
class="disabled-text long-error">Inputs can't be the same</p>
</div>
this is the main js in my controller:
$scope.checkCodes = function() {
if ($scope.code1 && $scope.code1 === $scope.code2) {
$scope.showUniqueError = true;
$scope.form.$setValidity("prop", false);
$scope.showError2 = false;
} else {
$scope.showUniqueError = false;
$scope.form.$setValidity("prop", true);
}
}
//tried to use this in ng-focus but not working.
$scope.setValid = function() {
$scope.form.$setValidity("prop", true);
}
You were pretty close you just had the wrong scope variable in your ng-if.
I also change the ng-blur attritbutes to ng-keyup. With ng-blur your error message would only be displayed if you click outside of the text box or another control gets focus.
In the live example you will see that if you type in the same value for each input box that your error will be displayed and if you change one of the input boxes to a different value then the error will be removed.
Live Example: http://codepen.io/larryjoelane/pen/QyOZNR
test html:
<div ng-app="test" ng-controller="testController"><!--begin app container-->
<div class="col-xs-3">
<input ng-focus="setValid()"
class="form-control" required ng-blur="checkCodes()"
ng-model="code1">
<input ng-focus="setValid()"
class="form-control" required ng-blur="checkCodes()"
ng-model="code2">
</div>
<div ng-if="showUniqueError"
ng-messages="form.$error">
<p ng-show="code1 === code2"
class="disabled-text long-error">Inputs can't be the same</p>
</div>
</div><!--end app container-->
Test Javascript(Unchanged other then adding module wrapper and closure):
(function(){
angular.module("test",[]).controller("testController",function($scope){
$scope.checkCodes = function() {
if ($scope.code1 && $scope.code1 === $scope.code2) {
$scope.showUniqueError = true;
$scope.form.$setValidity("prop", false);
$scope.showError2 = false;
} else {
$scope.showUniqueError = false;
$scope.form.$setValidity("prop", true);
}
}
//tried to use this in ng-focus but not working.
$scope.setValid = function() {
$scope.form.$setValidity("prop", true);
}
});//end controller
})();
You can do it without using ng-message.
<form class="form-signin hide" id="gbLoginForm" method="POST" name="loginform" ng-controller="LoginCtrl" novalidate>
<div class="form-group">
<label for="username">User Name</label>
<input type="text" class="form-control" id="username" name="email" placeholder="User name/email" ng-model="user.email" required autofocus>
<span class="has-error" ng-show="loginform.email.$dirty && loginform.email.$error.required">
<span class="help-block" ng-bind="getValue('EMPTYEMAIL')"></span>
</span>
<span class="has-error" ng-show="loginform.email.$dirty && !loginform.email.$error.required && loginform.email.$error.validemail">
<span class="help-block" ng-bind="getValue('INVALIDEMAIL')"></span>
</span>
</div></form>
// email field is empty
if(!$scope.user.email){
$scope.loginform.email.$dirty = true;
$scope.loginform.email.$setValidity('required', false);
return false;
}
//invalid email
if(!UtilityService.validateEmail($scope.user.email)) {
$scope.loginform.email.$dirty = true;
$scope.loginform.email.$setValidity('validemail', false);
return false;
}
You don't need use ng-blur or ng-keyup, because angular refresh your ngModel on change input.
To create the various checks can use directive use-form-error.
Live example jsfiddle.
<form name="ExampleForm">
<label>Code 1</label>
<input ng-model="code1" required/>
<label>Code 2</label>
<input ng-model="code2" required/>
<div use-form-error="isSame" use-error-expression="code1 && code1==code2" ng-show="ExampleForm.$error.isSame">Inputs can't be the same</div>
</form>
I'm making a simple Multiple Choice Question form. I want to put validation that if a user clicks on Question <textarea> and clicks somewhere else on page while not entering value in <input type="text" name="q1_option1"> of options of the question, then the user should get an alert("Wait, you forgot to enter options for Question 1");. I tried doing it like this but it's simply not the thing that i want. Here is the <html>
<div class="right">
<div class="row" style="margin:5px;">
<label><strong>Question 1</strong></label>
<div>
<textarea name="question1"></textarea>
</div>
</div>
<div class="row">
<div class="span-4"><input type="text" name="q1_option1" value="" class="q1" /></div>
<div class="span-4"><input type="text" name="q1_option2" value="" class="q1" /></div>
<div class="span-4"><input type="text" name="q1_option3" value="" class="q1" /></div>
<div class="span-4"><input type="text" name="q1_option4" value="" class="q1" /></div>
<div class="clear"></div>
</div>
</div>
And this is <script>
<script type="text/javascript">
$(function(){
$('textarea[name=question1]').blur(function(){
$('.right').click(function(event) {
if($(event.target).is('input[name=q1_option1]')) {
$('#alert_error_message').text('Please enter all options in Question 1!!');
callalert();
return false;
}
else
{
alert('Not working!');
}
})
})
})
</script>
Now what is happening in this code, when the user clicks on <input> to enter the options, blur is fired and user gets the alert.
What i want that if a user clicks on these <input> of answers, he should not get the alert, else, the user must get the alert for not entering values in the <input> of options!!
DEMO
I came up with below approach and I will explain what I am doing with the below code. Check for the inline comments.
$(function(){
var hasFocus=false; //this variable is used to check whether focus was on textarea
//when clicked on document
$('textarea[name=question1]').blur(function(event){
setTimeout(function(){
hasFocus=false; //on blur set the variable to false but after sometime
},100);
}).focus(function(){
hasFocus=true; //on focus set it to true again
});
//A click event on document so that to display alert only if textarea had focus and the
//targetted element is not radio button
$(document).on('click',function(e){
if($(e.target).attr('class')!='q1' && hasFocus && $(e.target).attr('name')!="question1")
{
if(!$('.q1:checked').length) //if any radio has been checked
{
//if not checked then display alert
alert('Please select an option');
}
}
});
})
How about this?
var all_filled = true;
// for each component having class "q1", if the value is empty, then all_filled is false
$('.q1').each(function(comp){
if(comp.val() == ''){
all_filled = false;
break;
}
});
// if not all input is filled, then do what you want
if(!all_filled){
// do what you want
}
I'm trying to check whether a check box is checked, and if it is checked, then I want to add the "required" attribute to an adjacent text field. I've tried it two different ways with no success. Here are the form elements and my two JQuery attempts.
neither of those will actually trigger the event. My browser either does nothing at all or triggers an "Empty string passed to getElementById()." event
Form elements:
<div class="col-sm-5">
<label id="checkboxNumber-label" class="toplabel" for="checkboxNumber">Checkbox</label>
<g:textField name="checkboxNumber" value="${...checkboxNumber}" class="form-control" required="" aria-labelledby="checkboxNumber-label"/>
<label class="checkbox-inline">
<g:checkBox name="checkboxYesNo" id="checkboxYesNo" value="${...checkboxYesNo}" onclick="chkboxYesChecked()"/>
</label>
</div>
<div class="col-sm-5">
<label id="someTextField-label" class="toplabel" for="someTextField">Some Text Field Here</label>
<g:textField name="someTextField" id="someTextField" value="${...someTextField}" class="form-control" aria-labelledby="someTextField-label"/>
</div>
JQuery:
function chkboxYesChecked(){
if($('#checkboxYesNo').prop('checked')){
$('#someTextField').prop('required',true);
$('#someTextField').append('<span class="required-indicator">*</span>');
}else{
$('#someTextField').removeAttr('required');
}
}
$(document).ready(function() {
$('#checkboxYesNo').click(function() {
if($(this).is(":checked"))
{
$('#someTextField').prop('required',true);
$('#someTextField').append('<span class="required-indicator">*</span>');
} else {
$('#someTextField').removeAttr('required');
}
});
});
With your markup this becomes more convoluted than it needs to be.
$(document).on("click", ".checkbox-inline :checkbox", function () {
var $nextTextbox = $(this).closest("div").next("div").find(":text").first();
if (this.checked) {
$nextTextbox.prop("required", true).after('<span class="required-indicator">*</span>');
} else {
$nextTextbox.prop("required", false).next('.required-indicator').remove();
}
});
Notes
This approach uses event delegation.
There are no IDs involved, because I suppose you need the same thing more than once on your page. Tying it to a specific element ID is counter-productive.
This approach relies on the specific document structure from your sample Grails template. If you want something more flexible and easier-to-read, change your HTML.
This applies to all checkboxes that have a text field in the immediately following <div>. Use CSS classes on your elements to filter it/make it apply to specific ones only.
If there is no immediately following <div> with a text box, the function does nothing.
$(this).is(":checked") is superfluous. You don't need jQuery to find out if the current DOM element is checked. this.checked is a lot simpler and has the same effect.
Don't use inline event handlers (onclick="..."). Ever.
See it in action:
$(document).on("click", ".checkbox-inline :checkbox", function () {
var $nextTextbox = $(this).closest("div").next("div").find(":text").first();
if (this.checked) {
$nextTextbox.prop("required", true).after('<span class="required-indicator">*</span>');
} else {
$nextTextbox.prop("required", false).next('.required-indicator').remove();
}
});
input[required] {
background-color: #FFD1D1;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="col-sm-5">
<label id="checkboxNumber-label" class="toplabel" for="checkboxNumber">Checkbox</label>
<input type="text" name="checkboxNumber" value="${...checkboxNumber}" class="form-control" required="" aria-labelledby="checkboxNumber-label" />
<label class="checkbox-inline">
<input type="checkbox" name="checkboxYesNo" id="checkboxYesNo" value="${...checkboxYesNo}" />
</label>
</div>
<div class="col-sm-5">
<label id="someTextField-label" class="toplabel" for="someTextField">Some Text Field Here</label>
<input type="text" name="someTextField" id="someTextField" value="${...someTextField}" class="form-control" aria-labelledby="someTextField-label" />
</div>