Adding exceptions in blur event - javascript

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
}

Related

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

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

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.

Printing text next to a form field in JavaScript

I'm having a bit of trouble with this assigment and would like your help.
We are meant to create a product registration form page with all the regular expressions and everything and display the correct error when the regexes don't match.
I am trying to print a tick or say OK next to a form field but I can't get the right function. My form right now looks like this: http://www.imageurlhost.com/images/98zrdmrmsvbxnwowrvsf.png
The "Please enter product ...." is activated by jquery with a slideUp and slideDown function with onblur on the text field.
So I want to display OK where the red circle is after you click away from it, and then if you change it to something that doesn't match the OK disappears and my alert shows up. So this is my code so far:
My html form:
<div>
<input type="text" class="name" placeholder="Name" name="name" onblur="return validateProductName()"> <p class ="p11" id="p1"></p>
<p class="name-help">Please enter a product name between 1-50 characters.</p>
</div>
My css:
.p11 {
float: right;}
My jQuery:
$(".name").focus(function(){
$(".name-help").slideDown(500);
}).blur(function(){
$(".name-help").slideUp(500);
});
And then my JavaScript:
// Function to validate product name
function validateProductName() {
// if statement for product name
if (document.myForm.name.value.trim().search(pName) == -1) {
alert("Invalid product name. Please note: product name should have 1-50 characters.");
} else {
document.getElementById("p1").innerHTML = "OK";
}
}
So, it prints the OK in between the field on the right side, but I want it right next to the field like I showed in the picture and I can't get this to work! I want it to disappear if I go back to the form and put something wrong...
Thanks guys!
I assume, you have no problem with the jQuery itself, you have a problem of showing it next to input box. So,
Create a <span id='tick'> tag after the input field
And once it passes the validation, use jquery to show the tick
$('#tick').html('whatever you want');
EDIT: You dont have to include the float:left on span
Check out the fiddle link
EDIT:
In this validation function, just show and hide according to the validation results
// Function to validate product name
function validateProductName() {
// if statement for product name
if (document.myForm.name.value.trim().search(pName) == -1) {
document.getElementById("tick").style.display = 'none'; // to hide the OK text if enterd the wrong input
} else {
document.getElementById("tick").innerHTML = "OK"; //NOTE: This is for showing the ok text
document.getElementById("tick").style.display= "block";
}
}
Create a span wherever you want your tick to be displayed and they do this,
$("#btn").click(function() {
if ($("#txtname").val() == "") //can be any check
{
$("#g").attr("style", "display:block;width:20px");
} else {
$("#g").attr("style", "display:none;width:20px;");
}
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<input type="text" id="txtname" style="display:inline-block" placeholder="enter name" />
<img id="g" style="width:50px;display:none;" src="http://pixabay.com/static/uploads/photo/2014/04/02/10/19/check-303494_640.png" />
<br/>
<input type="button" id="btn" value="click to submit" />
This should work-
<script src="jq.js"></script>
<div>
<input type="text" class="name" placeholder="Name" name="name" id="input"> <span class ="p11" id="p1"></span>
<p class="name-help">Please enter a product name between 1-50 characters.</p>
</div>
<style>
p11 {
float: right;}
</style>
<script>
$(".name").focus(function(){
$(".name-help").slideDown(500);
}).blur(function(){
$(".name-help").slideUp(500);
validateProductName()
});
</script>
<script>
// Function to validate product name
function validateProductName() {
// if statement for product name
if (document.getElementById("input").value.trim() == "" || document.getElementById("input").value.length > 50 ) {
alert("Invalid product name. Please note: product name should have 1-50 characters.");
document.getElementById("p1").innerHTML = "";
} else {
document.getElementById("p1").innerHTML = "OK";
}
}
</script>

Enable input field X+1 onChange of input field X

So every 'special-input' div contains an input field. I am trying regulate when each information can be entered into each input field.
Initially, I would like the first input field from the top to be enabled, while the rest of the input fields below it be disabled.
OnChange of input field 1, I would like for the next input field below it to be enabled, while the rest disabled. OnChange of input field 2, I would like for input field 3 to become enabled, while the rest remain disabled, etc...
I know I can use JQuery's attr() to enable input fields when needed, but I am unsure how to apply the logic to accomplish this as JQuery is quite new to me.
<div class="special-input"><input type="text" /></div>
<div class="special-input"><input type="text" /></div>
<div class="special-input"><input type="text" /></div>
<div class="special-input"><input type="text" /></div>
<div class="special-input"><input type="text" /></div>
<div class="special-input"><input type="text" /></div>
<div class="special-input"><input type="text" /></div>
<div class="special-input"><input type="text" /></div>
<div class="special-input"><input type="text" /></div>
......
......
......
<div class="special-input"><input type="text" /></div>
// Cache the inputs, this is a good way to improve performance of your
// jQuery code when re-using selectors.
var $inputs = $('.special-input :input');
// Disable all except the first input
$inputs.not(':first').attr('disabled', 'disabled');
$inputs.each(function(i) {
// For each input, bind a change event to enable the next input,
// if the user presses enter, the next textbox will receive focus. if the user
// presses tab, the following input won't receive focus, so you'll have to add
// code if you want this to work.
$(this).on('change', function() {
// Get the index of the current input element we're looking at,
// We need to re-wrap the $input[i] element as it is now a normal
// DOM element.
var $nextInput = $($inputs[i + 1]);
$nextInput.removeAttr('disabled').focus();
});
});​
Edit: You can see a working example at http://jsfiddle.net/dFZEq/11/
Edit 2:
To enable the next line's set of elements after a certain condition is met, use this:
var $specialInputs = $('.special-input');
// don't disable the first line's input elements.
$specialInputs.not(':first').find(':input').attr('disabled', 'disabled');
$specialInputs.on('change', function() {
var $this = $(this);
if ($this.find(':input').filter(function() {
// you can change this filter to match any condition you
// like, for now we'll just make sure all inputs have a non-empty value
return $(this).val() == '';
}).length == 0) {
var $nextInputSet = $($specialInputs[$this.index() + 1]).find(':input');
// enable the next set of elements
$nextInputSet.removeAttr('disabled');
// focus your element here, requires more work
$nextInputSet.first().focus();
}
});​
Example at http://jsfiddle.net/tFG5W/
I've not tested the following code, but should look something like this :
$(".special-input").bind("change",function(event){
$(this).attr("disabled","disabled");
$(this).next().removeAttr("disabled").focus();
});

Error Message will not show in JQuery if it is NOT the first one encountered

I have a feedback form and I am replicating some code to check for values in text inputs and textareas. I have a name field and a feedback field. The errors hide on document load and at the start of a click function The name one shows as expected, but I cannot get the feedback one to show.
I set the errors to show on document load but hide onclick and I could get the feedback error to show if I filled in the name(the name error would hide, as expected).
HTML form.
<div class="slide-out-div">
<h3>Give us Feedback</h3>
<a class="handle" href="#">Content</a>
<p>We would love to hear your ideas to make the site more user-friendly or efficient for your benefit.</p>
<form name="feedbackform" id="feedbackform" action="" method="post">
<label for="feedname">Name:</label>
<input type="text" name="feedname" id="feedname" style="width:100%" /><br />
<label class="error" for="feedname" id="feedname_error">Please insert your name.</label> <br />
<label for="feedback">Feedback:</label><br />
<textarea name="feedback" id="feedback" style="width:100%;height:150px;"></textarea>
<label class="error" for="feedback" id="feedback_error">Please insert your some feedback.</label> <br />
<input type="submit" value="Submit Feedback" id="feedbacksubmit" />
</form>
<div id="feedwrap"></div>
</div>
JQuery Process
$('#feedbacksubmit').click(function (e) {
$('.error').hide();
//Cancel the link behavior
e.preventDefault();
var name = $("input#feedname").val();
if(name == ""){
$("label#feedname_error").show();
$("input#feedname").focus();
return false;
}
Var feedback = $("textarea#feedback").val();
if(feedback == ""){
$("label#feedback_error").show();
$("textarea#feedback").focus();
return false;
}
//process
return false;
});
Any help would be greatly appreciated.
It's becasue you are returning false as soon as you complete the validation of the name. That'll stop the execution of the function there and the second error message will not show up. May be you can write something like this.
$('#feedbacksubmit').click(function (e) {
$('.error').hide();
//Cancel the link behavior
e.preventDefault();
var returnvalue = true;
var name = $("input#feedname").val();
if(name == ""){
$("label#feedname_error").show();
$("input#feedname").focus();
returnvalue = false;
}
var feedback = $("textarea#feedback").val();
if(feedback == ""){
$("label#feedback_error").show();
$("textarea#feedback").focus();
returnvalue = false;
}
//process
return returnvalue ;
});
It appears that if I move the error above the textarea is shows but otherwise it does not, it must show but not visible to the user.

Categories