JavaScript - detect input change on any input/select field on current modal - javascript

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

Related

Percent sign in form input

Need help to make "%" sign show up automatically to my input field when user type number
<input type="text" name="ownership" id="ownership" placeholder="2.00%">
like here:
If user enter some number it will always add "%" sign in view. Probably should use some js, but I'm not familiar yet.
I have tried This way, but it works for every input
<script type="text/javascript">
$('input').change(function() {
$(this).val(function(index, old) { return old.replace() + '%'; });
});
</script>
If you use Boostrap this should work :
<div class="input-group mb-3">
<input type="text" class="form-control" aria-label="">
<div class="input-group-append">
<span class="input-group-text">%</span>
</div>
</div>
https://jsfiddle.net/uv9s6q02/
Seeing the code would help, but you can test to see if the user has typed a number using regex.
input.addEventListener('keyup', () => {
if (inputvalue.search(/\d/) > -1) { /* add % */ }
});

Maximum number of characters in search field

I have search field and it doesn't have that typical submit button. It looks like this:
HTML:
<div class="input-group">
<input type="text" class="form-control" name="keyword" id="searchbox" onkeypress="return checkLength()"/>
<span class="btn btn-primary input-group-addon" onclick="checkLength()"><i class="fa fa-search"></i></span>
</div>
I only added a span and not the input element for submit button. How do I validate if the user types or inputs not less than 2 characters? If the user types in 1 character only then presses that search button or just hit the enter key, there should be a red error message at the bottom of the search field saying "Keyword should be not less than 2 characters" or something like that.
I tried this code but it's not working:
function checkLength(){
var textbox = document.getElementById("searchbox");
if(textbox.value.length <= 10 && textbox.value.length >= 2){
alert("success");
} else {
alert("Keyword should be not less than 2 characters");
$(document).keypress(function (e) {
var keyCode = (window.event) ? e.which : e.keyCode;
if (keyCode && keyCode == 13) {
e.preventDefault();
return false;
}
});
}
}
Need help. Thanks.
EDIT:
After inputting keywords and hit the enter key, the page would redirect to a search results page, but that should be prevented from happening if the inputted keyword does not have 2 or more characters, hence, displaying a red text error message below the search field. How to do it?
You can use pattern attribute in HTML5 input, and you can validate the text with just CSS:
.error {
display: none;
font: italic medium sans-serif;
color: red;
}
input[pattern]:required:invalid ~ .error {
display: block;
}
<form>
<input type="text" name="pattern-input" pattern=".{2,}" title="Min 2 characters" required>
<input type="submit">
<span class="error">Enter at least two characters</span>
</form>
Here is the Fiddle
Note: This would work with all modern browsers, IE9 and earlier doesn't seems to have support for :invalid, :valid, and :required CSS pseudo-classes till now and Safari have only partial support.
Jquery Validation plugin can be used. it is very simple.
$(document).ready(function(){
$("#registerForm").validate();
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://ajax.microsoft.com/ajax/jquery.validate/1.7/jquery.validate.min.js"></script>
<form id='registerForm' name='registerForm' method='post' action='' > <p>
Search <input type='text' name='name' id='name' minlength="2" class='required' />
</p>
</form>
Ref :
http://jqueryvalidation.org/documentation/
Try utilizing .previousElementSibling to select span .nodeName to select input set div .innerHTML to empty string "" or "Keyword should be not less than 2 characters" , using input event
var msg = document.getElementById("msg");
function checkLength(elem) {
var el = elem.type === "text" ? elem : elem.previousElementSibling
, len = el.value.length < 2;
msg.innerHTML = len ? "Keyword should be not less than 2 characters" : "";
$(el).one("input", function() {
checkLength(this)
})
}
#msg {
color:red;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div class="input-group">
<form>
<input type="text" class="form-control" name="keyword" id="searchbox" />
<input type="button" class="btn btn-primary input-group-addon" onclick="checkLength(this)" value="X" />
<div id="msg"></div>
</form>
</div>
I made a jsfiddle that might be close to what you want.
Take a gander and see what you can make of it.
Don't hesitate to ask questions about it.
My best explanation is:
There is an event handler on both the input and the submit button that test the input's value. Based on the conditions that I have assumed from your question, either a success alert or an error message is shown. The success alert could be replaced with an ajax call or to trigger a form submission.

Adding exceptions in blur event

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
}

jQuery | Set focus to input (fixed focus)

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.

Auto tab to next input field when fill 4 characters

What I am trying to do is, point to next tab when filling four characters. Each field should have 4 characters and once it is completed it should move to next input box.
$(".inputs").keyup(function () {
if (this.value.length == this.maxLength) {
$(this).next('.inputs').focus();
}
});
Fiddle.
Your code works fine, however your input elements are set as type="number". Non-numeric content is ignored, so if you enter "abcd", for example, the input's value is empty (meaning a length of 0). If you enter "1234" on the other hand, the input's value is 1234.
If you want your code to fire when non-numeric content is entered, simply change each input's type to text.
<input class="inputs" type="text" maxlength="4" />
JSFiddle demo.
Note that I've also removed the duplicate class attribute from each of your elements in that example, too.
As krish has mentioned in the comments on your question, there is an issue with your code in that the last input element will continue to accept more than 4 characters. To fix this, put a check in place to ensure that there is a next('.inputs') element:
if (this.value.length == this.maxLength) {
var $next = $(this).next('.inputs');
if ($next.length)
$(this).next('.inputs').focus();
else
$(this).blur();
}
JSFiddle demo.
Perhaps you neglected to enclose your code in DOM ready. Jsfiddle encloses your code in $(window).load(function() { .....}) and that's why it's working. So on your own page use:
$(function() {
$(".inputs").keyup(function () {
if (this.value.length == this.maxLength) {
$(this).next('.inputs').focus();
}
});
});
In the jsfiddle you can confirm that by selecting No wrap - in <head> and then click run. The code will not work. But if you use the above which is enclosed in DOM ready, it works.
<html>
<head>
<script src="http://code.jquery.com/jquery-1.11.0.min.js"></script>
<Script>
$(document).ready(function(){
$(".inputs").keyup(function () {
$this=$(this);
if ($this.val().length >=$this.data("maxlength")) {
if($this.val().length>$this.data("maxlength")){
$this.val($this.val().substring(0,4));
}
$this.next(".inputs").focus();
}
});
});
</Script>
</head>
<body>
<input type="text" class="inputs" data-maxlength="4">
<input type="text" class="inputs" data-maxlength="4">
<input type="text" class="inputs" data-maxlength="4">
<input type="text" class="inputs" data-maxlength="4">
</body>
Here is a improved Version for all who need this for some kind of splitted Informations like a serial key or something like that:
$(document).ready(function(){
$(".amazonInput").keydown(function (e) {
var code = e.which;
$this=$(this);
if ($this.val().length >=$this.data("maxlength") && code != 8) {
if($this.val().length>$this.data("maxlength")){
$this.val($this.val().substring(0,4));
}
$this.next(".amazonInput").focus();
}
if($this.val().length == 0 && code == 8) {
$this.prev(".amazonInput").focus();
}
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
My first issue with this has been that if tabbing through fields that are already filled, you have to select each field manually. I suggest this:
$(".inputs").keyup(function () {
if (this.value.length == this.maxLength) {
$(this).next('.inputs').select();
}
});
The second issue's solution escapes me. Basically, in the same situation of having fields previously filled, if you type too quickly the events will fire as such: KeyDown KeyDown KeyUp KeyUp
What this causes, is to skip the next input.
For those Who Have tried the Accepted Answer, but Couldn't find solution like me
In your Layout Page or page header, just input ajax library link (Shown in below)
It worked on me, Hope It will help you as well.
$(".inputs").keyup(function () {
if (this.value.length == this.maxLength) {
var $next = $(this).next('.inputs');
if ($next.length)
$(this).next('.inputs').focus();
else
$(this).blur();
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<body>
<input class="inputs" type="text" maxlength="4" style="font-size:10px" />
<input class="inputs" type="text" maxlength="4" style="font-size:10px" />
<input class="inputs" type="text" maxlength="4" style="font-size:10px" />
</body>

Categories