Adding class to input when default value changed - javascript

I have an input field that has a default value added with JavaScript
<input type="text" class="input-text required-entry validate-value-eg" id="city_field" name="city" onfocus="if(this.value=='e.g. Bristol, Yorkshire') this.value='';" onblur="if(this.value=='') this.value='e.g. Bristol, Yorkshire';" value="e.g. Bristol, Yorkshire">
Whenever visitor click on this field the default value will dissipated and restore if not replaced by other value.
What I am trying to achieve is to add a class only if value has been changed from default?
Any help much appreciated,
Thanks
Dom

It is always a better practice to define your events in the script section or a separate .js file.
You don't need to handle that in a .change() event . You can check that in the .blur() event itself..
HTML
<input type="text" class="input-text required-entry validate-value-eg"
id="city_field" name="city" value="e.g. Bristol, Yorkshire">
Pure Javascript
var elem = document.getElementById('city_field');
elem.addEventListener('focus', function() {
if (this.value == 'e.g. Bristol, Yorkshire') {
this.value = '';
}
});
elem.addEventListener('blur', function() {
if (this.value == 'e.g. Bristol, Yorkshire') {
RemoveClass(this, "newClass")
}
else if (this.value == '') {
this.value = 'e.g. Bristol, Yorkshire';
RemoveClass(this, "newClass")
}
else {
this.className += " newClass";
}
});
function RemoveClass(elem, newClass) {
elem.className = elem.className.replace(/(?:^|\s)newClass(?!\S)/g, '')
}​
Javascript Fiddle
But you can achieve this with a loss lesser code by using other javascript frameworks.
This will make your life a lot easier but it is always good if you start out with javascript.
jQuery
$(function() {
var $elem = $('#city_field');
$elem.val('e.g.Bristol, Yorkshire'); // Default value
$elem.on('focus', function() { // Focus event
if (this.value == 'e.g.Bristol, Yorkshire') {
this.value = '';
}
});
$elem.on('blur', function() { // Focus event
if (this.value == 'e.g.Bristol, Yorkshire') {
$(this).removeClass("newClass");
}
else if (this.value == '') {
this.value = 'e.g.Bristol, Yorkshire';
$(this).removeClass("newClass");
}
else {
$(this).addClass("newClass");
}
});
});​
jQuery Fiddle

Add an onchange handler to your input
<input type="text" class="input-text required-entry validate-value-eg"
id="city_field" name="city"
onchange="addClass(this)"
onfocus="if(this.value=='e.g. Bristol, Yorkshire') this.value='';"
onblur="if(this.value=='') this.value='e.g. Bristol, Yorkshire';"
value="e.g. Bristol, Yorkshire">
<script>
function addClass(input) // 'this' in onChange argument is the input element
{
if( input.value=='e.g. Bristol, Yorkshire')
{
$(input).removeClass("not_default_input_class");
$(input).addClass("default_input_class");
}
else
{
$(input).removeClass("default_input_class");
$(input).addClass("not_default_input_class");
}
}
</script>
EDIT: Added use of jQuery to add/remove the CSS classes

<script>
function addClass(input) // 'this' in onChange argument is the input element
{
input.className = input.value==input.defaultValue?
"default_input_class" : "not_default_input_class"
}
</script>

Related

Validating textbox on copy paste in mvc

I have a textbox that has variable maxlenght based on some condition. There are keyup and keydown events associated with the textbox. On paste my maxlenght validation fails.If "Location" is selected the type of textbox is number with maxlenght 6, for other the type is text with maxlen 11 and 15 respectively "
$(document).on("pageinit", function (event) {
$('input[type="text"]').on('keyup keydown', function (event) { /*Some validation*/} });
$('input[type="number"]').on('keyup keydown', function (event) { /*Some validation*/} });
JQuery
$(document).ready(function() {
var characters ;
$("#text").keyup(function(){
if($('#vehicle').prop('checked')){
characters=5;
}
else{
characters=10;
}
if($(this).val().length > characters){
$(this).val($(this).val().substr(0, characters));
}
});
});
HTML
<input type="checkbox" id="vehicle" value="Bike">I have a bike<br>
<input type="text" id="text"/>
SEE DEMO HERE
I used paste event to trigger keyup event because only using paste event I can somehow get the input but I couldn't manipulate the input given. Here's how I found a way -
$(".AlphaValidateOnPaste").on('paste', function(e) {
$(e.target).keyup();
});
$('.AlphaValidateOnPaste').on('keyup',function(e){
var value = $(this).val();
var i = value.length;
while (i--) {
var result = value.charAt(i).match(/^[a-zA-Z ]*$/);
if(result == null){
$(this).val('');
alert('Only Alphabates and Spaces');
break;
}
}
});
<label for="name">Name <span class="required">*</span></label>
<input type="text" name="employee_name" class="form-control AlphaValidateOnPaste" id="employee_name" required>
<script src="//code.jquery.com/jquery-1.11.3.min.js"></script>

Javascript to check input value

I am looking for a javascript function that when using onblur it validates that the text input is a number only with no decimal points or special characters. I have been able to find a few things, but none of them have worked thus far.
Here's what I have for the input fields:
<tr>
<td width="312"><strong>Cash on Hand</strong></td>
<td width="188">$
<input type="text" onchange="updateassets()" value="0" maxlength="11" name="CashOnHand" /></td>
Any help would be greatly appreciated.
Use below method onKeyUp event, this will not allow any characters on input field
function numericOnly(e)
{
var val = e.value.replace(/[^\d]/g, "");
if(val != e.value)
e.value = val;
}
Input field code
<input type="text" onchange="updateassets()" onKeyUp="numericOnly(this)" value="0" maxlength="11" name="CashOnHand" />
I like to separate the structure (HTML) from the function (JS). That's why there's no "onchange" attribute in the input element.
HTML
<input type="number" name="cashOnHand" value="0" maxlength="11" />
JS
function checkInputInteger() {
// Check if the input value is an integer
if (this.value == parseInt(this.value)) {
// The value is an integer
console.log('Input ' + this.name + ' is an integer');
}
else {
// The value is not an integer
console.log('Input ' + this.name + ' is not an integer');
}
}
// Get the input from DOM (getElementsByName returns a list)
input = document.getElementsByName('cashOnHand')[0];
// Bind the blur event to checkInputInteger
input.addEventListener('blur', checkInputInteger, false);
HTML
<form>
<input type="text" id="txt" />
</form>
JS
(function(a) {
a.onkeypress = function(e) {
if (e.keyCode >= 49 && e.keyCode <= 57) {}
else {
if (e.keyCode >= 97 && e.keyCode <= 122) {
alert('Error');
// return false;
} else return false;
}
};
})($('txt'));
function $(id) {
return document.getElementById(id);
}
Hope it helps you
Given:
<input onchange="updateassets()" value="0" ...>
you can make life easier by passing a reference to the element to the function using this:
<input onchange="updateassets(this)" value="0" ...>
and the validation function can be:
function validateIsInteger(element) {
if (/\D/.test(element.value)) {
// the element value contains non–digit values
} else {
// the element value is only digits
}
}
Using the change event is a good idea, as if the value hasn't changed, you don't need to check it.

javascript clear field value input

I am making a simple form and i have this code to clear the initial value:
Javascript:
function clearField(input) {
input.value = "";
};
html:
<input name="name" id="name" type="text" value="Name" onfocus="clearField(this);"/>
But what i don't want is that if the user fills the input but clicks it again, it gets erased. I want the field to have the starter value "Name" only if the input is empty. Thank you in advance!
do like
<input name="name" id="name" type="text" value="Name"
onblur="fillField(this,'Name');" onfocus="clearField(this,'Name');"/>
and js
function fillField(input,val) {
if(input.value == "")
input.value=val;
};
function clearField(input,val) {
if(input.value == val)
input.value="";
};
update
here is a demo fiddle of the same
Here is one solution with jQuery for browsers that don't support the placeholder attribute.
$('[placeholder]').focus(function() {
var input = $(this);
if (input.val() == input.attr('placeholder')) {
input.val('');
input.removeClass('placeholder');
}
}).blur(function() {
var input = $(this);
if (input.val() == '' || input.val() == input.attr('placeholder')) {
input.addClass('placeholder');
input.val(input.attr('placeholder'));
}
}).blur();
Found here:
http://www.hagenburger.net/BLOG/HTML5-Input-Placeholder-Fix-With-jQuery.html
This may be what you want:
Working jsFiddle here
This code places a default text string Enter your name here inside the <input> textbox, and colorizes the text to light grey.
As soon as the box is clicked, the default text is cleared and text color set to black.
If text is erased, the default text string is replaced and light grey color reset.
HTML:
<input id="fname" type="text" />
jQuery/javascript:
$(document).ready(function() {
var curval;
var fn = $('#fname');
fn.val('Enter your name here').css({"color":"lightgrey"});
fn.focus(function() {
//Upon ENTERING the field
curval = $(this).val();
if (curval == 'Enter your name here' || curval == '') {
$(this).val('');
$(this).css({"color":"black"});
}
}); //END focus()
fn.blur(function() {
//Upon LEAVING the field
curval = $(this).val();
if (curval != 'Enter your name here' && curval != '') {
$(this).css({"color":"black"});
}else{
fn.val('Enter your name here').css({"color":"lightgrey"});
}
}); //END blur()
}); //END document.ready
HTML:
<input name="name" id="name" type="text" value="Name" onfocus="clearField(this);" onblur="fillField(this);"/>
JS:
function clearField(input) {
if(input.value=="Name") { //Only clear if value is "Name"
input.value = "";
}
}
function fillField(input) {
if(input.value=="") {
input.value = "Name";
}
}
var input= $(this);
input.innerHTML = '';
OP's question is no longer relevant- the question was asked in 2013 when the placeholder attribute wasn't well supported.
Nowadays you can just use <input placeholder="Your text here">
https://developer.mozilla.org/en-US/docs/Web/HTML/Element/input#htmlattrdefplaceholder

Jquery / window.onbeforeload in custom jquery function

I want to add to this code a "window.onbeforeload" event to show a message that prevent the user from quitting the current page without adding the products to cart.
I have to show only when the quantity in > than 0 and with respecting the code below.
How can I do that ?
<form> <p><input class="qty"
type="text" maxlength="1" value="0" /></p>
<p><input class="qty" name="text"
type="text" value="0" /></p> <p><input
class="qty" name="text2" type="text"
/></p> </form>
<script type="text/javascript">
$(".qty").change(function(e) {
if(this.value != '3' && this.value != '6' && this.value != '9') {
this.value = 0;
alert('You can buy only 3, 6, or 9 pieces fromn this product');
} }); </script>
Thanks for help :)
Not sure why everyone is suggesting globals. This method requires no globals and no change() listener (which you may still need if you want that alert there). Based on MDC, assuming support for [].indexOf:
window.onbeforeunload = function (e) {
var e = e || window.event;
if (['3','6','9'].indexOf($(".qty").val())>=0) {
return;
}
else {
var msg = 'You can buy only 3, 6, or 9 pieces from this product';
// For IE and Firefox prior to version 4
if (e) {
e.returnValue = msg;
}
// For Safari
return msg;
}
};
With multiple inputs you will need to change the condition slightly:
var valid = true;
$('.qty').each(function(){ valid = valid && ['3','6','9'].indexOf($(this).val())>=0; });
if (valid) {
return;
}
else { ... }
You would need to set some "global" variable. GLobal does not necessarily mean global to the window, just enough it's global in your own namespace (which you hopefully got).
if(this.value != '3' && this.value != '6' && this.value != '9') {
NotifyTheUser = true;
}
else {
NotifyTheUser = false;
}
window.onbeforeunload = function() {
if( NotifyTheUser ) {
return 'Check your input.. foo bar yay!';
}
};
you can save the value in some global variable and then onbeforeunload look for that value, whether it's greater than 0 or not.
var valueContainer = 0;
$(".qty").change(function(e) {
valueContainer = this.value;
//rest of your code
});
window.onbeforeunload = function() {
if( valueContainer == 0) {
return 'Please Don't go away without selecting any product :(';
} };

Using JQuery to get the default value of a textarea, clearing onfocus and reinstating value on empty

I have some JQuery that isn't working and I need a little help. I a few forms on my website, and they all have a textarea with the class ".form-textarea". What I'm trying to do is use JQuery to get the default value of the textarea, clear the value on focus and reinstate the original value if the the textarea is empty. I realise that an ID would probably be better but I need a generic function to affect all of the textareas with this particular class.
$(document).ready(function()
{
var def = $(".form-textarea")
$(".form-textarea").focus(function(srcc)
{
if ($(this).val() == def)
{
$(this).removeClass("defaultTextActive");
$(this).val("");
}
});
$(".form-textarea").blur(function()
{
if ($(this).val() == "")
{
$(this).addClass("defaultTextActive");
$(this).val(def);
}
});
$(".defaultText").blur();
});
This is an old method I used for the exact same purpose. I believe this is what you're looking for (uses Textareas) : Live demo
This uses the jQuery data API. I've also added an extra class so you can markup your text nicely (disabled_text). This is a general purpose method so all you need to do is add the suggest class to your textarea/input and the script will do the rest
<textarea class='suggest'>Some default value</textarea>
<textarea class='suggest'>Some default value2</textarea>
<textarea class='suggest'>Some default value3</textarea>
<input type='text' value ='me too' class='suggest'>
$('.suggest').each(function() {
$this = $(this);
if ($this.val() != '') {
return;
}
$this.data('defaultval', $this.val());
$this.addClass('disabled_text').focus(function() {
if ($this.val() == $this.data('defaultval')) {
$this.val('');
}
$this.removeClass('disabled_text');
}).blur(function() {
var oldVal = ($this.data('defaultval')) ? $this.data('defaultval') : '';
if ($this.val() == '' && oldVal != '') {
$this.addClass('disabled_text').val(oldVal);
}
})
});
Here, give this a whirl and see if it does the trick.
<script>
$(document).ready(function(){
$default = "defaultText";
$(".form-textarea").focus(function(){
if( $(this).val() == $default ){
$(this).removeClass("defaultTextActive");
$(this).val("");
}
});
$(".form-textarea").blur(function(){
if( $(this).val() == "" ){
$(this).addClass("defaultTextActive");
$(this).val($default);
}
});
});
</script>
<input class="form-textarea" type="text" value="defaultText" />
<input class="form-textarea" type="text" value="defaultText" />
I've just tried to remove the value "srcc" from the focus function and it works fine

Categories