using jquery to change contents of form upon typing - javascript

I am trying to get the default value to not go away on click, but rather when the user starts typing (so they know what the field is for)....the problem is the following:
when I use onchange instead of onfocus it keeps the default value in there when they start typing. If its confusing what I am doing go to facebook and look how their search box works...thats what I am going for.
<script>
function uFocus() {
$('#fakeusername').hide();
$('#username').show();
$('#username').focus();
}
function uBlur() {
if ($('#username').attr('value') == '') {
$('#username').hide();
$('#fakeusername').show();
}
}
</script>
<input style='width:202px;height:25px;margin-top:8px;font-size:14px;color:gray;' type='text' name='fakeusername' id='fakeusername' value=' Username' onfocus='uFocus()' />
<input style='width:202px;height:25px;margin-top:8px;font-size:14px;color:#000000;display: none' type='text' name='username' id='username' value='' onblur='uBlur()' />

Two options:
In HTML5, the placeholder attribute will simulate what you want with no Javascript needed.
<input type='text' name='fakeusername' id='fakeusername' value='Username' placeholder='Type your username' />
The second, and I believe the approach used by Facebook, is to swap a background image containing the sample text with a blank one. So you might create two background images (the first containing the words "Type your username" in the font used by the input, the second a blank) and set them to flip whenever the input is focused.

Is this what you are looking for:
$("#fakeusername").on({
focus: function() {
$(this).css('color', '#000');
},
blur: function() {
$(this).css('color', 'grey');
},
keydown: function() {
if ($(this).val()==' Username') {
$(this).val('');
}
}
});
FIDDLE

Here's a method that places label over top of input and requires proper for/ID match to allow browser to do default focus of input when clicking on label. Positions label over top of input, if no value of input on blur will show label again. Using label makes it accessible
http://jsfiddle.net/UCxaZ/2

Related

Trigger jquery function on input when clicking other input

I'm creating a dinamically added input form. I want to make it so when an input loses the focus, its value get .00 appended to it. So far I tried this:
$(".money-input").on("click", function(e) {
e.stopPropagation();
});
$(document).on("click", function (e) {
$(".money-input").each(function() {
var valTemp = $(this).val();
if ((valTemp.indexOf(".00") < 0) && (valTemp != "")) {
valTemp += ".00";
$(this).val(valTemp);
}
});
});
My problem is, it only works when I click on other divs but inputs. Additionally what I also want to achieve is when I edited something on one input then switch focus to other input, the previous input value got appended by .00.
Any help appreciated! :)
Use
$(".money-input").live('blur', function() {
var valTemp = $(this).val();
if ((valTemp.indexOf(".00") < 0) && (valTemp != "")) {
valTemp += ".00";
$(this).val(valTemp);
}
});
blur is your 'lost-focus' event. With using live it will attach this event to elements that exists now and in the future (since you are dynamically adding a form).
The requested behavior is odd...use the step attribute instead:
<input type='number' step='01'>
The minimum requirements to have a floating point value in an input is to have: type="number" and step attributes. In the following Demo there are 3 forms with 2 inputs each for a total of 6 inputs.
The first 2 inputs have no step attribute.
The second pair are dynamically created. The first input has no step attribute whilst the second one does.
The last pair of inputs have the step attribute.
I modified the styles so when an input has the step attribute, its borders are red dashed lines. It's not necessary to do this, it's just for demonstration purposes.
There is a jQuery on event handler registered on 2 events, one is blur event and the other is the change event. These events trigger the same handler which will set the step attribute to an input upon the triggering of either change or blur events.
Demo
$('#form1').append("<input id='i2' class='money' type='number' value='0.00'>").append("<input id='i3' class='money' type='number' value='0.00' step='.01'>");
$('.money').on('blur change', function(e) {
if ($(this).val() > 0) {
$(this).attr('step', '.01');
}
});
input[step*=".01"] {
border: 1px dashed red
}
<form id='form0'>
<input id='i0' class='money' type='number' value='0.00'>
<input id='i1' class='money' type='number' value='0.00'>
</form>
<form id='form1'></form>
<form id='form2'>
<input id='i4' class='money' type='number' value='0.00' step='.01'>
<input id='i5' class='money' type='number' value='0.00' step='.01'>
</form>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

Use two fonts in one input box

I am writing a program in which when a user click on check box , the font of the input (which i am writing) changes. Like firstly if the check box is unchecked the font is 'arial' and when the check box is checked the input font should become 'verdana'.
I am able to do this but the function changes all the previous text written into verdana.
Code Sample:
<input type= "checkbox" onchange = "tests();" name="remember" id = "remember"> **(Checkbox)**
function tests(){
if (remember.checked == 1){
$(.form-control).css('font-family','verdana');
}else{
$('.form-control').css('font-family','arial');
}
}
i need that whenever i check this , the upcoming data should be in verdana and the previous should remain same in input box.
Instead of changing the font of whole form class $(.form-control) do it for specific class of checkbox
Update:
add this css
input[type=checkbox]:checked + label {
font-family:'verdana'
}
input[type=checkbox] + label {
font-family:'arial'
}
In your code you seem to be using JQuery, so you can do this:
$("#remember").change(function() {
if ($(this).is(":checked")) {
$(".myText").css("font-family", "Verdana");
} else {
$(".myText").css("font-family", "Arial");
}
});
Here is the JSFiddle demo

Check input elements responsively when changed

I have this code. It obviously calls function when selected element is focused. The function then checks if selected element has length less than 3, and if it does it changes background color of the element.
$('#register-form input[type="text"]').focus(function(){
if ($(this).length < 3) {
$(this).css('background','#f00');
}
});
Now the problem is that when there are more than 4 characters within input, color still remains. The problem is that it calls function when element is focused. After that, it doesn't check the if statement anymore, as obviosuly function is never called again.
The solution I seek; I want it to check if the IF statement is still legit once the input element value is changed. Or any other smooth way to check IF statements and calls functions in a live time.
The answer to this question is simple and well known. However, as you answer please provide some information related to this question; What are the best ways to check various changes in statements lively? What are the best ways to make website 'alive' and respond to any actions immediately?
Give the error a class and use onkeyup (and change if you wish - which triggers on blur too)
Also test the .val().length instead:
<style>
.error { background-color:red }
</style>
$('#register-form input[type="text"]').on("keyup,change",function(){
$(this).toggleClass("error", $(this).val().length < 3);
}).keyup(); // trigger on load
$(function() {
$('#register_form input[type="text"]').on("keyup", function() {
$(this).toggleClass("error", $(this).val().length < 3);
console.log("error")
}).keyup(); // initialise in case of reload
});
.error {
color: red
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<form id="register_form">
<input type="text" />
<input type="text" />
<input type="text" />
</form>
Try this:
$('#register-form input[type="text"]').on("focus input", function(){
$(this).css('background', $(this).val().length < 3 ? '#f00' : '#fff');
});
EDIT
Personally, I use AngularJS alot for web applications that have alot of these. E.g. you can do this:
<input type="text" ng-model="myValue" ng-style="{'background-color', myValue.length < 3 ? '#f00' : '#fff'}"/>

Animated form, how to check input value on page refresh?

I have a form which uses dynamic styling. Consider this html
<div class="field-name field-form-item">
<label class="placeholder" for="name">Name</label>
<input class="form-input" id="name" type="text" name="name" maxlength="50" size="30">
</div>
The label is ABOVE the input, with CSS. When you click the label :
$('.placeholder').on('click focus', function() {
$(this).addClass('ph-activated');
$(this).siblings('input').focus();
})
Then the label is animated and let the user type in the input.
If the user dont wan't to write anything, the animation goes back, and hide input field :
$('input').on(' blur', function(){
if ($(this).val().length === 0) {
$(this).siblings('label').removeClass('ph-activated');
}
});
That's alright.
But when a user fill the input, THEN refresh the page and its browser didn't reset input fields(ie firefox) : the label is above the input, even if the latter is not empty.
I tried this :
$(document).ready(function() {
if ($('input').val().length) {
$(this).siblings('label').addClass('ph-activated');
}
})
But it doesn't seem to trigger, I tried several ways to write this function. Up to now I never managed to give the class ph-activated to a label with a filled input on page refresh.
Sorry I can't fiddle this. I just have far too much html/css/js/php to copy paste
Well you are targeting wrong element in $(document).ready because you are referring label with this thinking that $(this) is input whereas it is document. So try applying below code and I hope there will be multiple input elements in page, so I've used $.each and looping through all the inputs
$(document).ready(function() {
$('input').each(function(){ //loop through each inputs
if ($(this).val().length) {
$(this).siblings('label').addClass('ph-activated');
}
});
})
DEMO - Inspect the label and you will find ph-activated class added to label
Try this one:
$(document).ready(function() {
var length = $('input').filter(function( index ) {
return ($(this).val() !== '');
}).length;
if (length > 0) {
$(this).siblings('label').addClass('ph-activated');
}
})

Default text on input

How to set blank default text on input field and clear it when element is active.
In modern browsers, you may set the placeholder attribute on a field to set its default text.
<input type="text" placeholder="Type some text" id="myField" />
However, in older browsers, you may use JavaScript to capture the focus and blur events:
var addEvent = function(elem, type, fn) { // Simple utility for cross-browser event handling
if (elem.addEventListener) elem.addEventListener(type, fn, false);
else if (elem.attachEvent) elem.attachEvent('on' + type, fn);
},
textField = document.getElementById('myField'),
placeholder = 'Type some text'; // The placeholder text
addEvent(textField, 'focus', function() {
if (this.value === placeholder) this.value = '';
});
addEvent(textField, 'blur', function() {
if (this.value === '') this.value = placeholder;
});
Demo: http://jsbin.com/utecu
Using the onFocus and onBlur events allows you to achieve this, I.e.:
onfocus="if(this.value=='EGTEXT')this.value=''"
and
onblur="if(this.value=='')this.value='EGTEXT'"
The full example is as follows:
<input name="example" type="text" id="example" size="50" value="EGTEXT" onfocus="if(this.value=='EGTEXT')this.value=''" onblur="if(this.value=='')this.value='EGTEXT'" />
Or simply
<input name="example" type="text" id="example" value="Something" onfocus="value=''" />
This will not post back the default text once the box is cleared but also will allow the user to clear the box and see all results in the case of an autocomplete script.
Declare styles for inactive and active states:
.active {
color: black;
}
.inactive {
color: #909090;
}
Add the Javascript to handle the changing of state:
function toggleText(el)
{
var v = el.value;
//Remove text to allow editing
if(v=="Default text") {
el.value = "";
el.className = "active";
}
else {
//Remove whitespace
if(v.indexOf(" ")!=-1) {
split = v.split(" ").join("");
v = split;
}
//Change to inactive state
if(v=="") {
el.value = "Default text";
el.className = "inactive";
}
}
}
Add your input box, with the default value set, the inactive class set and Javascript handlers pointing to the toggleText() function (you could use event listeners to do this if you wish)
<input type="text" value="Default text" class="inactive" onFocus="toggleText(this);" onBlur="toggleText(this);">
From a usability point of view the text in the input component should be preserved only for user's input purposes. The possible default value in the input should be valid if left untouched by the user.
If the placeholder text is meant to be a hint for how to fill the input, it is better to be blaced near the input where it can be seen also when the input has been filled. Moreover, using a placeholder text inside text components can cause troubles e.g. with braille devices.
If a placeholder text is used, regardless of usability guidelines, one should make sure that it is done in an unobtrusive way so that it works with user agents without javascript or when js is turned off.
I have found jQuery plugin (http://www.jason-palmer.com/2008/08/jquery-plugin-form-field-default-value/) and use it :)
What I did is put a placeholder attribute for modern browsers:
<input id='search' placeholder='Search' />
Then, I made a fallback for older browsers using JQuery:
var placeholder = $('search').attr('placeholder');
//Set the value
$('search').val(placeholder);
//On focus (when user clicks into the input)
$('search').focus(function() {
if ($(this).val() == placeholder)
$(this).val('');
});
//If they focus out of the box (tab or click out)
$('search').blur(function() {
if ($(this).val() == '')
$(this).val(placeholder);
});
This works for me.
You can use this plugin (I'm an co-author)
https://github.com/tanin47/jquery.default_text
It clones an input field and put it there.
It works on IE, Firefox, Chrome and even iPhone Safari, which has the famous focus problem.
This way you do not have to be worried about clearing input field before submitting.
OR
If you want to HTML5 only, you can just use attribute "placeholder" on input field
You can use placeholder attribute.
np. <input type="text" name="fname" placeholder="First name">
check http://www.w3schools.com/tags/att_input_placeholder.asp

Categories

Resources