textarea.val() value changing but not displaying on page - javascript

I have a textarea like so,
<textarea id="txtaFilter" cols="45" rows="5"></textarea>
and the following script,
$(document).ready(function () {
$(".selector").bind('change', function () {
var value = $(this).val();
$("#txtaFilter").val($("#txtaFilter").val() + value);
$(this).children('option:eq(0)').prop('selected', true);
});
});
where ".selector" is a class applied to two dropdownlists.
When I chose a value on the dropdown, it appears to do nothing, but after looking at the debugger in chrome it is changing the value just not displaying it.
Does anyone know why this is? Is there something special I'm missing about the .val() property?
Problem/Solution:
I forgot that there are multiple "#txtaFilter"'s on the page when I removed the $(this).siblings("#txtaFilter"), So it was accessing the hidden one instead of the visible one. Sorry about that, guess I was wrong on the question too :/

You can use val method:
$("#txtaFilter").val(function(i, oldVal){
return oldVal + value
});

Use .val() to get the text of a textarea.
$(document).ready(function () {
$(".selector").bind('change', function () {
var value = $(this).val();
var txtaFilter = $("#txtaFilter");
txtaFilter.val(txtaFilter.val()+value);
$(this).children('option:eq(0)').attr('selected', true);
});
});

Related

Issues displaying a dynamically updated HTML input value

I'm struggling to get the behaviour I need - as follows:
A HTML form is pre-populated with a value via jQuery. When the user focuses on the input field I want the form to clear. On blur from the form, the form should repopulate the form with the existing value.
I have a solution that clears and repopulates the form but it fails as soon as anything is typed in.
This is what I have so far:
var x = "Default";
$(function () {
$("input").attr({
"value": x
});
$("input").focus(function () {
$("input").attr({
"value": ""
});
});
$("input").blur(function () {
$("input").attr({
"value": x
});
});
});
https://jsfiddle.net/thepeted/p74kfdt8/6/
If I look in developer tools, I can see the input value is changing dynamically in the DOM, but in the case that the user has typed something in to the form, the display no longer updates.
I'd love to understand why this is happening (ie, why it works in one case and not the other). Also, if there is a better way of approaching the problem.
As pointed out by Stijn, best practice would be to use the placeholder attibute.
However if you do want to use a function for it. I would check on the focus if the value is the default value or not. If so, empty the input, if not, don't do anything.
On blur, you also only want to place the default value back if the value is empty... so check for that aswell.
var x = "Default";
$(function() {
$('input[type=text]').val(x);
$('input[type=text]').on('focus', function() {
var elem = $(this);
if (elem.val() == x)
elem.val('');
}).on("blur", function() {
var elem = $(this);
if (elem.val() == '')
elem.val(x);
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" />
Your edited jsfiddle.
updated code:
$("input").blur(function () {
$("input").val(x);
});
Personnaly, I'd use the placeholder attribute as everyone pointed out. If you too are facing the need to support older browsers and some others that do not support the placeholder attribute, use this snippet I've made:
$('input[placeholder]').each(function(){
var $this = $(this);
$this.val($this.attr('placeholder')).css('color','888888');
$this.focus(function(){
if($(this).val() == $(this).attr('placeholder'))
$(this).val('').css('color','');
});
$this.blur(function(){
if($(this).val() == '')
$(this).val($(this).attr('placeholder')).css('color','888888');
});
});
This script will find all inputs with a placeholder attribute, give it's value to the input, and add the correct events. I've left the css calls just to show you where to put the codes to mimic the greyed text like modern browsers do.
Try this code
var x = "Default";
$(function () {
$("input").val(x);
$("input").focus(function () {
$("input").val("");
});
$("input").blur(function () {
$("input").val(x);
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<input type="text"/>

How to get the value of a select tag which doesn't change on hover?

I'm using jQuery's .val() function to read the value of a <select> tag.
It seems that, at least in Firefox, .val() returns the value of the option the user is currently hovering over. You can see this behaviour at this jsfiddle.
Is there any way using jQuery or pure javascript to get the value that is shown in the select box, i.e. the last value that actually fired a change event?
Original Idea
function foo() {
var value = $('#select').val();
// do something that depends on value
}
The problem with this is that I only want foo() to use the value that is currently selected. By selected I mean the option that was clicked. In the fiddle, you can see that this value changes as you hover over options.
Alternative
var value;
$('#select').change(function() {
value = $('#select').val();
}
function foo() {
// do something with value
}
This is OK, but the information appears to exist in the DOM, since the last clicked value is displayed in the select box.
So, my question is, is it possible to get the last clicked option from the DOM?
You can do this on the change event instead of by interval
UPDATED CODE based on comments below
$('#bar').on('change', function(){
var $t =$(this) , value=$t.val();
$t.attr('data-answer', value);
});
setInterval(function(){
$('#foo').text($('#bar').attr('data-answer'));
},1000);
your select would have this attribute on it
<select id="bar" data-answer="" >
//options here
</select>
Or using .data method:
$('#bar').on('change', function(){
var $t =$(this) , value=$t.val();
$t.data('answer', value);
});
setInterval(function(){
$('#foo').text($('#bar').data('answer'));
},1000);
Sounds like you're looking for focus()
$("select").focus(function () {
var focusValue = this.value;
$('#foo').text(focusValue);
})
You can chain the event listener focus with change to find the current value and then the selected.
$("select").focus(function () {
var focusValue = this.value;
$('#foo').text(focusValue);
}).change(function() {
var changeValue = this.value
$('#foo').text(changeValue);
});
Here is a jsFiddle 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'));
});

How to know with jQuery that a "select" input value has been changed?

I know that there is the change event handling in jQuery associated with an input of type select. But I want to know if the user has selected another value in the select element ! So I don't want to run code when the user select a new element in the select but I want to know if the user has selected a different value !
In fact there are two select elements in my form and I want to launch an ajax only when the two select elements has been changed. So how to know that the two elements has been changed ?
You can specifically listen for a change event on your chosen element by setting up a binding in your Javascript file.
That only solves half your problem though. You want to know when a different element has been selected.
You could do this by creating a tracking variable that updates every time the event is fired.
To start with, give your tracking variable a value that'll never appear in the dropdown.
// Hugely contrived! Don't ship to production!
var trackSelect = "I am extremely unlikely to be present";
Then, you'll need to set up a function to handle the change event.
Something as simple as:-
var checkChange = function() {
// If current value different from last tracked value
if ( trackSelect != $('#yourDD').val() )
{
// Do work associated with an actual change!
}
// Record current value in tracking variable
trackSelect = $('#yourDD').val();
}
Finally, you'll need to wire the event up in document.ready.
$(document).ready(function () {
$('#yourDD').bind('change', function (e) { checkChange() });
});
First of all you may use select event handler (to set values for some flags). This is how it works:
$('#select').change(function () {
alert($(this).val());
});​
Demo: http://jsfiddle.net/dXmsD/
Or you may store the original value somewhere and then check it:
$(document).ready(function () {
var val = $('#select').val();
...
// in some event handler
if ($('#select').val() != val) ...
...
});
First you need to store previous value of the selected option, then you should check if new selected value is different than stored value.
Check out the sample!
$(document).ready(function() {
var lastValue, selectedValue;
$('#select').change(function() {
selectedValue = $(this).find(':selected').val();
if(selectedValue == lastValue) {
alert('the value is the same');
}
else {
alert('the value has changed');
lastValue = selectedValue;
}
});
});​
You can save the value on page load in some hidden field.
like
$(document).ready(function(){
$('hiddenFieldId').val($('selectBoxId').val());
then on change you can grab the value of select:
});
$('selectBoxId').change(function(){
var valChng = $(this).val();
// now match the value with hidden field
if(valChng == $('hiddenFieldId').val()){
}
});
$("select").change(function () {
var str = "";
$("select option:selected").each(function () {
str += $(this).text() + " ";
});
$("div").text(str);
})
.change();
http://docs.jquery.com/Events/change

how to know the old value of an element onChange or onTrigger in JQuery?

I have a button :
<button id="btn1">55</button>
And so I change the button value to test2
$('#btn1').text("22");
I want to show a background-picture if the buttons oldValue greater then the newValue.
How can I get the old value from this button?
"I have over 100 buttons and they are changing dynamically."
Update: Isn't there an event that fires before it changes?
You could use jQuery's .data() call and store it for retrieval as needed.
For instance, say you HTML is:
HTML
<form action="#" method="GET">
<input type="text" value="369" />
<button id="btnID">420</button>
</form>
You could easily first gather the data needed and asign it to each element:
Opening script
$("button") // would simply grab all buttons, you can use whatever css selector
.each(function(i) {
$(this).data("prevVal", parseInt($(this).text()));
});
You can then later check this value against a new value as needed:
... some change function
$('#btn1').text("22");
if ($('#btn1').data("prevVal") > 22) {
// do work
}
$('#btn1').data("prevVal", 22)
Just FYI
If you were using inputs instead it would be easier:
$("input").each(function(i) { $(this).data("prevVal", parseInt($(this).val())) })
.on("change", function(e) {
var newVal = parseInt($(this).val());
if ($(this).data("prevVal") > newVal) {
// do work
};
$(this).data("prevVal" newVal);
});
Or if you wanted to maintain a list of values:
$("input").each(function(i) {
$(this).data("vals", new Array());
$(this).data("vals").push(parseInt($(this).val()));
})
.on("change", function(e) {
$(this).data("vals").push(parseInt($(this).val()));
var vals = $(this).data("vals");
if (vals[vals.length-1] > vals[vals.length-2]) {
// do work
};
});
You need to compare it before changing value.
For example
$('#btn1').text(function (index, old) {
if (parseInt(old) > 22) {
//change background image
}
return "22";
});
FIDDLE
Unless you preserve it before the change you cannot get the old value. The change event is fired after the value has been changed already.
Not sure where you want the old value.. but if it while changing the text then use the function to change the text.
$('#btn1').text(function (index, oldvalue) {
console.log(oldvalue);
return "test2";
});
<button id="btn1">test1</button>
​$(document).ready(function(){
var i=1;
$('#btn1').click(function(){
$(this).data('old', $.trim($(this).text())).text('btn'+(++i));
alert( $(this).data('old'));
});
});​
for demo
use jQuery.data() to store data associated with the specified element and you will be able to get it just by accessing the same element.
Here's the link to show you how to use jQuery.data();
Here's the code using a more convenient .data() link
Set
$("#btn1").data("oldVal", $("#btn1").html());
Get
$("#btn1").data("oldVal");
Fiddle

Categories

Resources