I have this code:
$(document).ready(function() {
$('.watermark').focus(function() {
if (this.className == 'watermark')
{
this.className = '';
this.reset = this.value;
this.value = '';
}
});
$('.watermark').blur(function() {
if (this.value == '')
{
this.className = 'watermark';
this.value = this.reset;
}
});
});
And it works fine, but when I submit my form the watermarks are submitted as data. Without modifying my php processing file, is it possible for watermarked text to be submitted as blank? What I mean is: if the textbox's class is 'watermark' submit a blank value for said textbox. I don't want to modify my php processing file but I do not mind using JQuery. Would the best solution be to capture the submit button's click event and quickly set textbox's with a watermark values to blank?
this should work if i understood you correctly:
$('form').submit(function(){
$(this).find('.watermark').each(function(){
if(!this.reset)
this.value = '';
});
});
Use the placeholder attribute on your text input elements:
<input type="text" placeholder="Text goes here" id="foo" />
Since this doesn't work in some older browsers, add an HTML5 placeholder attribute fallback script to your page (like this or this).
Related
Friends i am new to javascript, I am trying to write a script to validate the entire form whenever any input field value is changed of input fiels with the data attribute of required.
HTML
<form>
<input type="text" name="FirstName" class="inputField" data-required="true"></input>
<input type="text" name="MiddleName" class="inputField"></input>
<input type="text" name="LastName" class="inputField" data-required="true"></input>
</form>
SCRIPT
var field, required, isValid, fieldVal;
function validatedForm() {
field = document.querySelectorAll('.inputField');
document.getElementById("submitButton").disabled = true;
var isValid = true;
for(var i=0; i < field.length; i++){
required = field[i].dataset.required;
if(required){
field[i].addEventListener('blur', function(e){
fieldVal = this.value;
if(fieldVal == ''){
isValid = false;
}
checkSubmitBtn();
}, true);
}
}
function checkSubmitBtn() {
if(isValid = true) {
console.log(isValid);
document.getElementById("submitButton").disabled = false;
}
}
}
window.addEventListener("load", validatedForm);
PROBLEM 1:
The isValid is not updating hence even an empty blur on the input field makes the button disable to be false.
PROBLEM 2:
In case there are multiple forms on the page then how to validate only the desired forms .. just like in jQuery we add a script tag in the end to initialize the script according to it.
PROBLEM 3:
Is there a way to change the disable state of the button without the GetElementID ... I mean if that can be managed depending on the submit button of that particular form on the page where the script is suppose to work.
Any help will be highly appreciated. Thanks in advance.
I think you need something like the following form validation..
<script type="text/javascript">
var field, fieldVal, required = false;
function validatedForm() {
field = document.querySelectorAll('.inputField');
document.getElementById("submitButton").disabled = true;
field.forEach(function(elem) {
required = elem.dataset.required;
if(required){
elem.addEventListener('blur', function(e) {
checkSubmitBtn(field);
});
}
});
}
function checkSubmitBtn(field) {
var isDisabled = false;
field.forEach(function(elem) {
fieldVal = elem.value.trim();
if(fieldVal == ''){
isDisabled = true;
return false;
}
});
document.getElementById("submitButton").disabled = isDisabled;
}
window.addEventListener("load", validatedForm);
</script>
I hope it helps...
There are quite a few things going on here. First, your checkSubmitBtn function used a single = operator in the if statement. This won't actually check the variable, it instead will set the variable to that value. Here is the fixed function:
function checkSubmitBtn() {
if (isValid == true) {
document.getElementById("submitButton").disabled = false;
}
}
You mentioned not wanting to use getElementById. There are a few ways around this. One way would be to call the function once and store it in a variable to use later, like so:
var button = document.getElementById("submitButton");
...
function checkSubmitBtn() {
button.disabled = !isValid;
}
Another way would be to use jQuery. It still is technically calling getElementById in the backend, but the code is much simpler. If you wanted to avoid that, you also can still combine this with the technique I described above.
$("#submitButton").attr("disabled", !isValid);
I'd also like to point out that your code doesn't account for a situation where a form goes from invalid (starting point) to valid and back to invalid again. Say a user types in all of the fields but then backspaces everything. Your code will fall apart.
Lastly, your <input> HTML tags should not be closed. There are certain tags that are considered "self-closing", i.e. you don't have to write the closing tag, </input>.
Place holder is not working in IE-9,so I used the below code for place holder.
jQuery(function () {
debugger;
jQuery.support.placeholder = false;
test = document.createElement('input');
if ('placeholder' in test) jQuery.support.placeholder = true;
});
// This adds placeholder support to browsers that wouldn't otherwise support it.
$(function () {
if (!$.support.placeholder) {
var active = document.activeElement;
$(':text').focus(function () {
if ($(this).attr('placeholder') != '' && $(this).val() == $(this).attr('placeholder')) {
$(this).val('').removeClass('hasPlaceholder');
}
}).blur(function () {
if ($(this).attr('placeholder') != '' && ($(this).val() == '' || $(this).val() == $(this).attr('placeholder'))) {
$(this).val($(this).attr('placeholder')).addClass('hasPlaceholder');
}
});
$(':text').blur();
$(active).focus();
$('form:eq(0)').submit(function () {
$(':text.hasPlaceholder').val('');
});
}
});
When I am taking the value of test,it shows null.How can I get the details of all input tag?
I think this will help you
if ($.browser.msie) {
$("input").each(function () {
if (IsNull($(this).val()) && $(this).attr("placeholder") != "") {
$(this).val($(this).attr("placeholder")).addClass('hasPlaceHolder');
$(this).keypress(function () {
if ($(this).hasClass('hasPlaceHolder')) $(this).val("").removeClass('hasPlaceHolder');
});
$(this).blur(function () {
if ($(this).val() == "") $(this).val($(this).attr("placeholder")).addClass('hasPlaceHolder');
});
}
});
}
I'm on my mobile so this is hard but really you need to do
JQuery.support.placeholder = typeof 'placeholder' in test !== 'undefined'
Because null means there isn't any placeholder value, but there is placeholder support
From what I understand you're saying that the placeholder in test is returning null
I suggest you don't write this yourself and go for an off-the-shelf solution. There's more complexity here that you'd probably want to tackle yourself if all you want is provide support for older browsers.
For example, here's the shim I'm using (and that is recommended on http://html5please.com): https://github.com/mathiasbynens/jquery-placeholder/blob/master/jquery.placeholder.js
Go ahead and read the code. These are some issues you need to have in mind when writing such shim:
detect the browser support,
keep track when the box contains the real input or not;
add a class to allow different text colour for the placeholder,
clear the placeholders before submitting the form,
clear the placeholders when reloading the page,
handle textarea,
handle input[type=password]
And that's probably not even all. (The library I've linked also hooks into jQuery in order to make .val() return '' when there's no real input in the box.
There's also another shim that uses a totally different approach: https://github.com/parndt/jquery-html5-placeholder-shim/blob/master/jquery.html5-placeholder-shim.js
This library doesn't touch the actual value of the input, but instead displays an element directly over it.
HTML:
<input type='text' id='your_field' value='Enter value'/>
jQuery:
$(document).ready(function(){
$("#your_field").on('focusout',function(){
if($("#your_field").val() == ''){
$("#your_field").val('Enter value');
}
});
$("#your_field").on('focus',function(){
if($("#your_field").val() == 'Enter value'){
$("#your_field").val('');
}
});
});
See DEMO
Also check when the form is posted because if the user submits the form without entering the field then Enter value will be posted as the value of the field.So do either validations in client side or check in the server side when submitting the form.
I am trying to come up with a simple jquery input watermark function. Basically, if the input field has no value, display it's title.
I have come up with the jquery necessary to assign the input's value as it's title, but it does not display on the page as if it was a value that was hand-coded into the form.
How can I get this to display the value when the page loads in the input field for the user to see?
Here's the fiddle: http://jsfiddle.net/mQ3sX/2/
$(document).ready(function() {
$(".wmk").each(function(){
var value = $(this).val();
var title = $(this).attr("title");
if (value == '') {
value = title;
}
$(".result").text(value);
// You can see I can get something else to display the value, but it does
// not display in the actual input field.
});
});
Instead of writing your own, have you considered using a ready-bake version? It's not exactly what you asked for, but these have additional functionality you might like (for instance, behaving like a normal placeholder that auto-hides the placeholder when you start typing).
http://www.hagenburger.net/BLOG/HTML5-Input-Placeholder-Fix-With-jQuery.html
http://archive.plugins.jquery.com/project/input-placeholder
Use the below line of code. You need to specify the input element, and update its value. Since your input field has a class called '.wmk', I am using the below code. You can use "id" and use "#" instead of ".". Read more about selectors at http://api.jquery.com/category/selectors/
$(".wmk").val(value);
Updated jsfiddle http://jsfiddle.net/bhatlx/mQ3sX/9/
Update: since you are using 'each' on '.wmk', you can use
$(this).val(value)
I think what you want is this:
$(document).ready(function() {
$(".wmk").each(function(){
var value = $(this).val();
var title = $(this).attr("title");
if (value == '') {
$(this).val(title);
}
$(".result").text(value);
});
});
May be you want something like below,
DEMO
$(document).ready(function() {
$(".wmk").each (function () {
if (this.value == '') this.value = this.title;
});
$(".wmk").focus(
function () {
if (this.value == this.title) this.value = '';
}
).blur(
function () {
if (this.value == '') this.value = this.title;
}
);
}); // end doc ready
I have implemented through jQuery the placeholder HTML 5 attribute for the browsers that don't support it (all except webkit at this time).
It works really great but it has a small problem: it breaks the HTML 5 required="required" and pattern="pattern" attributes on Opera (it's the only browser that supports them currently).
This is because the placeholder value is temporarily set as the input value, and thus Opera thinks on form submission that the input is actually filled with the placeholder value. So I decided to remove the placeholders when the form is submitted:
$('form').submit(function() {
$(this).find(".placeholder").each(function() {
$(this).removeClass('placeholder');
$(this).val('');
});
});
This worked but another problem arose: if the form client-side validation failed (because of the required or pattern attributes) then the fields aren't re-given their placeholder value.
So, is there a way (js event?) to know if/when the form submission failed client-side, so I can re-add the placeholders?
Test case: open this with a browser that supports required/pattern but not placeholder (only Opera at this time). Try to submit the form without filling any of the inputs; you'll see that when you do the second input loses the placeholder. I don't want it to happen.
This is the complete code, but it's probably not needed:
function SupportsPlaceholder() {
var i = document.createElement('input');
return 'placeholder' in i;
}
$(document).ready(function() {
if (SupportsPlaceholder())
return;
$('input[placeholder]').focus(function() {
if ($(this).hasClass('placeholder')) {
if ($(this).val() == $(this).attr('placeholder'))
$(this).val('');
$(this).removeClass('placeholder');
}
});
$('input[placeholder]').keypress(function() {
if ($(this).hasClass('placeholder')) {
if ($(this).val() == $(this).attr('placeholder'))
$(this).val('');
$(this).removeClass('placeholder');
}
});
$('input[placeholder]').blur(function() {
if ($(this).val() != '')
return;
$(this).addClass('placeholder');
$(this).val($(this).attr('placeholder'));
});
$('input[placeholder]').each(function() {
if ($(this).val() != '' && $(this).val() != $(this).attr('placeholder'))
return;
$(this).val($(this).attr('placeholder')).addClass('placeholder');
});
$('form').submit(function() {
$(this).find(".placeholder").each(function() {
$(this).removeClass('placeholder');
$(this).val('');
});
});
});
read this: http://dev.opera.com/articles/view/making-legacy-pages-work-with-web-forms/
I didn't try, but it looks like you can check form validity this way:
if (form.checkValidity ){// browser supports validation
if( ! form.checkValidity()){ // form has errors,
// the browser is reporting them to user
// we don't need to take any action
}else{ // passed validation, submit now
form.submit();
}
}else{ // browser does not support validation
form.submit();
}
or simply check: element.validity.valid
btw. you should implement placeholder also for textarea - simply replace 'input[placeholder]' with 'input[placeholder], textarea[placeholder]'... and actually you don't need 'placeholder' class ;)
I need to focus out from the textbox when it focus in.
I try to set focus for outer div and its working fine in IE but not in mozilla.
How do I do this?
This is my current code:
<div id="outer"> <input type = "textbox" /></div> Onfocus: document.getElementById("outer").focus()
I wonder what's the purpose of using a textbox in this case if the user can never write anything inside. Just add a disabled="disabled" attribute or readonly="readonly" (in case you want to post the value).
In HTML:
<input type="text" onfocus="this.blur();" />
In JS:
document.getElementById("input1").onfocus = function () { this.blur(); }
Some elements cannot accept focus without being editable.
Where is the point in that? JS would be (didn't test it):
$('#textbox').focusin(function() {
$(this).focusout();
});
I have tried all the answers and not worked in all the browsers. And I combined all together in to it.
TextBox.readonly = true;
OnFocus:
var curText = TextBox.value;
TextBox.value = "";
TextBox.value = curText;
TextBox.blur();
TextBox_Parent.focus()
And its working fine in all the browsers
/*for textarea*/
$(document).ready(function() {
$('textarea[type="text"]').addClass("idleField");
$('textarea[type="text"]').focus(function() {
$(this).removeClass("idleField").addClass("focusField");
if (this.value == this.defaultValue){
this.value = '';
}
if(this.value != this.defaultValue){
this.select();
}
});
$('textarea[type="text"]').blur(function() {
$(this).removeClass("focusField").addClass("idleField");
if ($.trim(this.value == '')){
this.value = (this.defaultValue ? this.defaultValue : '');
}
});
});
that's what I used on my form.