JQuery .select after setting value using .val - javascript

I have two Radtextboxes (telerik) in two tabstrips inside my html. I want to set the value of each based on the change made by user on other. I have achived using following code:
function OnUsernameChanged() {
$('#txtUserNameTab1').focus(function (e) {
$(this).select();
});
$('#txtUserNameTab2').focus(function (e) {
$(this).select();
});
$('#txtUserNameTab1').bind('keypress blur keyup', function (e) {
var userNameValue = $(this).val();
$('#txtUserNameTab2').val($(this).val());
});
$('#txtUserNameTab2').bind('keypress blur keyup', function (e) {
var userNameValue = $(this).val();
$('#txtUserNameTab1').val($(this).val());
});
}
Its all working fine with updating the value of second textbox when first's value is changed and vice versa. But the issue is with select, when focussed on any of the textbox, it always does a select all on that textbox, but the value gets changed to initial value of the textbox.

I have created a fiddle that works the way you wanted with textbox controls.
http://jsfiddle.net/ZeEXp/1/
JS:
$('#txtUserNameTab1,#txtUserNameTab2').mouseup(function() {
$(this).select();
});
$('#txtUserNameTab1').bind('keyup', function (e) {
var userNameValue = $(this).val();
$('#txtUserNameTab2').val($(this).val());
});
$('#txtUserNameTab2').bind('keyup', function (e) {
var userNameValue = $(this).val();
$('#txtUserNameTab1').val($(this).val());
});
HTML:
<textarea id="txtUserNameTab1">asdfasdfa</textarea>
<textarea id="txtUserNameTab2">563gh45</textarea>

Related

why changing input doesn't trigger on change event?

I am trying to get change value of input when its values are changed.
http://jsfiddle.net/stackmanoz/694W9/
$(function () {
$('.color-iris').iris();
$('#color').on('change', function () {
console.log($(this).val());
});
});
I am using color-picker and after the input's value has changed with the new color value, I want to get its value.
But this is not going well.
Please guide me through this
Use option change
$(function () {
$('.color-iris').iris({
change: function () {
console.log(this.value);
}
});
});
DEMO
Change event would be fired only when that textbox value changes as wel as focus is getting blurred out from the particular text box,so in this context you have to use input
$(function () {
$('.color-iris').iris();
$('#color').on('input', function () {
console.log($(this).val());
}) ;
});
DEMO

Jquery - How to copy an input that has a value on load

I have a website url field that has the value set for returning visitors who have previously filled out the form. If they change the value, then ('keyup blur paste', function() will copy it to a div. If they do not change the value, the ('keyup blur paste', function() does not copy the value to the div
I would like to figure out how to add to this script a function that would also copy the value to the div if they do not change it, because blur only works if they click in the input before they submit the form.
Here is my current script:
$(function () {
$('#Website').on('keyup blur paste', function() {
var self = this;
setTimeout(function() {
var str = $(self).val();
$("#viewer").text(str.replace(/^http\:\/\//, ''));
}, 0)
})
});
If I get you correctly, you want to populate the div on load as well as on keyup/blur/paste? Something like this?
$(function () {
$('#Website').on('keyup blur paste', function() {
var self = this;
setTimeout(function() {
var str = $(self).val();
$("#viewer").text(str.replace(/^http\:\/\//, ''));
}, 0)
});
// just add the line below
$("#viewer").text($('#Website').val().replace(/^http\:\/\//, ''));
});
I've updated the fiddle you created to demonstrate this working: http://jsfiddle.net/8kn4V/2/
on your page load...
$('#mydiv').html('whatever the value of the cookie');
is that what you need? as they mentioned in the comments above, your question is a little confusing.
use val() for input , select and textareas, and use text() for general elements like divs.
First solution
It seems now you are using a timeout of 0. That is not necessary at all, I think. So please check out this Fiddle:
$('#website').on("keyup blur paste", function () {
var s = $(this).text();
$("#viewer").text(s.replace(/^http\:\/\//, ''));
});
Edited solution
Now it seems you also want code that update #viewer from #website even when not triggered.
Here is a second fiddle — I hope you'll give credit if this solves the problem as it stands currently.
Relevant code:
function viewerupdate(me){
var s = me.text();
$("#viewer").text(s.replace(/^http\:\/\//, ''));
}
$('#website').on("keyup blur paste", function () { viewerupdate($(this)) });
var current_viewer = $('#viewer').text();
$('#submit').click(function(){ // assumes in the case that no change was made, that the submission is done through #submit
if($('#viewer').text() == current_viewer )
viewerupdate($('#website'));
});

Global click event blocks element's click event

This should happen
If the user clicks on one of the two input boxes, the default value should be removed. When the user clicks elswhere on the webpage and one text field is empty, it should be filled with the default value from the data-default attribute of the spefic element.
This happens
When somebody clicks somewhere on the page and the field is empty, the field will be filled with the right value, but when somebody clicks in the field again the text isn't removed. It seems like the $(document) click event is blocking the $(".login-input") click event, because the $(".login-input") is working without the $(document) click event.
JSFiddle
A sample of my problem is provieded here: JSFiddle
Tank you for helping!
When you click on the input, the script is working, but since the input is in the document, a click on the input is a click on the document aswell. Both function will rune, document is the last one.
That is called event bubblingand you need to stop propagation :
$(document).ready(function () {
$(".login-input").click(function (e) {
e.stopPropagation()
$(this).val("");
});
});
Fiddle : http://jsfiddle.net/kLQW9/3/
That's not at all how you solve placeholders, you do it like so :
$(document).ready(function () {
$(".login-input").on({
focus: function () {
if (this.value == $(this).data('default')) this.value = '';
},
blur: function() {
if (this.value == '') this.value = $(this).data('default');
}
});
});
FIDDLE
Preferably you'd use the HTML5 placeholder attribute if really old browsers aren't an issue.
EDIT:
if you decide to do both, check support for placeholders in the browser before applying the javascript :
var i = document.createElement('input'),
hasPlaceholders = 'placeholder' in i;
if (!hasPlaceholders) {
// place the code above here, the condition will
// fail if placeholders aren't supported
}
Try below code
$(document).ready(function () {
$(".login-input").click(function () {
$(this).val("");
});
});
$(document).ready(function () {
$(".login-input").each(function () {
if ($(this).val() === "") {
$(this).val($(this).attr("data-default"));
}
});
$(".login-input").blur(function () {
if ($(this).val() === "") {
$(this).val($(this).attr("data-default"));
}
});
});
Check fiddle
Why not to use focus and blur events?
$(document).ready(function () {
$(".login-input").focus(function () {
$(this).val("");
});
});
$(document).ready(function () {
$(".login-input").blur(function () {
if ($(this).val() === "") {
$(this).val($(this).attr("data-default"));
}
});
});
http://jsfiddle.net/kLQW9/5/
P.S. In yours, and this code, on focus all data fro input will be cleared. If you need to clear only default text, add proper condition for that.

How can I update a input using a div click event

I've got the following code in my web page, where I need to click on the input field and add values using the number pad provided! I use a script to clear the default values from the input when the focus comes to it, but I'm unable to add the values by clicking on the number pad since when I click on an element the focus comes from the input to the clicked number element. How can I resolve this issue. I tried the following code, but it doesn't show the number in the input.
var lastFocus;
$("#test").click(function(e) {
// do whatever you want here
e.preventDefault();
e.stopPropagation();
$("#results").append(e.html());
if (lastFocus) {
$("#results").append("setting focus back<br>");
setTimeout(function() {lastFocus.focus()}, 1);
}
return(false);
});
$("textarea").blur(function() {
lastFocus = this;
$("#results").append("textarea lost focus<br>");
});
Thank you.
The first thing I notice is your selector for the number buttons is wrong
$('num-button').click(function(e){
Your buttons have a class of num-button so you need a dot before the class name in the selector:
$('.num-button').click(function(e){
Secondly, your fiddle was never setting lastFocus so be sure to add this:
$('input').focus(function() {
lastFocus = this;
...
Thirdly, you add/remove the watermark when entering the field, but ot when trying to add numbers to it (that would result in "Watermark-text123" if you clicked 1, then 2 then 3).
So, encalpsulate your functionality in a function:
function addOrRemoveWatermark(elem)
{
if($(elem).val() == $(elem).data('default_val') || !$(elem).data('default_val')) {
$(elem).data('default_val', $(elem).val());
$(elem).val('');
}
}
And call that both when entering the cell, and when clicking the numbers:
$('input').focus(function() {
lastFocus = this;
addOrRemoveWatermark(this);
});
and:
$('.num-button').click(function(e){
e.preventDefault();
e.stopPropagation();
addOrRemoveWatermark(lastFocus);
$(lastFocus).val($(lastFocus).val() + $(this).children('span').html());
});
You'll see another change above - you dont want to use append when appends an element, you want to just concatenate the string with the value of the button clicked.
Here's a working branch of your code: http://jsfiddle.net/Zrhze/
This should work:
var default_val = '';
$('input').focus(function() {
lastFocus = $(this);
if($(this).val() == $(this).data('default_val') || !$(this).data('default_val')) {
$(this).data('default_val', $(this).val());
$(this).val('');
}
});
$('input').blur(function() {
if ($(this).val() == '') $(this).val($(this).data('default_val'));
});
var lastFocus;
$('.num-button').click(function(e){
e.preventDefault();
e.stopPropagation();
var text = $(e.target).text();
if (!isNaN(parseInt(text))) {
lastFocus.val(lastFocus.val() + text);
}
});
Live demo
Add the following function:
$('.num-button').live( 'click', 'span', function() {
$currObj.focus();
$currObj.val( $currObj.val() + $(this).text().trim() );
});
Also, add the following variable to global scope:
$currObj = '';
Here is the working link: http://jsfiddle.net/pN3eT/7/
EDIT
Based on comment, you wouldn't be needing the var lastFocus and subsequent code.
The updated fiddle lies here http://jsfiddle.net/pN3eT/28/

Using jquery to monitor form field changes

Trying to learn some jquery to implement an autosave feature and need some assistance. I have some code to monitor the status of form fields to see if there has been any change. Everything works, but I need to only monitor the changes in a specific form, not all form inputs on the page. There is a search box and a newsletter form on the same page and when these form fields are changed, they are detected as well, which I need to filter out somehow or better yet, only target the specific form.
$(function(){
setInterval("CheckDirty()",10000);
$(':input').each(function() {
$(this).data('formValues', $(this).val());
});
});
function CheckDirty()
{
var isDirty = false;
$(':input').each(function () {
if($(this).data('formValues') != $(this).val()) {
isDirty = true;
}
});
if(isDirty == true){
alert("isDirty=" + isDirty);
}
}
Just add a class to the form and use it to filter
$('.form :input').each(function() {
$(this).data('formValues', $(this).val());
});
EDIT
Just a suggestion, you can attach the change event directly to the form
live demo here : http://jsfiddle.net/jomanlk/kNx8p/1/
<form>
<p><input type='text'></p>
<p><input type='text'></p>
<p><input type='checkbox'></p>
</form>
<p><input type='text'></p>
<div id='log'></div>
$('form :input').change(function(){
$('#log').prepend('<p>Form changed</p>')
});
You can easily improve this by adding a timer and making it save every xx seconds.
var $jq= jQuery.noConflict();
$jq(function() { $jq('#extensibleForm').data('serialize',$jq('#extensibleForm').serialize());
});
function formHasChanged(){
if($jq('#extensibleForm').serialize()!=$jq('#extensibleForm').data('serialize')){
alert("Data Changed....");
return (false);
}
return true;
}
what's your form's id?
you just need to make your selector more specific :)
instead of $(':input').each(function() {
use
$('#yourFormId').find(':input').each(function() {
You can use the .change() function and then use $(this) to denote you want to work with just the field that is actively being changed.
$('#myForm input[type="text"]').change(function() {
$(this)...
});
Edit: #myForm is your form ID so you can target a specific form. You can even specify just type="text" fields within that form, as in my example.
Here you can see it working: http://jsfiddle.net/paska/zNE2C/
$(function(){
setInterval(function() {
$("#myForm").checkDirty();
},10000);
$("#myForm :input").each(function() {
$(this).data('formValues', $(this).val());
});
$.fn.checkDirty = function() {
var isDirty = false;
$(this).find(':input').each(function () {
if($(this).data('formValues') != $(this).val()) {
isDirty = true;
}
});
if(isDirty == true){
alert("isDirty=" + isDirty);
}
};
});
I think you can use a class to select the type of input you want.
<input class="savethis" ... />
Then in jQuery use this.
$(':input .savethis').each(function() { ...
You can specify an id attribute (say theForm) to your form element and then select only those input fields inside it.
then try selecting with
$(':input', '#theForm')
I respect all the working answers but for me I think using the focus event might be much better than change event. This is how I accomplished my watchChange() function is JS:
var changeInterval = 0;
var changeLength = 0; //the length of the serverData
var serverData = {value:''}; //holds the data from the server
var fieldLength = 0; //the length of the value of the field we are tracking
var frequency = 10000;
function watchChange() {
$input.on('focus', function() {
var $thisInput = $(this);
//we need the interval value so that we destroy
//setInterval when the input loses focus.
changeInterval = setInterval(function() {
changeLength = serverData.value.length;
fieldLength = $thisInput.val().length;
//we only save changes if there is any modification
if (changeLength !== fieldLength) {
$.ajax({
url: 'path/to/data/handler',
dataType: 'json',
data: "data=" + $thisInput.val(),
method: 'post'
}).done(function(data) {
serverData = data;
}); //end done
} //end if
}, frequency); //end setInterval
//and here we destroy our watcher on the input
//when it loses focus
}).on('blur', function() {
clearInterval(changeInterval);
});
}
Even though this approach seems to be naive but it gave me what I wanted!

Categories

Resources