<form class="navbar-form navbar-right" role="search">
<div class="form-group">
<input id="search_text" type="search" class="form-control" placeholder="Search" size="30">
<div class="form_control" id="search_info" style="width:283px;height:125px;top:86%;position:absolute;background-color:white; border: 1px solid #dce4ec;border-radius: 4px;display:none;"></div>
</div>
</form>
$("#search_text").keypress(function (){
if($("#search_text").val().length == 0)
{
$("#search_info").hide();
}
else if($("#search_text").val().length != 0)
{
$("#search_info").show();
}
});
My issue is that with this code it will only show
$("#search_info")
on the 2nd keypress. For example if i'm typing to the search field which I have as
$("#search_text"), $("#search_info") should show on the first press but it does not, when I more than one character into the search field it then shows $("#search_info").
I can't seem to figure it out.
Use keyup instead of keypress - as when keypress fires the value has not been inserted into the input yet.
$("#search_text").keyup(function (){
if($("#search_text").val().length == 0)
{
$("#search_info").hide();
}
else if($("#search_text").val().length != 0)
{
$("#search_info").show();
}
});
http://jsfiddle.net/qxh3x2s6/
Related
Im trying to auto jump to the next input once keypress is triggered but my code isnt working and I believe its todo with the next() select but can't seem to get it selected correctly.
HTML Form
<form method="POST" action="">
<div id="confirm-input">
#csrf
<div class="col-xs-1">
<input type="text" class="form-control input" maxlength="1"/>
</div>
<div class="col-xs-1">
<input type="text" class="form-control input" maxlength="1"/>
</div>
<div class="col-xs-1">
<input type="text" class="form-control input" maxlength="1"/>
</div>
<div class="col-xs-1">
<input type="text" class="form-control input" maxlength="1"/>
</div>
<div class="col-xs-1">
<input type="text" class="form-control input" maxlength="1"/>
</div>
<div class="col-xs-1">
<input type="text" class="form-control input" maxlength="1"/>
</div>
</div>
</form>
JS Code
$('.input').keyup(function (e) {
if (this.value.length == this.maxLength) {
var next = $(this).nextAll('input').first();
//Check if there is a next input.
if (next.length) {
next.focus();
} else {
$(this).blur
//AJAX CALL
}
}
});
Im using nextAll() as i believe it can look outside the div but not having any luck.
"Im using nextAll() as i believe it can look outside the div but not having any luck."
That's your problem right there. nextAll() only looks on the same tree level in the DOM. (Plunker here to demonstrate: http://plnkr.co/edit/u5t2Oy636xvl82WIgmvp?p=preview)
One possible solution would be to give your inputs successive ids, so that if your current input has an id of, say, "input-2", the look for "input-3" as the next input to focus on.
Update:
Here's a working Plunker that illustrates the above idea: http://plnkr.co/edit/UT5HydtxzyxkTIt5LBeZ?p=preview
$('.input').keyup(function (e) {
if (this.value.length == this.maxLength) {
var currId = $(this).attr('id');
var nextId = '#input-' + (Number(currId.split('-')[1]) + 1);
var next = $(nextId);
//Check if there is a next input.
if (next.length) {
next.focus();
} else {
$(this).blur
//AJAX CALL
}
}
}
My suggested solution is to determine how many elements match the selector then invoke .focus() using the index of each element, .blur() on the last element. You probably don't want to fire the AJAX call unless you've hit maxLength, hence the else if statement rather than just else.
var selector = "#confirm-input .input";
$(selector).keyup(function (e) {
var i = $(this).index(selector);
var len = $(selector).length - 1;
if (this.value.length == this.maxLength && i < len) {
$(selector).eq(i+1).focus();
}
else if(this.value.length == this.maxLength && i === len) {
$(this).blur();
//AJAX CALL
}
});
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 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.
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.