Issue with focus() after detach and insertBefore - javascript

I am having an issue with using the Tab key to move through the fields when I detach the current focussed element and insert it again. Please find my code in jsfiddle.. Also see below:
JS Code:
$(document).ready(function() {
$('.formElem').focusin(function() {
// Remove default text on focus in
if ($(this).val() == $(this).attr('title')) {
$(this).val('').removeClass('defaultText');
if (($(this).attr('id') == 'reg_pwd') || ($(this).attr('id') == 'reg_conf_pwd')) {
id = '#' + $(this).attr('id');
marker = $('<span>123</span>').insertBefore($(this));
$(this).detach().attr('type', 'password').insertAfter(marker);
marker.remove();
}
if ($(this).get(0) != $(':focus').get(0)) {
$(this).focus();
}
}
}).focusout(function() {
// Remove default text on focus out
if ($(this).val() === '') {
$(this).val($(this).attr('title')).addClass('defaultText');
if (($(this).attr('id') == 'reg_pwd') || ($(this).attr('id') == 'reg_conf_pwd')) {
marker = $('<span>123</span>').insertBefore($(this));
$(this).detach().attr('type', 'text').insertAfter(marker);
marker.remove();
}
}
});
});​
The code changes the type of the field from text to password and back and forth. When you click or use Tab to reach the password field, it loses the focus after it has been added again. Thanks if somebody can figure out why.

It appears that your using html5, so perhaps you could take advantage of the placeholder attribute. Instead of <input value="blah" /> use <input placeholder="blah" />. Now you don't even need to have the defaultText class, so you can remove that, along with associated jquery code you have that removes and adds classes.
Now you can also change the <input type="text" /> to <input type="password" /> for the password fields. I'm not sure what your trying to do with <span>123</span>. So perhaps, I don't fully understand your question. But the below seems to accomplish the effect your trying to do.
A jsfiddle as well http://jsfiddle.net/8BBRC/2
edit: Had wrong jsfiddle link.
<input type="text" class="formElem" id="reg_fullname" name="fullname" placeholder="Full Name" title="Full Name" /><br />
<input type="email" class="formElem" id="reg_email" name="email" placeholder="Email Address" title="Email Address" /><br />
<input type="password" class="formElem" id="reg_pwd" name="pwd" placeholder="Confirm" title="Password" /><br />
<input type="password" class="formElem" id="reg_conf_pwd" name="conf_pwd" placeholder="Confirm Password" title="Confirm Password" /><br />
<input type="submit" id="reg_submit" value="Submit" /><br />

Related

Disable an input element when a dependent element has changed value

<input type="password" placeholder="oldPass" id="passwordcyu" class="input-xlarge" name="passwordcyu">
<input type="password" placeholder="newPass" disabled=true class="input-xlarge" name="passwordmoi" id="passwordmoi">
<input type="password" placeholder="confirmPass" disabled=true class="input-xlarge" name="cfpw" id="cfpw" style="display:inline">
Hi everyone, I'm a new guy in javascript/jquery, I have three inputs text like above. I don't know how to disable inputs #newPass and #confirmPass when #oldPass has changed value. Please help me or give me some advises.
P/s: This is the first time I raise a question on stackoverflow. Sorry if I make someone feels uncomfortable about my question.
I'm going to assume that since your elements are already disabled in your HTML, you'll likely want to enable them. (This also fits the implied use case.)
The simplest jQuery-based answer for you would be to bind your element to a change() handler and disable the inputs as you see fit:
$("#passwordcyu").change(function() {
$("#passwordmoi, #cfpw").removeAttr("disabled");
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type="password" placeholder="oldPass" id="passwordcyu" class="input-xlarge" name="passwordcyu">
<input type="password" placeholder="newPass" disabled=true class="input-xlarge" name="passwordmoi" id="passwordmoi">
<input type="password" placeholder="confirmPass" disabled=true class="input-xlarge" name="cfpw" id="cfpw" style="display:inline">
Pure javascript live example:
function changeInputs() {
document.getElementById("passwordcyu").disabled = true;
document.getElementById("passwordmoi").disabled = false;
document.getElementById("cfpw").disabled = false;
}
<input type="password" placeholder="oldPass" id="passwordcyu" onchange="changeInputs()">
<input type="password" placeholder="newPass" disabled="true" id="passwordmoi">
<input type="password" placeholder="confirmPass" disabled="true" id="cfpw">
You can use prop and disabled the other input whenever old password is clicked . i.e :
//when oldpass is click
$("#passwordcyu").on("click",function(){
$("#cfpw , #passwordmoi").prop("disabled", true);
});
//when new password is click enbaled it
$('#passwordmoi ').closest("div").click(function () {
$(this).find("#cfpw,#passwordmoi").attr("disabled", false);
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type="password" placeholder="oldPass" id="passwordcyu" class="input-xlarge" name="passwordcyu"><br/><br/>
<div>
<input type="password" placeholder="newPass" class="input-xlarge" name="passwordmoi" id="passwordmoi"> <br/><br/>
<input type="password" placeholder="confirmPass" class="input-xlarge" name="cfpw" id="cfpw" style="display:inline">
</div>

Check if an input with class is empty in a form

I wrote a code to validate a form on client-side. Since I binded all the error messages on('input', function()) now the last case to take in consideration is when the user didn't even hit a required input leaving it empty.
If all the inputs in the form were required I could have used something like
$('#subButton').on('click', function(e) {
if (!$('#formName').val()) {
e.preventDefault();
alert("Fill all the required fields");
});
But since in my form there are required inputs (with class="req") and non required inputs, I would like to know if there's a method to perform the check only on the .req inputs.
Something like:
$('#subButton').on('click', function(e) {
if (!$('#formName.req').val()) {
e.preventDefault();
alert("Fill all the required fields");
}
});
In other words I would like to perform the identical check which the up-to-date browsers do if the HTML required option is specified, just to be sure that, if the browser is a bit old and doesn't "read" the required option, jQuery prevents the form to be sent.
Just use .filter and check the length. Also, a simple ! check probably isn't good, what if someone enters 0?
var hasEmptyFields = $('#formName.req').filter(function() {
return this.value.replace(/^\s+/g, '').length; //returns true if empty
//Stole the above regex from: http://stackoverflow.com/questions/3937513/javascript-validation-for-empty-input-field
}).length > 0
if (hasEmptyFields) {
}
Use reduce
const submitAllowed = $('.req').toArray().reduce((result, item) => {
return result && (!!item.value || item.value === 0);
}, true)
if (!submitAllowed) { ... }
Here is a simple demo:
<form action="dummy.asp" onSubmit="return handleSubmit()">
<p> You can only submit if you enter a name </p>
<br />
Enter name: <input class="req" type="text" name="fname">
<input type="submit" value="Submit">
</form>
<script>
function handleSubmit() {
const submitAllowed = $('.req').toArray().reduce((result, item) => {
return result && (!!item.value || item.value === 0);
}, true)
return submitAllowed;
}
</script>
But since in my form there are required inputs (with class="req")
and non required inputs, I would like to know if there's a method to
perform the check only on the .req inputs
There is an HTML5 form boolean attribute required.
required works on:
<input type="text" />
<input type="search" />
<input type="url" />
<input type="tel" />
<input type="email" />
<input type="password" />
<input type="date" />
<input type="number" />
<input type="checkbox" />
<input type="radio" />
<input type="file" />
Example:
input {
display: block;
margin: 6px;
}
<form action="http://www.stackoverflow.com/">
<input type="text" placeholder="This is required" required />
<input type="text" placeholder="This isn't required" />
<input type="text" placeholder="This is required" required />
<input type="text" placeholder="This isn't required" />
<input type="submit" value="Press Me Without Filling in any of the Fields">
</form>
Peculiarly, the StackOverflow Snippet above doesn't seem to be working.
Here's a JSFiddle to demonstrate what it should be doing:
https://jsfiddle.net/a5tvaab8/

Validate input textbox with image

I have 13 input text boxes simply to collect information from user. I'm trying to add a little bit of logic that when user clicks next button check to see if input field is blank and if so place a X image after the textbox. Where I'm getting up up at is if I put text in the box then it will not outline the box in red but still places an X after the form.
I've tried using the $.each() and $.filter()
Here is the js:
var invalid = '<img src="css/Filtration/img/x.png" /> ';
$('.btn').click(function () {
var inputs = $(":input").filter(function () {
return this.value === "";
});
if (inputs.length) {
$(inputs).css('border-color', 'red').after(invalid);
console.log(inputs.length);
}
});
Here is some of the input text boxes not all :
<label>First Name:</label>
<input type="text" name="First Name" class="txtbox" id="firstName" />
<label>Last Name:</label>
<input type="text" name="Last Name" class="txtbox" id="lastName" />
<label>Email Address:</label>
<input type="text" name="Email Address" class="txtbox" id="email" />
<label>Company:</label>
<input type="text" name="Company" class="txtbox" id="company" />
Try this:
var invalid = '<img src="css/Filtration/img/x.png" /> ';
$('.btn').click(function () {
$(":input").each(function () {
if($(this).val() == '' ){
$(this).css({borderColor: 'red'}).after(invalid);
}
});
});
Note that if you had not previously set other border css parameters, the color may not work. So this pattern can take care of it in that case:
.css({border: '1px solid red'})
Now, :input is a bit broad and therefore inefficient. Therefore, its better to say:
$(':text', '#container').each(...
Where #container is, of course, the container of all your inputs.
Please, consider use jquery Validate, you can see examples here and documentation here

Search box active when visiting website.

I have a search box that I would like to make active when the customer visits my web page.
My HTML is:
<form class="form-search top-search" action="Search.aspx" onsubmit="return validateSearch(this);" method="GET">
<input type="text" class="input-medium search-query yui-ac-input" name="ss" id="ss" placeholder="Search and find it fast" title="Search and find it fast" onblur="if (this.value == '') { this.value = 'Search and find it fast'; }" onfocus="if ((this.value == 'Search and find it fast')||(this.value == 'Search and find it fast')) { this.value = ''; }" onkeypress="if ((this.value == 'Please enter a keyword or item #')||(this.value == 'Search and find it fast')) { this.value = ''; } else{ document.getElementsByName('ss')[0].style.color='black'; }" autocomplete="off">
<input type="submit" title="Search" class="btn btn-orange SearchButton" value="Search">
</form>
I'm just wanting to default the user into the field, like how Amazon defaults you into their search box.
You can use the HTML5 autofocus attribute:
<input type="text" autofocus>
You can use .focus() to focus the input
$(function () {
$('#ss').focus();
});
DEMO
Pure Javascript solution, works IE6+ and any other browser.
Put this before body end tag
<script type="text/javascript">
var obj = document.getElementById("ss");
obj.focus();
</script>
On browsers, that support html5, you can use autofocus attribute inside input.
<input autofocus type="text" class="input-medium search-query yui-ac-input" name="ss" id="ss" placeholder="Search and find it fast" title="Search and find it fast" autocomplete="off" />
You can use any of these options After Page Load.
$('#ss').focus();
$('#ss').select();
$('#ss').trigger('focus');
$('#ss').trigger('click');
For Example:
$(document).ready(function(){
$('#ss').trigger('click');
});

Disable password masking in password field

I want creating form field hints where the default value shows 'Password' and on focus, it goes away. If the field loses focus with no use input, it will reveal back to the default value of 'Password'.
Problem: The default value for the password field gets masked as well. How can I show the default value of 'Password' without getting masked, and masks only the user input?
jQuery Code
$(".splash_register_short_input, .splash_register_long_input").each(function() {
$(this).val( $(this).attr('title') );
});
$(".splash_register_short_input, .splash_register_long_input").focus(function() {
if($(this).val() == $(this).attr('title')) {
$(this).val('');
}
});
$(".splash_register_short_input, .splash_register_long_input").blur(function() {
if($(this).val() == '') { // If there is no user input
$(this).val($(this).attr('title'));
$(this).removeClass('splash_register_have_userinput');
} else { // If there is user input
$(this).addClass('splash_register_have_userinput');
}
});
HTML Code
<form id="splash_register_traditional_form">
<input type="text" name="register_first_name" class="splash_register_short_input" title="First Name" /><label for="register_first_name"></label>
<input type="text" name="register_last_name" class="splash_register_short_input" title="Last Name" /><label for="register_last_name"></label>
<input type="text" name="register_email" class="splash_register_long_input" title="Email" /><label for="register_email"></label>
<input type="password" name="register_password" class="splash_register_long_input" title="Password" /><label for="register_password"></label>
<input type="submit" id="splash_register_signup_button" value="Sign up" />
</form>
You can simply use the HTML5 placeholder-attribute:
<input type="password" placeholder="Enter Password..." />
Concerning the lack of backwards compatibility as mentioned in the comments, this jQuery placeholder plugin combined with some kind of a fallback machanism in case the attribute is not supported (like maybe this one) may be helpful.
Best way to do it would be to not set default value as value of password field but as an overlay over password field which disappears on focus or when user changes value to something else. You can use the arelady existing jquery in-field-label plugins e.g.
http://www.viget.com/inspire/a-better-jquery-in-field-label-plugin/
http://fuelyourcoding.com/scripts/infield/
http://www.kryogenix.org/code/browser/labelify/
To hide password programatically add this line below oncreate android.provider.Settings.System.putInt(this.getContentResolver(),android.provider.Settings.System.TEXT_SHOW_PASSWORD, 0);

Categories