I want the same functions to run for 2 jQuery objects: $('input[type="text"]') and $('textarea[type=text]'). How can I combine those two in the code below? (currently, only input is included).
$('input[type="text"]').focus(function() {
if (this.value == this.defaultValue){
this.value = '';
}
if(this.value != this.defaultValue){
this.select();
}
});
$('input[type="text"]').blur(function() {
if ($.trim(this.value == '')){
this.value = (this.defaultValue ? this.defaultValue : '');
}
});
Thanks!
Try this:
$('textarea[type="text"], input[type="text"]').focus(...).blur(...);
Similarly you can also use jQuery's add function:
$('textarea[type="text"]').add('input[type="text"]').focus(...).blur(...);
May be easier to put a class on it and filter by that.
You could create a plugin:
jQuery.fn.clearDefValueOnFocus = function() {
return this.focus(function(){
if (this.value == this.defaultValue){
this.value = '';
}
if(this.value != this.defaultValue){
this.select();
}
}).blur(function(){
if (jQuery.trim(this.value) == ''){
this.value = this.defaultValue || '';
}
});
};
$('input[type="text"]').clearDefValueOnFocus();
$('textarea[type=text]').clearDefValueOnFocus();
Related
Am creating register form with jquery function keyup(),
for example if input is correct I assign it to a txtuname variable,then I press register button and I need to know that all form variables are correct and defined.Code below is not working:
<script type="text/javascript">
$("document").ready(function() {
$("#txtuname").keyup(function() {
if ($("#txtuname").val().length < 6) {
jQuery("label[for='txtuname']").text("user name is too short");
}
if ($("#txtuname").val().length >= 6) {
var txtuname = $("#txtuname").val();
jQuery("label[for='txtuname']").text("");
}
});
$("#submitRegistration").click(function() {
if (typeof txtuname == 'defined') {
alert("defined");
}
if (typeof txtuname == 'undefined') {
alert("undefined");
}
});
});
</script>
Modified code. Main point of this code is that txtuname should be visible in both scopes of keyup event listner and click listner. So if there are more lements, create Validation object and just check whether all the values was set and correct. And yes, use or $ or jQuery in your code.
$("document").ready(function(){
var txtuname = null;
$("#txtuname").keyup(function(){
if($("#txtuname").val().length<6){
jQuery("label[for='txtuname']").text("user name is too short");
}
if($("#txtuname").val().length>=6){
txtuname=$("#txtuname").val();
jQuery("label[for='txtuname']").text("");
}
});
$("#submitRegistration").click(function(){
if( txtuname == null || txtuname.length < 6) ){
alert("incorrect");
}
else{
alert("correct");
}
});
});
Updated check of variable using comment of #Rhumborl , thx
Replace code with below condition -
if( typeof txtuname !== 'undefined' && txtuname.length >= 6) ){
//proceed further
}else{
alert('Please correct entries.');
return false;
}
I would put the validation logic in a function and call that, you can update this with your specific requirements and only do it once:
function isValidName(field) {
var myName = field.val().trim();
// some of this is redundant but just to show possibilities
var isValid = myName.length && myName.length >= 6 && myName && undefined !== myName && myName != " ";
var myLabel = $("label[for='" + field.attr('id') + "']");
if (isValid) {
myLabel.text("");
} else {
myLabel.text("user name is too short");
}
return isValid;
}
$("document").ready(function() {
$("#txtuname").keyup(function() {
isValidName($(this));
});
$("#submitRegistration").click(function() {
var nameIsValid = isValidName($("#txtuname"));
if (nameIsValid) {
alert("valid");
} else {
alert("undefined or invalid");
}
});
});
You are using $ as well as jQuery window.jQuery object in your code. Do not use both at time , you can check by both
jQuery("document").ready(function() { jQuery("#txtuname").keyup(function(){ if(jQuery("#txtuname").val().length<6){
jQuery("label[for='txtuname']").text("user name is too short");
}
if(jQuery("#txtuname").val().length>=6){
var txtuname=jQuery("#txtuname").val();
jQuery("label[for='txtuname']").text("");
}
});
jQuery("#submitRegistration").click(function(){
if(typeof txtuname =='defined'){
alert("defined");
}
if(typeof txtuname =='undefined'){
alert("undefined");
}
});
});
Or use by replace jQuery by $ sign. It will work.
you can try this way too......
$("document").ready(function(){
var txtuname;
$("#txtuname").keyup(function(){
if($("#txtuname").val().length<6){
jQuery("label[for='txtuname']").text("user name is too short");
}
if($("#txtuname").val().length>=6){
txtuname=$("#txtuname").val();
jQuery("label[for='txtuname']").text("");
}
});
$("#submitRegistration").click(function(){
if(typeof txtuname=="undefined"){
alert("undefined");
}
else{
alert("defined");
}
});
});
I have a requirement of having a text-box with default value say "PF_". If I type something and press control+backspace All the values are been deleted. This problem occurs only If I have an underscore "_" at the end.
Javascript
var readOnlyLength = $('#field').val().length;
$('#output').text(readOnlyLength);
$('#field').on('keypress, keydown', function (event) {
var $field = $(this);
$('#output').text(event.which + '-' + this.selectionStart);
if ((event.which != 37 && (event.which != 39)) && ((this.selectionStart < readOnlyLength) || ((this.selectionStart == readOnlyLength) && (event.which == 8)))) {
return false;
}
});
Html
<input id="field" type="text" value="PF_" size="50" />
I have tried a sample fiddle.
Any Idea?
I'm not sure if this is what you're after, but this will reset the field to the previous value if the user tries to modify the read-only part:
$('#field').on('keypress, keydown', function (event) {
var $field = $(this);
var old = $field.val();
setTimeout(function(){
if($field.val().slice(0,3)!='PF_') {
$field.val(old);
}
},0);
});
Edit: in response to op's comments, try this code instead:
$('#field').on('keypress, keydown', function (event) {
var $field = $(this);
if(event.ctrlKey && event.which==8) { // ctrl-backspace
$field.val('PF_');
return false;
}
var old = $field.val();
setTimeout(function(){
if($field.val().slice(0,3)!='PF_') {
$field.val(old);
}
},0);
});
Fiddle
This is how I would do it:
$("#field").keyup(function(e){
if($(this).val().length < 3){
$(this).val("PF_");
}
});
Here is the JSFiddle demo
Here is my Fiddle
Initially the textbox won't have any value.
If any value is entered and it was emptied '0' will be added in it.
But the '0' is not removed after entering any value to it.
How can i remove the '0' if any value is entered it.
Here is my Code :
$('.qty').keyup(function(){
if($(this).val() == ""){
$('.qty').val('0');
}else if($(this).val() > 0){
$(this).val().replace(0,'');
}
});
Instead of
$('.qty').val('0');
Add palceholder.
$('.qty').attr('placeholder','0');
Try This Code:
$('.qty').keyup(function(){
if($(this).val() == ""){
$('.qty').val('0');
}else if($(this).val() > 0){
console.log($(this).val());
$(this).val().replace(0,'');
}
if($(this).val()!=0){
var text = $(this).val();
alert(text.slice(0,1));
if(text.slice(0,1)==0)
{
$(this).val(text.slice(1,text.length));
}
}
});
Working Demo
If placeholder isn't an option, you could parse value to integer:
$('.qty').keyup(function(){
var val = parseInt(this.value, 10);
this.value = val ? val: 0;
});
.replace() returns the modified string, you need to store it back into the value. Try this:
$('.qty').keyup(function () {
if ($(this).val() == "") {
$('.qty').val('0');
} else if ($(this).val() > 0) {
console.log($(this).val());
$(this).val(function() {
return this.value.replace(/^0+/, '');
});
}
});
I've also changed the replace() call to use a regular expression, so it only removes zeroes at the beginning of the input. Otherwise, it will change 102 to 12.
fiddle
You could achieve this using blur and focus instead of keyup :
$('.qty').blur(function() {
if (this.value == '') this.value = '0';
}).focus(function() {
if (this.value == '0') this.value = '';
});
JSFiddle example
Try this..
<input type="text" name="test" value="0">
$(document).ready(function(){
var Input = $('input[name=test]');
var value= Input.val();
$(Input).focus(function() {
if($(this).val() == value)
{
$(this).val("");
}
}).keyup(function(){
if($(this).val().length == 0)
{
$(this).val(value);
}
});
})
Try like this,
$('.qty').keyup(function(){
if($(this).val() == ""){
$('.qty').val('');
}else if($(this).val() > 0){
console.log($(this).val());
$(this).val().replace(0,'');
}
});
Instead of replace 0, replace with whole value using javascript Number function
$('.qty').keyup(function(){
if($(this).val() == ""){
$('.qty').val('0');
}else if($(this).val() > 0){
console.log($(this).val());
$(this).val(Number($(this).val()))
}
});
refer jsFiddle
$(document).ready(function() {
$('.watermark').focus(function() {
if (this.className == 'watermark')
{
this.className = '';
this.value = '';
}
});
$('.watermark').blur(function() {
if (this.value == '')
{
this.className = 'watermark';
this.value = 'Type here';
}
});
});
I have this block of code that works perfectly except that it is not dynamic. I was wondering if there was an elegant way to reset the value to the original dynamically. I was thinking that maybe if you defined the original text in its ID or some other sort of attribute you could reset it that way.. or maybe you could use variables or arrays or tuples. What does SO think is the best way of doing it?
How about storing the value into some other attribute of the input?
$(document).ready(function() {
$('.watermark').focus(function() {
if (this.className == 'watermark')
{
this.className = '';
this.title = this.value;
this.value = '';
}
});
$('.watermark').blur(function() {
if (this.value == '')
{
this.className = 'watermark';
this.value = this.title;
}
});
});
In this scenario i prefer to use html5(placeholder attrinute) with javascript fall back.
function supports_input_placeholder() {
var i = document.createElement('input');
return 'placeholder' in i;
}
$(document).ready(function() {
if (!supports_input_placeholder())
{
$('input').each(function(){
$(this).val($(this).attr('placeholder'))
});
$('input').focus(function() {
if (this.className == 'watermark')
{
this.className = '';
this.value = '';
}
});
$('input').blur(function() {
if (this.value == '')
{
this.className = 'watermark';
this.value = $(this).attr('placeholder');
}
});
}
});
This script will detect if native placeholder is available if not it will take text from placeholder attribute and simulate it.
You can just store it in a variable if it's scoped to each element:
$(function() {
$('.watermark').each(function() {
var lead = $(this).val();
$(this).focus(function() {
if ($(this).val() == lead) $(this).val('');
}).blur(function() {
if ($(this).val() == '') $(this).val(lead);
});
});
});
$(".box_yazi2").each(function () {
var default_value = this.value;
$(this).css('color', '#555'); // this could be in the style sheet instead
$(this).focus(function () {
if (this.value == default_value) {
this.value = '';
$(this).css('color', '#000');
}
});
$(this).blur(function () {
if (this.value == '') {
$(this).css('color', '#555');
this.value = default_value;
}
});
});
This function of default value of input doesnt work in FF, but perfectly works in IE
and ofcourse the input itself looks like this:
<input type="text" class="box_yazi2" id="konu" name="konu" value="Boş" />
Just use the defaultValue property:
var default_value = $(this).prop("defaultValue");
Or:
var default_value = this.defaultValue;
The solution is quite easy; you have an extra }); in your code (thanks # Box9).
I would encourage you to reuse the variable and not create dozens of jQuery objects.
I've changed your example to background-color but it will work.
$('.box_yazi2').each(function(index, element) {
var $element = $(element);
var defaultValue = $element.val();
$element.css('background-color', '#555555');
$element.focus(function() {
var actualValue = $element.val();
if (actualValue == defaultValue) {
$element.val('');
$element.css('background-color', '#3399FF');
}
});
$element.blur(function() {
var actualValue = $element.val();
if (!actualValue) {
$element.val(defaultValue);
$element.css('background-color', '#555555');
}
});
});
demo
$('input[type="text"]').focus( function(){
elementValue = $(this).val();
$(this).val("");
});
$('input[type="text"]').blur( function(){
if($(this).val() != elementValue && $(this).val() != ""){
}else{
$(this).val(elementValue);
}
});
I'm using the next code:
//clear the focused inputs
$('input[type="text"]').focus( function(){
if( $(this).attr('value') == $(this).attr('defaultValue') ){
$(this).attr('value', '');
};
} );
$('input[type="text"]').blur( function(){
if( $(this).attr('value') == '' ){
$(this).attr('value', $(this).attr('defaultValue') );
};
} );
Use this.defaultValue
Sorry for the link to w3notcools, http://www.w3schools.com/jsref/prop_text_defaultvalue.asp
You should use prop instead of so many functions to be honest, use 'delegate' instead of 'on' for late static binding.
$('.box_yazi2').each(function() {
$(this).on('focus', function(){
if($(this).val() == $(this).prop('defaultValue')){
$(this).val('');
$(this).css('color', '#000');
}
});
$(this).on('blur', function(){
if($(this).val() == ''){
$(this).val($(this).prop('defaultValue'));
$(this).css('color', '#000');
}
});
});