JQuery focusOut issue in IE - javascript

I have a small problem with focusout function in IE.
I have two fields with the same class and I wrote an empty validation code in jQuery for that class with focusout.
While I focus out of a field which is empty it shows alert and focus to the same field.
While doing that focus, It shows me alert again and again b'coz of the same class.
What to do?
JS:
$(".emptyValidate").focusout(function() {
var currFocusOut = $(this).attr("inText");
if($(this).val() == ""){
alert(currFocusOut+" should not be Empty");
document.getElementById(currFocusOut).focus();
}
});
Markup :
<input type="text" inText="Name" id="Name" class="emptyValidate "/>
<input type="text" inText="Phone" id="Phone" class="emptyValidate "/>

Working Demo
$(".emptyValidate").focusout(function () {
var currFocusOut = $(this).attr("id");
if ($(this).val() == "") {
alert(currFocusOut + " should not be Empty");
$('#'+currFocusOut).focus();
}
});

Try to use blur function like,
$(".emptyValidate").blur(function() {
var currFocusOut = $(this).attr("inText");
if($(this).val() == ""){
alert(currFocusOut+" should not be Empty");
document.getElementById(currFocusOut).focus();
}
});
Read blur()
Or, custom attribute inText may not work, so you can use data in jquery like
<input type="text" data-inText="Name" id="Name" class="emptyValidate "/>
<input type="text" data-inText="Phone" id="Phone" class="emptyValidate "/>
$(".emptyValidate").focusout(function() { // use blur if not works
var currFocusOut = $(this).data("inText");
if($(this).val() == ""){
alert(currFocusOut+" should not be Empty");
document.getElementById(currFocusOut).focus();
}
});
Read data()

Try inline function like this:
<input type="text" inText="Name" id="Name" class="emptyValidate" onfocusout="myFunction(this)"/>
<input type="text" inText="Phone" id="Phone" class="emptyValidate" onfocusout="myFunction(this)"/>
function myFunction(el){
var currFocusOut = $(el).attr("inText");
if($(el).val() == ""){
alert(currFocusOut+" should not be Empty");
document.getElementById(currFocusOut).focus();
}
}

Related

Get the input selector using this

I have set of input fields which are generated dynamically, hence I can't use an ID. For each of the input fields I have a focusout method which validates the value input by the end user.
If the validation fails, I would like to clear the value of the input and bring back the focus to the same input. When I tried to use this keyword scope seems to be set to the windows rather than the input control.
Input fields screenshot:
function validate(reg){
debugger;
if(isNaN(reg)==false){
return;
}
else
{
alert("The field should contain number");
$(this).val(""); //clear the value
$(this).focus();
}
}
In the above code, this keyword doesn't seem to work.
Pass the event to your validate() function, and then you can use event.target to target the input element.
function validate(reg, e){
debugger;
if(isNaN(reg)==false){
return;
}
else
{
alert("The field should contain number");
$(e.target).val(""); //clear the value
$(e.target).focus();
}
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input onfocusout="validate(this.value, event)"/>
<input onfocusout="validate(this.value, event)"/>
<input onfocusout="validate(this.value, event)"/>
Another method:
$(document).ready(function () {
var inputs = document.querySelectorAll("input[type=text]");
for (i = 0; i < inputs.length; i++)
inputs[i].addEventListener("focusout", function () { validate(this); });
});
function validate(reg) {
if (isNaN($(reg).val()) == false) {
return;
}
else {
alert("The field should contain number");
$(reg).val(""); //clear the value
$(reg).focus();
}
}
<input type="text" value="" />
<input type="text" value="" />
<input type="text" value="" />
<input type="text" value="" />

javascript keyup to change divs not just text

I have some code that checks if 2 text fields match. This is using the keyup which works fine but I would like it to hide or show a div depending on result. All I have is a code that changes divCheckPasswordMatch?
So I would like it to
$('#match').hide();
$('#nomatch').show();
The js code is :
$(function() {
$("#password2").keyup(function() {
var password = $("#password1").val();
$("#divCheckPasswordMatch").html(password == $(this).val() ? "Passwords match." : "Passwords do not match!");
});
});
My guess is you want to have two <div> displaying different messages using show() and hide(), but I'm not sure, so I did both.
$('#match').hide();
$('#nomatch').hide();
$("#password2").keyup(function() {
var password = $("#password1").val();
if ($(this).val() === password) {
$('#divCheckPasswordMatch').html('Passwords match');
$('#match').show();
$('#nomatch').hide();
} else {
$('#divCheckPasswordMatch').html('Passwords do not match');
$('#match').hide();
$('#nomatch').show();
}
});
<form action="/action_page.php">
First input: <input id="password1" type="text" name="fname"><br>
Second input: <input id="password2" type="text" name="lname"><br>
</form>
<div id="divCheckPasswordMatch"></div>
<div id="match">Match</div>
<div id="nomatch">No Match</div>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
Well following what you want you can do this.
HTML
<input id="password1">
<input id="password2">
<spam id="divCheckPasswordMatch"></spam>
JS
$(function() {
$("#password2").keyup(function() {
var password = $("#password1").val();
var password2 = $("#password2").val();
if(password!== null && password2!== null){
if(password == password2) {
$('#divCheckPasswordMatch').show();
$("#divCheckPasswordMatch").html("Passwords match.")
}
else {
$('#divCheckPasswordMatch').hide();
$("#divCheckPasswordMatch").html("Passwords do not match!")
}
}
});
});
But remember that you also need to anticipate if the password1 is changed too.
Here is working example. For learning purposes I highly suggest using pure javascript instead of jQuery. It is easy to rewrite it to jQuery. I can do it for you if you want.
You are missing blur event, I've added it. Code is not repeatable, it can be still improved. We are using one function for validation.
var field1 = document.getElementById('password1');
var field2 = document.getElementById('password2');
var result = document.getElementById('divCheckPasswordMatch');
function validateInputs() {
// If any of fields is empty then quit
if (field1.value === '' || field2.value === '') {
return;
}
if (field1.value === field2.value) {
result.innerHTML = '';
// optional hide it, clearing text gives almost the same effect, up to you
// result.style.display = 'none';
} else {
result.innerHTML = 'Passwords don\'t match';
// optional show it
//result.style.display = 'block';
}
}
document.getElementById('password1').addEventListener('keyup', validateInputs);
document.getElementById('password2').addEventListener('keyup', validateInputs);
document.getElementById('password1').addEventListener('blur', validateInputs);
document.getElementById('password2').addEventListener('blur', validateInputs);
<input type="text" id="password1">
<input type="text" id="password2">
<div id="divCheckPasswordMatch"></div>

Use JavaScript to disable fields in a HTML form

I have two fields in a HTML form:
<input type="text" name="name1"/>
<input type="text" name="name2"/>
Is there a way using JavaScript that if the user user has entered text into the first test box, the second textbox is disabled and vice-versa?
You could do it with jQuery by disabling the input that wasn't being typed in using the keyup() event in conjunction with the not() method. That would look like this:
$(function() {
var textLength;
$('input').keyup(function() {
textLength = $(this).val().length;
if (textLength > 0) {
$('input').not(this).attr('disabled','disabled');
} else {
$('input').removeAttr('disabled');
}
});
});
input[type="text"]:disabled {
background: #dddddd;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" name="name1"/>
<input type="text" name="name2"/>
Here is an very simple example(jsfiddle link below):
<input type="text" name="name1" id="name1" placeholder="Name 1"/>
<input type="text" name="name2"id="name2" placeholder="Name 2"/>
var name1 = document.getElementById('name1'),
name2 =document.getElementById('name2');
name1.onkeyup = function(e) {
if (name1.value.length > 0) {
name2.setAttribute('disabled', 'disabled');
} else {
name2.removeAttribute('disabled');
}
}
name2.onkeyup = function(e) {
if (name2.value.length > 0) {
name1.setAttribute('disabled', 'disabled');
} else {
name1.removeAttribute('disabled');
}
}
https://jsfiddle.net/Neviton/81zzjabk/
jQuery way:
At first you have to create CSS class 'disabled'.
<style>
.disabled {
opacity: 0.5;
pointer-events: none;
}
</style>
Then you add event listener 'change' to your inputs.
$( "input[value='name1']" ).change(function() {
$("input[value='name2']" ).addClass('disabled');
});
and
$( "input[value='name2']" ).change(function() {
$("input[value='name1']" ).addClass('disabled');
});
That will do the trick. When user changes value of input it adds class 'disabled' to another input.
This is an answer in clear JavaScript. The advantage of using the disabled property is, that even with tabulating it is not possible to put an input into the other field.
In the snippet the disabling is also reset if both input fields are empty.
var in1 = document.getElementById("input1"),
in2 = document.getElementById("input2");
function doOnChange() {
if (in1.value != "") {
in1.disabled = false;
in2.disabled = true;
} else if (in2.value != "") {
in1.disabled = true;
in2.disabled = false;
} if (in1.value == "" && in2.value == "") {
in1.disabled = false;
in2.disabled = false;
}
}
in1.addEventListener("keyup", doOnChange);
in2.addEventListener("keyup", doOnChange);
<input id="input1" />
<input id="input2" />
function myFunction() {
var a = document.getElementById('input1');
var b = document.getElementById('input2');
if (a.value.length == 0 && b.value.length == 0) {
a.disabled = false;
b.disabled = false;
} else if (a.value.length == 0) {
a.disabled = true;
} else if (b.value.length == 0) {
b.disabled = true;
}
}
<input type="text" id="input1" onkeyup="myFunction()" />
<input type="text" id="input2" onkeyup="myFunction()" />

Using watermark effect in forms

I want to implement watermark effect in my html form.
I have my code like this http://jsfiddle.net/aMjT4/1/
I want to set particular value to all my textboxes. Like in my textbox field
<input type="text" id="firstName" name="firstName" value="Enter First Name" class="inputTextboxId"/>
I want to set watermark text from value.(value="Enter First Name").
My javascript look like this but it will set watermark text into all my form fields.
$(document).ready(function () {
var watermark = 'Enter something...';
$('.inputTextboxId').blur(function () {
if ($(this).val().length == 0)
$(this).val(watermark).addClass('watermark');
}).focus(function () {
if ($(this).val() == watermark)
$(this).val('').removeClass('watermark');
}).val(watermark).addClass('watermark');
});
How can i set value text to all my textboxes?
I have this code but in this code i have to write this for all textboxes.
is there any way to generlize this?
<input type="text" id="city" name="city" value="Enter Your City" class="inputTextboxId" onblur="if (this.value == '') { this.value = 'Enter Country City';this.style.color = 'Gray'; }" maxlength="255" onfocus="if(this.value == this.defaultValue){this.value='';this.style.color='Black'}"/>
This is the hard way. You want to just either write a plugin or grab one that is readily available.
http://plugins.jquery.com/project/TinyWatermark
http://plugins.jquery.com/plugin-tags/watermark
Here's one I wrote
this is the js file code;
(function ($) {
$.fn.extend({
watermark: function () {
return this.each(function () {
var $obj = $(this);
$obj.val($obj.attr("watermarkText"));
$obj.focus(function (e) {
if ($obj.val() == $obj.attr("watermarkText"))
$obj.val("");
});
$obj.blur(function (e) {
if ($obj.val() == "")
$obj.val($obj.attr("watermarkText"));
});
});
}
});
})(jQuery);
and then in your html;
<script>
$(function () {
$(".watermark").watermark();
</script>
<input id="author" value="" type="text" name="author" watermarkText="Your name..." class="watermark required">

Jquery validation of input array elements manually

<input type="text" name="member_name[]" size="13" value="">
<input type="text" name="member_name[]" size="13" value="">
<input type="text" name="member_name[]" size="13" value="">
<input type="text" name="member_name[]" size="13" value="">
How do i validate these 4 fields so that they are not blank.. without using jquery validate plugin.?
You can cancel the form submission by registering a submit event handler and prevent the default behavior if one of your fields is empty:
$("form").submit(function(event) {
if ($("input:text[name='member_name\\[\\]'][value='']", this).length) {
window.alert("No member name should be empty.");
event.preventDefault();
}
});
EDIT: As naveen correctly points out, the code above would still submit the form if the fields only contain whitespace. You can use $.trim() with filter() to fix the problem:
$("form").submit(function(event) {
if ($("input:text[name='member_name\\[\\]']", this).filter(function() {
return $.trim(this.value) == "";
}).length) {
window.alert("No member name should be empty.");
event.preventDefault();
}
});
$('input:submit').click(function() {
$('form').submit(function(e) {
$("input:text[name^='member_name']").each(function() {
if (!$.trim($(this).val()).length) {
alert('Name Field should not leave empty');
return false; // or e.preventDefault();
}
});
});
});
var valid = true;
$('input').each(function(){
if($(this).val() == "") {
valid = false;
}
});
// use valid here
var invalidInputs = $('input').filter(function() {
return $(this).val() == "";
});
var valid = invalidInputs.length == 0
Not most advance, but simple & clear method.
$("form").submit(function(event) {
var inputLength = $('input[type="text"]').val().length; // check for value length
if ($('input').val().length > 0) {
// submit if input value is length > 0
alert('Form submitted.');
}
else {
// error if input value is NOT length > 0
alert('Fill the form.');
event.preventDefault();
}
});

Categories

Resources