This is probably stupidity on my part, but where am I going wrong with this?
$(function() {
$('textarea#comment').each(function() {
var $txt = $(this).val();
$(this).bind('focus', function() {
if($(this).val($txt)) {
$(this).val('');
}
});
});
});
Basically on focus I want to check if the value is the default value in this case 'Enter your comment', then if it is change the value to nothing.
Anyone know how to do this? I'm guessing its relatively simple. What the code does at the moment is removes any value.
Ok first off you should only have one tag with the id of comment since ids are supposed to be unique, but if we go with your code you have to setup a default value first like this:
<textarea id="comment">Enter text here</textarea>
Now the javascript:
(function() {
$('textarea#comment').each(function() {
var $txt = $(this).val();
//alert($txt);
$(this).bind('focus', function() {
if($(this).val() === this.defaultValue) {
$(this).val('');
}
});
});
})();
The self executing function syntax has been corrected here and should be as follow:
(function () { // my code here })();
and for default value use:
this.defaulValue; // works for input boxes as well
Hope it helps. Cheers
jquery_example plugin do exactly what you need. You may have a look at its source code and get some inspiration. Or you can store the default value as meta-data on the tag and check against it on change event of the textarea tag.
try
$('#comment').live('click change focus', function() {
var $txt = $(this).val();
if($txt == 'Enter your comment' );
$(this).val('');
});
DEMO
Related
Check the html code bellow. The id foo input taking a text then cloning to another input id doo. As you can see in jquery code i am simply passing the value from foo to doo. But my problem is when i try to get value of doo on second part of code in jquery i dont get updated value of doo. Thing is that if i write input in foo then it virtually displays in doo but in real this not changing i think. So what i want is- when i pass input in foo it will also trigger in doo value. Since i am also updating doo from foo. Ask question if you want to know anything more. Thanks in advance
jsfiddle link
Jquery:
$("#foo").keyup(function () {
$('#doo').val($(this).val());
});
$("#doo").on("change paste keyup", function () {
var tryGetNewValue = $('#doo').val();
console.log(tryGetNewValue);
});
Html:
<input type="text" id="foo" value=""><br>
<br>
<input type="text" id="doo" value=""><br>
The problem is that the functions are running at the same time and the value of doo hasn’t changed in time for the function. I would change your js code to this:
$("#foo").keyup(function () {
$('#doo').val($(this).val());
var tryGetNewValue = $('#doo').val();
console.log(tryGetNewValue);
});
$("#doo").on("paste keyup", function () {
var tryGetNewValue = $('#doo').val();
console.log(tryGetNewValue);
});
And then obviously run whatever you would run in both places where you have the var tryGetNewValue running
The change event does not get triggered because only input directly from the user into the element can set it off (see https://developer.mozilla.org/en-US/docs/Web/Events/change).
As for a way to allow this to work, you can use a function for each event like so:
$("#foo").keyup(function () {
$('#doo').val($(this).val());
changeEvent();
});
$("#doo").on("change paste keyup", function () {
changeEvent()
});
function changeEvent(){
var tryGetNewValue = $('#doo').val();
console.log(tryGetNewValue);
}
It's better use deligate function of jquery. Both function change both input values.
$(document).on("input paste keyup","#doo,#foo", function (e) {
$("#foo").val($(this).val());
$("#doo").val($(this).val());
var tryGetNewValue = $(this).val();
console.log(tryGetNewValue);
});
You can even get same thing like below to
$( "body" ).delegate( "#doo, $foo", "input paste keyup", function(e) {
$("#foo").val($(this).val());
$("#doo").val($(this).val());
var tryGetNewValue = $(this).val();
console.log(tryGetNewValue);
});
The User should be able to change the Name and then confirm the change. I'm not able to archive it with this code as when I click confirm, it returns like before.
What am I missing?
Any better way to put this together (which I'm sure there's one) ?
Please check the demo where you can also see the changeElementTypefunction
http://jsfiddle.net/dLk6E/
js:
$('.replace').on('click', function () {
$("h2").changeElementType("textarea");
$('.replace').hide();
$('.confirm').show();
//Confermation of the change
$('.confirm').bind('click', function () {
$('.replace').show();
$('.confirm').hide();
$("textarea").changeElementType("h2");
});
if ($('textarea:visible')) {
$(document).keypress(function (e) {
if (e.which == 13) {
alert('You pressed enter!');
$("textarea").changeElementType("h2");
$('.replace').css('opacity', '1');
}
});
}
});
Here are your updated code and working fiddle http://jsfiddle.net/dLk6E/
(function($) {
$.fn.changeElementType = function(newType) {
var attrs = {};
$.each(this[0].attributes, function(idx, attr) {
attrs[attr.nodeName] = attr.nodeValue;
});
this.replaceWith(function() {
return $("<" + newType + "/>", attrs).append($(this).contents());
});
}
})(jQuery);
$('.replace').on('click', function (){
$("h2").changeElementType("textarea");
$('.replace').hide();
$('.confirm').show();
//Confermation of the change
$('.confirm').on('click', function(){
$('.replace').show();
$('.confirm').hide();
// you are missing this
$('.replaceble').html($("textarea").val());
$("textarea").changeElementType("h2");
});
if ($('textarea:visible')){
$(document).keypress(function(e) {
if(e.which == 13) {
alert('You pressed enter!');
$("textarea").changeElementType("h2");
$('.replace').css('opacity','1');
}
});
}
});
updated
jsfiddle.net/dLk6E/1
I think your code is right but you need to use the value you're entering when replacing it. So the confirmation binding would be something like this (fetching it, and then using it to update the textarea before "transforming" it into an h2 tag.
$('.confirm').bind('click', function(){
var valueEntered = $('textarea').val();
$('.replace').show();
$('.confirm').hide();
$("textarea").html(valueEntered).changeElementType("h2");
});
You could be using .on for this as well as of jQuery 1.7 is prefered to .bind.
Another thing I would suggest is whenever you struggle with something like this just put in google (or whatever...) exactly what you want, in this case "jquery get value of input" will get asw first result the jquery documentation
This way you won't forget it ;)
Update: Maybe a small detail but in the binding I use it would be more efficient to just hit $('textarea') once, so it would be something like this. Something that you may keep in mind (not really an issue here), better to store in a variable than hit the DOM several times.
$('.confirm').on('click', function(){
var $textarea = $('textarea');
$('.replace').show();
$('.confirm').hide();
$textarea.html($textarea.val()).changeElementType("h2");
});
jsfiddle
I facing problem with my jquery, on showing input text based on input value.
Here is the JS fiddle demo :
http://jsfiddle.net/Ltapp/364/
When I try to input #hotmail, the input box will show. But when I want to type some text in the #hotm input box, it will hide again.
JS code :
$(window).load(function(){
var myString = '#hotmail';
$('#hotm').hide();
$("input").keyup(function () {
var value = $(this).val();
if($(this).val().match(myString)) {
$('#hotm').show();
} else {
$('#hotm').hide();
}
});
});
It's because your selector $("input") affects both input elements. I have updated it to the $("input:first") selector instead. JsFiddle here
$("input:first").keyup(function () {
var value = $(this).val();
if(value.match(myString)) {
$('#hotm').show();
} else {
$('#hotm').hide();
}
});
As many has said, you are binding the event on all the inputs I did a little change:
$(function(){
var myString = /#hotmail/ig;
$("#check").bind('keyup checkvalue', function() {
$('#hotm')[myString.test(this.value) ? 'show' : 'hide']();
}).trigger('checkvalue');
});
using regex if you are using #HoTmAil it will also hit on that, and also added a custom event checkvalue to see if #hotm should be visible on for example a postback on the form you might be using.
demo: http://jsfiddle.net/voigtan/xjwvT/1/
You're affecting all inputs. Either give each one a unique ID / Class or use the jQuery $(this) method.
See JSFiddle Here:
http://jsfiddle.net/Ltapp/366/
<input type="text" id="firstinput"/>
<p id="secondinput"><input type="text"/></p>
var myString = '#hotmail';
$('#secondinput').hide();
$("#firstinput").keyup(function () {
var value = $(this).val();
if($(this).val().match(myString)) {
$('#secondinput').show();
} else {
$('#secondinput').hide();
}
});
use this for your if part :
if($(this).val().match($(this).val().substr(0,strlen($(this).val())))
it's because the new box also = "input"; if you give the hotmail textbox it's own id, it won't hide
<input id="hotmail" type="text"/>
and then
$("#hotmail").keyup(function () {...});
I have a div that I need to grab the HTML contents of (so naturally I use html())...
However, they are text fields. Whenever I grab the contents of the div (that contains the text fields), it grabs the initial HTML and not any data changed by the end user...
Here is JS bin version..change the input field, run the function and you see that it will only take the initial value of the field...
Any way around this?
http://jsbin.com/oleni3/edit
http://jsbin.com/oleni3/5/edit
Try this out ^
The code:
$(document).ready(function() {
$('div#top input').change(function() {
$(this).attr('value', $(this).val());
});
$('#click').click(function() {
var _curHtml = $("div#top").html();
$("div#bottom").html(_curHtml);
});
});
Your getting the HTML of the div. You want to get the value of the input box:
$(document).ready(function() {
$('#click').click(function() {
var _curHtml = $("#data").val();
$("div#bottom").html(_curHtml);
});
});
No way to do it with html(). You'll have to get the value of each input using val(). You can use
$("input").each(function() {
doSomething($(this).val());
}
if it make life easier.
$(document).ready(function() {
$('#click').click(function() {
var _curHtml = $("#data").val();
$("div#bottom").html(_curHtml);
});
});
The easiest hack would be like this:
$("div#bottom input").val($("div#top input").val());
Get the value of the updated input and set that to the clone.
Updated link:
http://jsbin.com/oleni3/3/edit
$(document).ready(function() {
$('#data').change(function() {
$(this).attr('value', $(this).val());
})
$('#click').click(function() {
var _curHtml = $("div#top").html();
$("div#bottom").html(_curHtml);
});
});
This works.. here's the link http://jsbin.com/oleni3/2/edit
UPDATE: If you have many inputs inside the div, you can use this http://jsbin.com/oleni3/6/edit
How do you detect which form input has focus using JavaScript or jQuery?
From within a function I want to be able to determine which form input has focus. I'd like to be able to do this in straight JavaScript and/or jQuery.
document.activeElement, it's been supported in IE for a long time and the latest versions of FF and chrome support it also. If nothing has focus, it returns the document.body object.
I am not sure if this is the most efficient way, but you could try:
var selectedInput = null;
$(function() {
$('input, textarea, select').focus(function() {
selectedInput = this;
}).blur(function(){
selectedInput = null;
});
});
If all you want to do is change the CSS for a particular form field when it gets focus, you could use the CSS ":focus" selector. For compatibility with IE6 which doesn't support this, you could use the IE7 library.
Otherwise, you could use the onfocus and onblur events.
something like:
<input type="text" onfocus="txtfocus=1" onblur="txtfocus=0" />
and then have something like this in your javascript
if (txtfocus==1)
{
//Whatever code you want to run
}
if (txtfocus==0)
{
//Something else here
}
But that would just be my way of doing it, and it might not be extremely practical if you have, say 10 inputs :)
I would do it this way: I used a function that would return a 1 if the ID of the element it was sent was one that would trigger my event, and all others would return a 0, and the "if" statement would then just fall-through and not do anything:
function getSender(field) {
switch (field.id) {
case "someID":
case "someOtherID":
return 1;
break;
default:
return 0;
}
}
function doSomething(elem) {
if (getSender(elem) == 1) {
// do your stuff
}
/* else {
// do something else
} */
}
HTML Markup:
<input id="someID" onfocus="doSomething(this)" />
<input id="someOtherID" onfocus="doSomething(this)" />
<input id="someOtherGodForsakenID" onfocus="doSomething(this)" />
The first two will do the event in doSomething, the last one won't (or will do the else clause if uncommented).
-Tom
Here's a solution for text/password/textarea (not sure if I forgot others that can get focus, but they could be easily added by modifying the if clauses... an improvement could be made on the design by putting the if's body in it's own function to determine suitable inputs that can get focus).
Assuming that you can rely on the user sporting a browser that is not pre-historic (http://www.caniuse.com/#feat=dataset):
<script>
//The selector to get the text/password/textarea input that has focus is: jQuery('[data-selected=true]')
jQuery(document).ready(function() {
jQuery('body').bind({'focusin': function(Event){
var Target = jQuery(Event.target);
if(Target.is(':text')||Target.is(':password')||Target.is('textarea'))
{
Target.attr('data-selected', 'true');
}
}, 'focusout': function(Event){
var Target = jQuery(Event.target);
if(Target.is(':text')||Target.is(':password')||Target.is('textarea'))
{
Target.attr('data-selected', 'false');
}
}});
});
</script>
For pre-historic browsers, you can use the uglier:
<script>
//The selector to get the text/password/textarea input that has focus is: jQuery('[name='+jQuery('body').data('Selected_input')+']')
jQuery(document).ready(function() {
jQuery('body').bind({'focusin': function(Event){
var Target = jQuery(Event.target);
if(Target.is(':text')||Target.is(':password')||target.is('textarea'))
{
jQuery('body').data('Selected_input', Target.attr('name'));
}
}, 'focusout': function(Event){
var Target = jQuery(Event.target);
if(Target.is(':text')||Target.is(':password')||target.is('textarea'))
{
jQuery('body').data('Selected_input', null);
}
}});
});
</script>
You only need one listener if you use event bubbling (and bind it to the document); one per form is reasonable, though:
var selectedInput = null;
$(function() {
$('form').on('focus', 'input, textarea, select', function() {
selectedInput = this;
}).on('blur', 'input, textarea, select', function() {
selectedInput = null;
});
});
(Maybe you should move the selectedInput variable to the form.)
You can use this
<input type="text" onfocus="myFunction()">
It triggers the function when the input is focused.
Try
window.getSelection().getRangeAt(0).startContainer