Form Input Event Listener - javascript

I have an input form that is being dynamically updated with JavaScript. Using d3, I want to create an event listener that will run a function every time this input is manipulated.
Currently, it will run if I manually change the input field, but not if it is updated using the JavaScript. I have tried using .on("change",... and .on("input",....
Here is an example of the functionality I am trying to get:
<!DOCTYPE html>
<meta charset="utf-8">
<input value="0" id="input1">
<button onclick="clickFunc();">Click Me</button>
<script src="http://d3js.org/d3.v3.min.js"></script>
<script>
d3.select("#input1").on("input", function() {
// not printing when updated by javascript
console.log('value changed');
});
function clickFunc() {
document.getElementById('input1').value = document.getElementById('input1').value + 1;
}
</script>

you can execute functions with the oninput="" attribute in an input element.
<input type="text" oninput="myFunction()">
In JS, you can also use:
$("myobject").oninput = function(){myScript};
or you are better with this one:
$("myobject").addEventListener("input", myScript);

You need to use MutationObserver window class to observe an input's change triggered by JS.
Keep in mind that simply setting input's node value property, for instance, won't trigger MutationObserver. You have to invoke setAttribute(value, "value") to get the change picked up by MutationObserver.
Here's a working example I've made: https://codepen.io/Inlesco/pen/rmxdpz
Of course, this is a vanilla JS solution. If you don't care about vanilla and using jQuery is a desirability, you can attempt to use this jQuery-fied answer: Detect all changes to a <input type="text"> (immediately) using JQuery
Though, I can't guarantee it'll work. Have not tested.

Related

Changing input type="number" - value changes, but not the front-end number [duplicate]

I had thought these two were the same, but they appear to not be. I've generally been using $obj.attr("value") to work with form fields, but on the page I'm currently building, $obj.attr("value") does not return the text I enter in my field. However, $obj.val() does.
On a different page I've built, both $obj.attr("value") and $obj.val() return the text entered in the form field.
What could account for $obj.attr("value") working as expected in one case but not in another?
What is the proper way to set and retrieve a form field's value using jQuery?
There is a big difference between an objects properties and an objects attributes
See this questions (and its answers) for some of the differences: .prop() vs .attr()
The gist is that .attr(...) is only getting the objects value at the start (when the html is created). val() is getting the object's property value which can change many times.
Since jQuery 1.6, attr() will return the original value of an attribute (the one in the markup itself). You need to use prop() to get the current value:
var currentValue = $obj.prop("value");
However, using val() is not always the same. For instance, the value of <select> elements is actually the value of their selected option. val() takes that into account, but prop() does not. For this reason, val() is preferred.
PS: This is not an answer but just a supplement to the above answers.
Just for the future reference, I have included a good example that might help us to clear our doubt:
Try the following. In this example I shall create a file selector which can be used to select a file and then I shall try to retrieve the name of the file that I selected:
The HTML code is below:
<html>
<body>
<form action="#" method="post">
<input id ="myfile" type="file"/>
</form>
<script type="text/javascript" src="jquery.js"> </script>
<script type="text/javascript" src="code.js"> </script>
</body>
</html>
The code.js file contains the following jQuery code. Try to use both
of the jQuery code snippets one by one and see the output.
jQuery code with attr('value'):
$('#myfile').change(function(){
alert($(this).attr('value'));
$('#mybutton').removeAttr('disabled');
});
jQuery code with val():
$('#myfile').change(function(){
alert($(this).val());
$('#mybutton').removeAttr('disabled');
});
Output:
The output of jQuery code with attr('value') will be 'undefined'.
The output of jQuery code with val() will the file name that you selected.
Explanation:
Now you may understand easily what the top answers wanted to convey. The output of jQuery code with attr('value') will be 'undefined' because initially there was no file selected so the value is undefined. It is better to use val() because it gets the current value.
In order to see why the undefined value is returned try this code in your HTML and you'll see that now the attr.('value') returns 'test' always, because the value is 'test' and previously it was undefined.
<input id ="myfile" type="file" value='test'/>
I hope it was useful to you.
Let's learn from an example.
Let there be a text input field with default value = "Enter your name"
var inp = $("input").attr("value");
var inp = $("input").val();
Both will return "Enter your name"
But suppose you change the default text to "Jose" in your browser.
var inp = $("input").attr("value");
will still give the default text i.e. "Enter your name".
var inp = $("input").val();
But .val() will return "Jose", i.e. the current value.
Hope it helps.
The proper way to set and get the value of a form field is using .val() method.
$('#field').val('test'); // Set
var value = $('#field').val(); // Get
With jQuery 1.6 there is a new method called .prop().
As of jQuery 1.6, the .attr() method returns undefined for attributes
that have not been set. In addition, .attr() should not be used on
plain objects, arrays, the window, or the document. To retrieve and
change DOM properties, use the .prop() method.
In order to get the value of any input field, you should always use $element.val() because jQuery handles to retrieve the correct value based on the browser of the element type.
jQuery('.changer').change(function () {
var addressdata = jQuery('option:selected', this).attr('address');
jQuery("#showadd").text(addressdata);
});
jQuery(".morepost").live("click", function() {
var loadID = jQuery(this).attr('id'); //get the id
alert(loadID);
});
you can also get the value of id using .attr()
this example may be useful:
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.1/jquery.min.js"></script>
</head>
<body>
<input id="test" type="text" />
<button onclick="testF()" >click</button>
<script>
function testF(){
alert($('#test').attr('value'));
alert( $('#test').prop('value'));
alert($('#test').val());
}
</script>
</body>
</html>
in above example, everything works perfectly. but if you change the version of jquery to 1.9.1 or newer in script tag you will see "undefined" in the first alert.
attr('value') doesn't work with jquery version 1.9.1 or newer.
Example more... attr() is various, val() is just one! Prop is boolean are different.
//EXAMPLE 1 - RESULT
$('div').append($('input.idone').attr('value')).append('<br>');
$('div').append($('input[name=nametwo]').attr('family')).append('<br>');
$('div').append($('input#idtwo').attr('name')).append('<br>');
$('div').append($('input[name=nameone]').attr('value'));
$('div').append('<hr>'); //EXAMPLE 2
$('div').append($('input.idone').val()).append('<br>');
$('div').append('<hr>'); //EXAMPLE 3 - MODIFY VAL
$('div').append($('input.idone').val('idonenew')).append('<br>');
$('input.idone').attr('type','initial');
$('div').append('<hr>'); //EXAMPLE 3 - MODIFY VALUE
$('div').append($('input[name=nametwo]').attr('value', 'new-jquery-pro')).append('<br>');
$('input#idtwo').attr('type','initial');
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<input type="hidden" class="idone" name="nameone" value="one-test" family="family-number-one">
<input type="hidden" id="idtwo" name="nametwo" value="two-test" family="family-number-two">
<br>
<div></div>
jquery - Get the value in an input text box
<script type="text/javascript">
jQuery(document).ready(function(){
var classValues = jQuery(".cart tr").find("td.product-name").text();
classValues = classValues.replace(/[_\W]+/g, " ")
jQuery('input[name=your-p-name]').val(classValues);
//alert(classValues);
});
</script>
If you get the same value for both property and attribute, but still sees it different on the HTML try this to get the HTML one:
$('#inputID').context.defaultValue;
In attr('value') you're specifically saying you're looking for the value of an attribute named vaule. It is preferable to use val() as this is jQuery's out of the box feature for extracting the value out of form elements.
I have always used .val() and to be honest I didnt even know you could get the value using .attr("value"). I set the value of a form field using .val() as well ex. $('#myfield').val('New Value');

val() from textarea not selecting searched terms

The following var is only working in my script when the text is hard coded in the textarea (e.g. London):
script
var thought = $('textarea[name=search]').val(); //...used in object literal
html
<textarea rows="5" name="search" type="text" id="term">London</textarea>
I'd like to be able to type a search term into the textarea and search for it but it's not working?
I've tried all of the answers below with no luck!? I've therefore included the following in the object literal. It pulls the hard coded value from the textarea (like before) but it doesn't pull a value that is typed in the textarea normally? I thought this might be easier to resolve the problem (the feed not working when the search term is typed in)
search: $('textarea[name=search]').val(),
I'm following this tutorial below for a twitter feed with jquery but adding a textarea to search for terms,topics,hashtags etc is proving difficult to figure out.
Twitter Feed with Jquery linky
Do with keyup or change event of textarea
$("textarea[name='search']").keyup(function(e){
var currentText=this.value;
});
You have a couple options, either search using a click event on some button called Search, or use a change / keyup event to grab the new value each time the field is updated, and perform the search that way:
$("#term").keyup(function() {
console.log(this.value); //theres your value!
});
As stated before, if you use it like this, it will be stored in the thought var and you can call it from whatever function you're using.
Since your method calls it one time probably before you edit it.
At least that is what I'm guessing since your code is obviously not complete ;).
var thought = '';
$('textarea[name=search]').keyUp(function(){
thought = $(this).val();
});
Just add jquery and use below code.
<html>
<head>
//import jquery here
<script>
$(document)
.on("click", "#btn", function(event) {
var thought = $('textarea[name=search]').val();
alert(thought);
});
</script>
</head>
<body>
<textarea rows="5" name="search" type="text" id="term"></textarea>
<input type="button" id="btn" value="click me">
</body>

Javascript, viewing [object HTMLInputElement]

I'm just started to learn HTML. Doing an alert() on one of my variables gives me this result [object HTMLInputElement].
How to get the data, that were added in text field, where my input type is text?
Say your variable is myNode, you can do myNode.value to retrieve the value of input elements.
Chrome Developer Tools has a Properties tab which shows useful DOM attributes.
Also see MDN for a reference.
If the element is an <input type="text">, you should query the value attribute:
alert(element.value);
See an example in this jsFiddle.
Also, and seeing you're starting to learn HTML, you might consider using console.log() instead of alert() for debugging purposes. It doesn't interrupt the execution flow of the script, and you can have a general view of all logs in almost every browser with developer tools (except that one, obviously).
And of course, you could consider using a web development tool like Firebug, for instance, which is a powerful addon for Firefox that provides a lot of functionalities (debugging javascript code, DOM inspector, real-time DOM/CSS changes, request monitoring ...)
It's not because you are using alert, it will happen when use document.write() too. This problem generally arises when you name your id or class of any tag as same as any variable which you are using in you javascript code. Try by changing either the javascript variable name or by changing your tag's id/class name.
My code example:
bank.html
<!doctype html>
<html>
<head>
<title>Transaction Tracker</title>
<script src="bank.js"></script>
</head>
<body>
<div><button onclick="bitch()">Press me!</button></div>
</body>
</html>
Javascript code:
bank.js
function bitch(){ amt = 0;
var a = Math.random(); ran = Math.floor(a * 100);
return ran; }
function all(){
amt = amt + bitch(); document.write(amt + "
"); } setInterval(all,2000);
you can have a look and understand the concept from my code. Here i have used a variable named 'amt' in JS. You just try to run my code. It will work fine but as you put an [id="amt"](without square brackets) (which is a variable name in JS code )for div tag in body of html you will see the same error that you are talking about.
So simple solution is to change either the variable name or the id or class name.
change:
$("input:text").change(function() {
var value=$("input:text").val();
alert(value);
});
to
$("input:text").change(function() {
var value=$("input[type=text].selector").val();
alert(value);
});
note: selector:id,class..
<input type="text" id="name">
and in javascript
var nameVar = document.getElementById("name").value;
alert(nameVar);
<input type="text" />
<script>
$("input:text").change(function() {
var value=$("input:text").val();
alert(value);
});
</script>
use .val() to get value of the element (jquery method), $("input:text") this selector to select your input, .change() to bind an event handler to the "change" JavaScript event.
When you get a value from client make and that a value for example.
var current_text = document.getElementById('user_text').value;
var http = new XMLHttpRequest();
http.onreadystatechange = function () {
if (http.readyState == 4 && http.status == 200 ){
var response = http.responseText;
document.getElementById('server_response').value = response;
console.log(response.value);
}

jQuery with "onkeypress" lag to make a change

I have a span with a text in it that suppose to change constantly after I press something in my textbox.
<input type="text" class="response" onkeypress="return ChangeSpan()" id="how_many" name="how_many" placeholder="Enter how many..." />
and my jQuery:
<script type="text/javascript">
function ChangeSpan() {
var text = $("#how_many").val();
$('#changeText').text(text);
}
</script>
it's working perfectly fine , but when I press let's say "dfg" , its only present "df" on the span. and only when I add the next charecter, it adds the "g".
I want it to respond also to the last character, how do I do that ?
You probably want to use keyup.
You use jQuery and add the events inline? That is bad practice. Attach events using on.
$("#how_many").on("keyup", function(){ $('#changeText').text( this.value ); });
Difference between keyup, keydown, and keypress explained on quirksmode.
Yeah I might be a little late but actually using keypress is better than keyup because if you hold a key very long it will show up when you release it if you use keyup.
If you use keypress you'll directly see what you've typed but you've to use it as shown in the code below.
The only problem is that keypress won't recognize if you delete chars. So keypress is better but keyup should be also in use.
$("#how_many")
.keypress(function(e) {
var text = $("#how_many").val() + String.fromCharCode(e.which);
$("#changeText").text(text);
})
.keyup(function(e) {
var text = $("#how_many").val();
$("#changeText").text(text);
});​
Look at this example. It's exactly the code before.
And this example. It's the code before without using keypress.
Hold any character key in both examples while the text box is on focus. As you can see the first example reacts better.
Why dont you just use bindings? This should do it:
<input type="text" class="response" id="how_many" name="how_many" placeholder="Enter how many..." />
$(window).load(function(){
$("#how_many").bind('focus blur keyup',function(){
$('#changeText').text($(this).val());
});
})
<input type="text" class="response" onkeyup="return ChangeSpan()" id="how_many" name="how_many" placeholder="Enter how many..." />
Try changing your event to keyup. Here's an example:
http://jsfiddle.net/SHdTL/
Note: I'd recommend using jquery to assign your event listener as well rather than inline, but it's not pertinent to your issue.

Alter HTML real-time with input tag

How can I can I alter (change, add, whatever) HTML/text real-time using the input tag? Very similar to the preview interface when asking a question on Stack Overflow minus the code encoding. It just has to be simple.
For example,
<input type="text" name="whatever" />
<div id="example"></div>
Whatever text is entered in the above input tag is added to #example in real-time.
Something involving innerHTML and JavaScript perhaps?
You can do this with jQuery
$('input').keyup(function(){
var a = $(this).val();
$('#example').text(a);
});
Example: http://jsfiddle.net/5TnGT/
There are many other ways to change content than described in the previous answers. Listen for all of them and update realtime. Requires jQuery supporting the newer .on() event handling for this example. Can also use .bind() or .live() with appropriate syntax.
$(document).ready(function() {
$(document).on('keyup propertychange input paste', 'input', function() {
$('#example').text($(this).val());
});
});
The second $(document) can be made more specific depending on the markup of the rest of your page.
See also: http://jsfiddle.net/DccuN/2/
Yes javascript will do this. Have a look at on key up. Then either innerHTML as you say or jQuery makes things a bit easier with .append or .html or .text
(Damn too slow)
Plain JavaScript solution (you won't need any sophisticated lib if you don't get too fancy elsewhere):
<input type="text" onkeypress="document.getElementById('example').innerHTML=this.value;" name="whatever" />
<div id="example"></div>
You can bind to the keyup event. Then set the div contents to that of the input.
http://jsfiddle.net/wYqgc/
var input = document.getElementsByTagName('input')[0];
var div = document.getElementById('example');
input.onkeyup = function() {
div.innerHTML = this.value;
};
You can start with this:
input.onkeyup = function () {
output.innerHTML = this.value;
};
Live demo: http://jsfiddle.net/P4jS9/

Categories