Javascript focus event goes to next form field - forms

I am fairly new to Javascript and have a basic question. I have an HTML form with first_name and last_name input fields. I have the following Javascript code in the header but after the code runs, the focus goes to the next field (last_name). Why is that and how do I correct it?
Thank you.
<script>
function validateForm()
{
valid = true;
//validate first name
if (document.contactform.first_name.value == "")
{
//alert user first name is blank
alert("You must enter a first name");
document.getElementById("first_name").focus();
return false;
}
return valid;
}
</script>
and the form field code is:
input type="text" name="first_name" id="first_name" maxlength="50" size="30" onBlur="validateForm()"

A fix for this is to add a slight delay.. like so:
setTimeout(function() {
document.getElementById('first_name').focus()
}, 10);
Here is your example with this fix in jsfiddle: http://jsfiddle.net/FgHrg/1/
It seems to be a common Firefox problem.. I don't know exactly why but it has something to do with Firefox loading the javascript before the DOM is fully loaded.. in otherwords getElementById('first_name') returns null. But adding the slight delay fixes this problem.

Related

Text Field with hidden content when read, but visible when writing

I need a text field with the following behavior:
When the field is rendered, the current contents are hidden with password style (******), but if the user tries to edit it, the field gets cleared and they see on clear text what they are typing (so the behaviour is not entirely equivalent to PasswordTextField).
Any idea on how to achieve this behavior?
Thank you!
I think you should use some JavaScript to turn the field readable when focus event is fired. Here you can find a simple script that does the magic:
https://www.w3schools.com/howto/howto_js_toggle_password.asp
UPDATE:
In order to get the required behavior try the following code in the page above:
<!DOCTYPE html>
<html>
<body>
Password: <input type="password" value="FakePSW" id="myInput" onfocus="myFunction()"><br><br>
<script>
function myFunction() {
var x = document.getElementById("myInput");
x.value = "";
if (x.type === "password") {
x.type = "text";
} else {
x.type = "password";
}
}

jQuery Stop .blur() event when clicking "submit" button

I am building a small landing page with a simple demo e-mail signup form. I want to have the form field open up when focused, and then shrink back down on blur.
However the problem I'm facing is when you click the submit button this instigates the blur function, hiding the button and shrinking the form. I need to find a way to stop the .blur() method only when the user is clicking to focus on the submit button. Is there any good workaround for this?
Would appreciate any help I can get!
I know this question is old but the simplest way to do it would be to check event.relatedTarget. The first part of the if statement is to prevent throwing an error if relatedTarget is null (the IF will short circuit because null is equivalent to false and the browser knows that it doesn't have to check the second condition if the first condition is false in an && statement).
So:
if(event.relatedTarget && event.relatedTarget.type!="submit"){
//do your animation
}
It isn't the prettiest solution, but it does work. Try this:
$("#submitbtn").mousedown(function() {
mousedownHappened = true;
});
$("#email").blur(function() {
if (mousedownHappened) // cancel the blur event
{
mousedownHappened = false;
}
else // blur event is okay
{
$("#email").animate({
opacity: 0.75,
width: '-=240px'
}, 500, function() {
});
// hide submit button
$("#submitbtn").fadeOut(400);
}
});​
DEMO HERE
Try this inside .blur handler:
if ($(':focus').is('#submitbtn')) { return false; }
why not rely on submit event instead of click? http://jsbin.com/ehujup/5/edit
just couple changes into the html and js
wrap inputs into the form and add required for email as it obviously suppose to be
<form id="form">
<div id="signup">
<input type="email" name="email" id="email" placeholder="me#email.com" tabindex="1" required="required">
<input type="submit" name="submit" id="submitbtn" value="Signup" class="submit-btn" tabindex="2">
</div>
</form>
in js, remove handler which listen #submitbtn
$("#submitbtn").on("click", function(e){
e.stopImmediatePropagation();
$("#signup").fadeOut(220);
});
and use instead submit form listerer
$("#form").on("submit", function(e){
$("#signup").fadeOut(220);
return false;
});
you may use $.ajax() to make it even better.
Doing this you gain point in terms of validation and the native browser's HTML5 validator will make check email format where it is supported.

jquery / ajax form not passing button data

I thought the HTML spec stated that buttons click in a form pass their value, and button "not clicked" did not get passed. Like check boxes... I always check for the button value and sometimes I'll do different processing depending on which button was used to submit..
I have started using AJAX (specifically jquery) to submit my form data - but the button data is NEVER passed - is there something I'm missing? is there soemthing I can do to pass that data?
simple code might look like this
<form id="frmPost" method="post" action="page.php" class="bbForm" >
<input type="text" name="heading" id="heading" />
<input type="submit" name="btnA" value="Process It!" />
<input type="submit" name="btnB" value="Re-rout it somewhere Else!" />
</form>
<script>
$( function() { //once the doc has loaded
//handle the forms
$( '.bbForm' ).live( 'submit', function() { // catch the form's submit event
$.ajax({ // create an AJAX call...
data: $( this ).serialize(), // get the form data
type: $( this ).attr( 'method' ), // GET or POST
url: $( this ).attr( 'action' ), // the file to call
success: function( response ) { // on success..
$('#ui-tabs-1').html( response );
}
});
return false; // cancel original event to prevent form submitting
});
});
</script>
On the processing page - ONLY the "heading" field appears, neither the btnA or btnB regardless of whichever is clicked...
if it can't be 'fixed' can someone explain why the Ajax call doesn't follow "standard" form behavior?
thx
I found this to be an interesting issue so I figured I would do a bit of digging into the jquery source code and api documentation.
My findings:
Your issue has nothing to do with an ajax call and everything to do with the $.serialize() function. It simply is not coded to return <input type="submit"> or even <button type="submit"> I tried both. There is a regex expression that is run against the set of elements in the form to be serialized and it arbitrarily excludes the submit button unfortunately.
jQuery source code (I modified for debugging purposes but everything is still semantically intact):
serialize: function() {
var data = jQuery.param( this.serializeArray() );
return data;
},
serializeArray: function() {
var elementMap = this.map(function(){
return this.elements ? jQuery.makeArray( this.elements ) : this;
});
var filtered = elementMap.filter(function(){
var regexTest1= rselectTextarea.test( this.nodeName );
var regexTest2 = rinput.test( this.type ); //input submit will fail here thus never serialized as part of the form
var output = this.name && !this.disabled &&
( this.checked || regexTest2|| regexTest2);
return output;
});
var output = filtered.map(function( i, elem ){
var val = jQuery( this ).val();
return val == null ?
null :
jQuery.isArray( val ) ?
jQuery.map( val, function( val, i ){
return { name: elem.name, value: val.replace( rCRLF, "\r\n" ) };
}) :
{ name: elem.name, value: val.replace( rCRLF, "\r\n" ) };
}).get();
return output;
}
Now examining the jQuery documentation, you meet all the requirements for it to behave as expected (http://api.jquery.com/serialize/):
Note: Only "successful controls" are serialized to the string. No submit button value is serialized since the form was not submitted using a button. For a form element's value to be included in the serialized string, the element must have a name attribute. Values from checkboxes and radio buttons (inputs of type "radio" or "checkbox") are included only if they are checked. Data from file select elements is not serialized.
the "successful controls link branches out to the W3 spec and you definitely nailed the expected behavior on the spec.
Short lame answer: I think it is teh broken! Report for bug fix!!!
I've run into a rather unusual issue with this. I'm working on a project and have two separate php pages where one has html on the page separate from the php code and one is echoing html from inside php code. When I use the .serialize on the one that has the separate html code it works correctly. It sends my submit button value in its ajax call to another php page. But in the one with the html echoed from the php script I try to do the same thing and get completely different results. It will send all of the other info in the form but not the value of the submit button. All I need it to do is send whether or not I pushed "Delete" or "Update". I'm not asking for help (violating the rules of asking for help on another persons post) but I thought this info might be helpful in figuring out where the break down is occurring. I'll be looking for a solution and will post back here if I figure anything out.

HTML5 form placeholder fallback with form validation in Prototype

I've got an HTML5 form on my page with an email input that has place holder text in it. It works beautifully and I love the native validation!
I'm not sure how to serve old browsers best. I'm using a bit of javascript that copies the placeholder's text and imprints it as a value. It works well, but then the form validation goes off because there's text that isn't an email address in the form.
I do not want to lose the validation.. Any ideas?
HTML
<input id="email" type="email" placeholder="Enter your email address">
JavaScript (Prototype):
var Placeholder = Class.create({
initialize: function (element) {
this.element = element;
this.placeholder = element.readAttribute('placeholder');
this.blur();
Event.observe(this.element, 'focus', this.focus.bindAsEventListener(this));
Event.observe(this.element, 'blur', this.blur.bindAsEventListener(this));
},
focus: function () {
if (this.element.hasClassName('placeholder'))
this.element.clear().removeClassName('placeholder');
},
blur: function () {
if (this.element.value === '')
this.element.addClassName('placeholder').value = this.placeholder;
}
});
Event.observe(window, 'load', function(e){
new Placeholder($('email'));
});
EDIT:
Wouldn't it be great if browsers supporting placeholder ignored the value attribute?
EDIT 2:
No, I don't want to set the input type to text. That will change the validation's behavior from email syntax to spellcheck.
User Modernizr to detect support for placeholder and only use your javascript to copy the placeholder text if support doesn't exist:
if(!Modernizr.input.placeholder){
// copy placeholder text to input
}
This will prevent it from doing the copy on browsers supporting html5 form attributes like placeholder.
Try this:
<input type="email" value="Enter Email"
onfocus="if (this.value == 'Enter Email') {this.value = '';}"
onblur="if (this.value =='') {this.value = 'Enter Email';}" />
I know it's an old question, but it could help other users that come across this question.
You can use this http://afarkas.github.com/webshim/demos/demos/webforms.html for form validation with support for older browsers. It sits on top of jQuery and Modernizer and is pretty easy to implement.
Hope it helps.

How do I set two mutually exclusive check boxes in Jquery?

$(document).ready(function() {
$("input:txtAge1").click(function(event) {
if ($(txtAge1).attr("checked") == true) {
$(txtAge2).attr("checked", "unchecked");
$(txtAge2).attr("checked") == false)
}
if ($(txtAge2).attr("checked") == true) {
$(txtAge1).attr("checked", "unchecked");
$(txtAge1).attr("checked") == false)
}
});
});
<input type="checkbox" id="txtAge1" name="option1" value=""/>21<br>
<input type="checkbox" id="txtAge2" name="option2" value=""/>55<br>
I am trying to select either one checkbox or the other. So if one box is UNchecked, it should either be not allowed or force the
other box to BE checked ...in other words, enforce either one or the other but never allow
a "undefined" condition
Maybe I'm dumbing down the issue a bit, but why not try using radio buttons?
You can set one to be selected to avoid the user submitting an empty value.
Update: Since your customer wants checkboxes, here's a solution in jQuery:
$(document).ready(function(){
$('.radioButton').click(function() {
$('.radioButton').prop("checked", false);
$(this).prop("checked", true);
});
});
That's the jQuery code. You should set your input boxes up like this:
<input type="checkbox" id="txtAge1" class="radioButton" name="option1" value=""/>21
<input type="checkbox" id="txtAge2" class="radioButton" name="option2" value=""/>55
That should work, but it's untested. I might've missed something.
One solution is to add two click events, one for each checkbox. When one is clicked, the other is unclicked.
$("#checkbox1").click(function() {
$("#checkbox2").prop('checked', false);
});
$("#checkbox2").click(function() {
$('#checkbox1').prop('checked', false);
});
I ran into this issue recently, except I needed checkboxes instead of radio buttons as having both options unchecked was a requirement. I resolved it with something like this (adapted to the OP's code):
<input type="checkbox" id="txtAge1" />21
<input type="checkbox" id="txtAge2" />55
$(document).ready({
$("#txtAge1").click(function() {
if($("#txtAge1").is(':checked')) {
$("#txtAge2").prop('checked', false);
}
});
$("#txtAge2").click(function() {
if($("#txtAge2").is(':checked')) {
$("#txtAge1").prop('checked', false);
}
});
)};
Might not be that pretty, but it works.
I also wanted to note the excellent link http://rndnext.blogspot.com/2009/08/mutually-exclusive-html-select-elements.html here.
One caution though, I used it to mutex two dynamically generated select lists inside a div. . Since the content to be manipulated is not available at page load, it was not working as expected. Following solutions at jQuery - selecting dynamically created divs helped resolve the issue.
I would use this function. Allows mutual exclusion and allows uncheking:
$('#divId').find(':checkbox').click(function() {
var state=$(this).prop("checked");
$(':checkbox').prop("checked", false);
$(this).prop("checked", state);
});
$("input[type=checkbox]").click(function () {
$(this).siblings().prop("checked", false);
})