I know this question has been asked -and answered- multiple times. However I found a new solution - but do not fully understand it. The setup is this:
<input id="input1" onchange="GetText()"/>
All answers i found suggest to use the id to get the value of the input.
function GetText(){
alert($("#input1").val());
}
$(this).val() does not work here.
Another way to use the value of the #input1 would be to use this.value in the calling function:
<input id="input1" onchange="GetText(this.value)" />
This passes the value as a parameter to the function.
However I found a JQuery sample that attaches a function to #input1 and makes $(this).val() work.
$("#input1").change(function(e){
alert($(this).val())
});
Against all answers here at stackoverflow seeing that it is possible to attach a function to a input field and have access to the value of it - I ask myself how I would have to write this function and not attach it with JQuery. Or can it be only attached with JQuery? Why?
Here is a fidle with this setup to play
You either pass reference to input object as a parameter in inline call to callback like this:
<input id="input2" onchange="GetText(this)" />
and then in javascript:
function GetText(_this){
alert(_this.value);
}
Fiddle here
Or you can attach function directly to input object like so
document.getElementById('input2').getText = function() {
alert(this.value);
};
and in html:
<input id="input2" onchange="this.getText()" />
Fiddle here
Basically this object in javascript is bound to context, in which the function has been created. When you define function globally, like GetText in your example, this is bound to global object in scope of that function.
<input id="input1" onchange="GetText.call(this)"/>
or
<input id="input1" onchange="GetText.apply(this)"/>
Will call the GetText function with the input as the value of this. Then you can use $(this) or this.value within the scope of GetText.
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/call
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/apply
If you're looking for a similar Vanilla JS function that you can put into you're HTML, which I actually don't recommend, because I support JavaScript HTML separation, it would be something like:
function getInputVal(context){
alert(context.value);
}
In your HTML:
<input id='whoCares' name='whoCares' value='Some Value' onchange='getInputVal(this)' />
Inline JS is not easy to maintain, especially if there's so much of it. It is better to separate your JS and HTML.
//Wait for DOM to load
$(function() {
//set up change event listener --> anonymous function
$('#input1').on('change', function() {
alert( this.value );
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<input id="input1" />
Or if you want to use a named function:
//wait for DOM to load
$(function() {
//Define function
function GetText(){
alert( this.value );
}
//set up change event listener --> named function
$('#input1').on('change', GetText);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<input type="text" id="input1" />
All answers i found suggest to use the id to get the value of the input.
That's actually a pretty bad design; you want to create event handlers that can be unaware of the elements they're attached to.
The example without using jQuery would look like this:
var input = document.getElementById('input1');
input.addEventListener('change', function(event) {
alert(this.value);
}, false);
<input id="input1" />
See also: addEventListener()
Related
I want to get the default value of an input textbox when the page was loaded. As I searched around I saw that the DefaultValue() is a method to get a value from a textbox when is loaded . But what is the jQuery one?
<input id=text > </input>
<script>
$(#text).DefaultValue(); // This is wrong I need the Jquery function of this
</script>
Any Idea?
You can read the defaultValue DOM property like this:
$('#text').prop('defaultValue')
Heres a working example
$('#value').click(function(){
alert($('#text').val())
});
$('#def').click(function(){
alert($('#text').prop("defaultValue"))
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" id="text" value="This is the default value">
<button id="value">Click to see the current value</button>
<button id="def">Click to see the default value</button>
If you want to call a Javascript DOM function on a jQuery object, you can simple extract the corresponding DOM object with .get(0) or [0]:
$("#text").get(0).defaultValue;
$("#text")[0].defaultValue;
Note also that you were calling the basic JS wrong. First, it's defaultValue, not DefaultValue. Second, it's a property, not a method, so there's no parentheses after it.
Try this,
$(function(){
console.log($('#text')[0].defaultValue);
// or try
console.log($('#text').prop( 'defaultValue' ));
});
Read https://developer.mozilla.org/en-US/docs/Web/API/HTMLInputElement
I am a newbie in Javascript and jquery I have a jquery function
$('.input-group .date').datepicker({
});
for
<div class="input-group date" id="dp3">
<input class="form-control" type="text" placeholder="Date" name="date" value="">
</div>
I want to add this inside input tag using onclick="" can you please tell me how to do this ?
If I'm thinking what your thinking then it's wrong.
.datepicker() already assigns an onClick event so you don't have to create an extra one.
You have to make sure you are using jQuery and jQuery UI in order for datepicker to work.
Then you either have to put your script before you close body or in the head and use
$(document).ready(function(){ ... });
I also think you are using the wrong selector here.
. is class
# is ID
So it should be
$('.input-group .form-control').datepicker();
Example: http://jsfiddle.net/Spokey/AjRm3/
For those coming to this question because they want to know how to bind to the event that happens when someone clicks on an input box, then this is useful:
$('input.your-input-box-class').focus(function(e){
// do something
});
For those who want to use datepicker like the original question asks, then remember that jQuery UI abstracts away from these types of details. So just use the widgets like they were meant to be used. In this case, create the datepickers for all your input boxes that have a certain class (say date maybe) when the DOM is done loading:
$(document).ready(function(){
$('input.datepicker').datepicker({ /*... pass options here ...*/ });
});
And for options, you read the documentation, they include handling all the events you need:
http://api.jqueryui.com/datepicker/
Call a function:
onclick="someFunction(this);"
Set function:
function someFunction(this) {
$(this).prev('.input-group.date').datepicker({});
}
You bind datepicker to DOM element, not onClick.
$(document).ready(function(){
$('.form-control').datepicker({});
});
Or add it in function, so you can call it dynamically.
put the set of code inside a javascript function say clickMe()
function clickMe(){
$('.input-group .date').datepicker({
});
}
now call the function in click method.
<div class="input-group date" id="dp3">
<input class="form-control" type="text" placeholder="Date" name="date" value="" onclick="clickMe()">
</div>
I'm using this code to set the HTML textbox value using Javascript function. But it seems to be not working. Can anyone point out, what is wrong with this code?
Whats your Name?
<input id="name" value="" />
<script type="text/javascript">
function setValue(value){
var myValue=value;
document.getElementsById("name").value = myValue;
}
</script>
the "value" is came from my android java class using this codes
String value = "Isiah";
WebView web = (WebView) findViewById(R.id.web1);
web.getSettings().setJavaScriptEnabled(true);
web.loadUrl("file:///android_asset/www/webpage");
web.loadUrl("javascript:setValue("+ value +")");
function setValue(value) {
var myValue=value; //unnecessary
document.getElementById("name").value= myValue;
}
But then as pointed out in the comments, you need to call setValue(value) somewhere in your code. Right now you just defined the function is never called.
You could either access the element’s value by its name:
document.getElementsByName("textbox1"); // returns a list of elements with name="textbox1"
document.getElementsByName("textbox1")[0] // returns the first element in DOM with name="textbox1"
So:
input name="buttonExecute" onclick="execute(document.getElementsByName('textbox1')[0].value)" type="button" value="Execute" />
Or you assign an ID to the element that then identifies it and you can access it with getElementById:
<input name="textbox1" id="textbox1" type="text" />
<input name="buttonExecute" onclick="execute(document.getElementById('textbox1').value)" type="button" value="Execute" />
You are using document.getElementsById("name") it should be document.getElementById("name")
not Elements it is Element
You are not linking the function to anything. For example, a click:
<input id="name" value="" onclick="javascript:this.value=12;"/>
Replace the onclick attribute for your desired function, whatever it does (you need to be more specific)
Also, there is no language attribute (at least not anymore) use type="text/javascript" instead
Here is a fiddle: http://jsfiddle.net/4juEp/
Click the input to see it working.
Look at this second fiddle. http://jsfiddle.net/4juEp/1/
which loads whatever is defined in the hid input to the name input.
Firstly, you have a typo in your javascript function i.e. you have used getElementsById as compared to getElementById
To set the value of the textbox on page load, I suggest you use an alternative
<body onload="setValue('yourValueToSet');">
<!-- Your usual html code in the html file -->
</body>
I think you are missing the quotes,
try,
web.loadUrl("javascript:setValue('"+ value +"')");
also consider about the typo.
Check this out:
<body onload="setvalue($value);">
Whats your Name?<input id="name" name="name" value=""/>
<script type="text/javascript">
function setValue(value){
document.{formname}.name.value = value;}</script>
It's not Elements
It's Element
You should use document.getElementById('object-id');
I have a tag with a complex "oninput" handler, e.g.
<input id="x" type="text" name="x"
oninput="lotsofgeneratedcocde...."/>
I want to add another handler that simply calls that one. My initial though was that this would work:
<input id="x" type="text" name="x"
oninput="lotsofgeneratedcocde...." onfocus="this.oninput"/>
But it doesn't. What should I be doing? Thanks.
Edit: I thought that onfocus="this.oninput" would copy the reference to the function, that's why I left off the parentheses for a call.
this.oninput() (note parentheticals) should work:
<input id="x" type="text" name="x"
oninput="console.log('test');" onfocus="this.oninput();"/>
http://jsfiddle.net/9kNrW/
This could work?
... onfocus="this.oninput()"
I assume there's no way to have the generated code be outsourced as proper functions that you could call from both event handlers...
Short answer:
Use parens: onfocus="this.oninput();"
If oninput references this or the event object, you need to add a little more:
onfocus="this.oninput.call(this, event);"
Explanation:
If you were attaching the event handlers in code, your syntax is correct. Because you are setting a function reference. Ie,
myInput.onfocus = myInput.oninput;
But, when attached in the markup, the code between the quotes actually is itself a function. Eg,
<span id="foo" onclick="alert('hello world');" />
Is equivalent to:
document.getElementById("foo").onclick = function () {
alert('hello world');
};
So your code as written is the equivalent of:
document.getElementById("x").onfocus = function () {
this.oninput; // returns a function reference. Does not call the function.
};
I´m making a google instant-type of remote suggestion script with ajax on a site I'm making.
now I have this:
<input type="text" name="spanishtitle" onkeyup="suggest(this, 'title_es');" onblur="fill();" />
and I would like to move that onkeyup script to a jquery call, so I added this
$('.suggestable').live('keyup', ( function() { suggest(this); } ));
and changed the above to this
<input class="suggestable" type="text" name="spanishtitle" onblur="fill();" />
but I'm missing the 'title_es' parameter which tells the ajax handler what am I looking for.
So what I want to know, basically, is if there's a way to add this parameter to the object, so I can access it from suggest() somehow.
You can add it to your HTML...
<input type="text" name="spanishtitle" onblur="fill();" data-title="title_es" />
And then access it in jQuery...
$('.suggestable').live('keyup',
function() { suggest(this, $(this).attr('data-title')); }
);
The data- prefixed attributes are in the HTML5 spec, and are going to be very useful.
At last, no further excuses for using inline event attributes :)
Assign it as the id of the element and then
$('.suggestable').live('keyup', function() {
suggest(this, $(this).attr("id"));
});
The data-* attribute is html5 as far as I know
You can add it as an attribute to the input, something like:
<input data-lookfor='title_es' class="suggestable" type="text" name="spanishtitle" onblur="fill();" />
then you can access it in jQuery with .attr()
var look_for = $(this).attr('data-lookfor');