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);
}
Related
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');
https://stackoverflow.com/a/43635720
On this answer, it says to define a variable (window.parentPage = true;) in the index.html page. How can I go about doing this?
You would need to define the variable using JavaScript. You can embed some JavaScript in the HTML file by encasing it in a script tag like so:
<script type="text/javascript">
window.parentPage = true;
</script>
First you need to clearly realize your reason... what you want to achieve.
After that defining that to yourself:
First option:
You can store/save some data as stated on the link you added to your question inside a tag, like that:
<script>
var myLittleBox = "box content";
</script>
And access it later like:
<script>
myLittleBox = myLittleBox + " extra content";
console.log(myLittleBox);
//this will print "box content extra content"
</script>
You need to use the tag to access the javascript environment.
Second option:
You can save/store data with pure HTML using an with type "hidden" to not show it on screen as an input box, and changing it's value, like that:
<input type="hidden" value="box content">
But this way you'll not be able to access the data directly without aid of javascript code, unless you send this input somewhere reachable as GET or POST within a and recover it getting the respective GET or POST.
Javascript variables:
https://www.w3schools.com/js/js_variables.asp
Ex: https://www.w3schools.com/js/tryit.asp?filename=tryjs_variables
HTML input:
https://www.w3schools.com/tags/tag_input.asp
HTML form handling:
https://www.w3schools.com/php/php_forms.asp
You're probably trying to understand the first option, but you question do not make that clear. Anyway, good studies.
Whatever you do you will have to use JavaScript in order to access the variable. An orthodox way of doing it that is not mentioned yet is using an data-attribute inside the html and than you access it by JavaScript:
const attributeName = 'data-parentPage';
const setup = () => {
let parentPageBool = document.querySelector(`html[${attributeName}]`).getAttribute(attributeName);
console.log(parentPageBool)
};
window.addEventListener('load', setup);
<html data-parentPage="true">
</html>
I have created a very simple editor that has been working great. However, I just tried to put JavaScript into it and I can't get it to work.
The code for the editor:
<div id="buttoncontainer">
<input id="button" onclick="update();" type="button" value="Update page">
</div>
<div id="tryitcontainer">
<textarea id="codebox"></textarea>
<iframe id="showpage"></iframe>
</div>
The JavaScript for the editor:
<script>
function update() {
var codeinput = document.getElementById('codebox').value;
window.frames[0].document.body.innerHTML = codeinput;
}
</script>
I just wanted to run some simple JavaScript that changes an image when it is clicked. This code works fine when I run it in a full browser, so I know its the editor thats the problem.
Is there a simple fix for this that I'm missing?
The button is not finding the update() method. You need that function to be globally available:
http://jsfiddle.net/t5swb7w9/1/
UPDATE: I understand now. Internally jQuery basically evals script tags. There's too much going on to be worth replicating yourself... either use a library to append, or eval the code yourself. Just a warning that eval'ing user input is rarely a good thing and is usually a welcome mat for hackers.
window.myScope = {
update: function() {
var div = document.createElement('div'),
codeinput = document.getElementById('codebox').value,
scriptcode = "";
div.innerHTML = codeinput;
Array.prototype.slice.apply(div.querySelectorAll("script")).forEach(function(script) {
scriptcode += ";" + script.innerHTML;
div.removeChild(script);
});
window.frames[0].document.body.appendChild(div);
// hackers love to see user input eval'd like this...
eval(scriptcode);
}
};
And then you would update your button like so:
<input id="button" onclick="myScope.update();" type="button" value="Update page">
Or, even better, use addEventListener and forget the onclick part altogether. I'll let you do that research on your own ;)
JavaScript inserted via innerHTML will not be executed due to security reasons:
HTML5 specifies that a <script> tag inserted via innerHTML should not execute.
from MDN: Element.innerHTML - Security considerations, see also: W3: The applied innerHTML algorithm.
A possible solution using the jQuery method .append() works around that, as it somehow evals the content. But this will still not solve your problem, as the JavaScript code is executed in the current scope.
Here's a test scenario:
function update() {
var codeinput = document.getElementById('codebox').value;
$(window.frames[0].document.body).append(codeinput);
}
Try it here
Try to insert this script:
<script>
alert( document.getElementById('tryitcontainer') );
</script>
and this one:
<p id="test">Test</p>
<script>
window.frames[0].document.getElementById('test').innerHTML = 'updated';
</script>
The first one will return a [object HTMLDivElement] or similar. Here you can see, that you're still in the same scope as the parent frame. The second one will correctly update the content within the iframe. Keep that in mind, when experimenting with those things.
Maybe Executing elements inserted with .innerHTML has some more infos for you.
I'm new at coding with any language and now im working (trying to) with HTML, PHP and JavaScript. My difficulty is to show through an alert in a JavaScript file the information that is in a textarea from an HTML file. The HTML code is this:
<head>
<title> My Form</title>
<script type= "text/javascript" src ="./JavaScript/validaLinha.js"></script>
</head>
<body>
<form name="Linhas" method="POST" action="Linhas-p.php">
<textarea name="descricaoLinha" onFocus="resetField('descricaoLinha')"> TEXT-TEXT-TEXT</textarea>
</form>
</body>
As you can see at the HTML code, I try to send the name of the textarea to a JavaScript function called "resetField". Let's see what the "resetField" does:
function resetField(field){
d = document.Linhas;
alert("It's entering the function."); //ANSWER = It's entering the function.
alert(field); //ANSWER = descricaoLinha
alert(d.field.value); //ANSWER = Nothing.
alert(d.getElementById(field).value); //ANSWER = Nothing.
}
I can't get the information set at the value of my textarea! The event is calling the function (First alert shows up), the string is being received by the function (Second alert shows the name of the text area) but the other two that are the ones that i need doesn't show up. I already tried to change the order of the alerts because of that JavaScript stuff that doesn't continues to read the code if an error appears.
Just to emphasize, i want the content IN the textarea. (The name of it is being received properly)
Thanks for reading! Sorry about my english. ^^
Add an ID to your textaea
<textarea id="descricaoLinha" name="descricaoLinha" onFocus="resetField('descricaoLinha')"> TEXT-TEXT-TEXT</textarea>
And then, send the ID instead of name
alert(d.getElementById(field).value);
This code can't find the element descricaoLinha because its searching for an element that has an ID = "descricaoLinha"
Your 'field' is just a string, not a javascript object and of course it does not have the name attribute;
And it is similar to the d = document.linha;
You have have to get the DOM element by its id attribute:
d = document.getElementById("Linha");
Edit: You also need add the id attribute to your field
<textarea id="descricaoLinha" name="descricaoLinha" onFocus="resetField('descricaoLinha')"> ...
One solution is: you change your JavaScript function to
function resetField(fieldId) {
var field = document.getElementById(fieldId);
alert(field); // object
alert(field.value); // text field value
// Do whatever you want with the field object here
}
You should turn on the console and using console.log('output') instead of using alert() for debugging;
You can turn on Firefox console by Ctrl + Shift + K
You should pass in this in your onfocus handler:
onFocus="resetField(this);"
Access it like:
alert("It's entering the function.");
alert(field.name);
alert(field.value);
Here's a demo: http://jsfiddle.net/RbUZr/
SO i am trying to get the value or the contents of an HTML text box. I have tried various types of methods but none of them work. According to the debugger , the code stops at getelementbyid method. The commented lines are the methods that I have already tried. Some of them return null while some of them return NaN and most of them just return a blank page.
help is much appreciated.
<html>
<head>
<script type="text/javascript" >
function calculateit(){
document.open();
var number = document.getElementsByName('xyz')[0].value
//var number = document.getElementsByName("xyz").value;
//var number = document.getElementsByName('xyz').value;
//var number = document.getElementsByName("xyz");
//var number = document.getElementsByName('xyz');
//var number = document.getElementsById("xyz").value;
//var number = document.getElementsById('xyz').value;
//var number = document.getElementsById("xyz");
//var number = document.getElementsById('xyz');
//var number = document.form1.xyz.value; //form 1 was my form name and/or id
document.writeln(number);
var newtemp = 0;
var newtemp = tempera *9/5+32;
document.write(newtemp);
}
</script>
</head>
<body>
<input type="text" id="xyz" name="xyz">
<button title="calculate" onclick="calculateit()">calculate </button>
</body>
</html>
You're using the wrong method. The two widely supported methods for javascript are "getElementsByTagName" and "getElementById". Note exactly how "getElementById" is spelled. It is meant to get one element with the exact id that you specify. "getElementsByTagName" gets all elements of a certain tag...such as "div". When using "getElementById", you don't to index it or anything - it either returns null (can't find) or the exact element reference. From there, since it is a textarea, you can use ".value" to get the current value, like you already are.
ALSO:
You probably shouldn't use "document.write" or any of its related write methods AFTER the page has been rendered. In your example, that's exactly what you're doing, so once you get the ".value" stuff working, I would change that. The point is that "document.write" is more for during page rendering...so if you had javascript inline with the HTML body or something. Something like:
<html>
<head>
</head>
<body>
<script type="text/javascript">
document.write("testing");
</script>
</body>
</html>
would be fine, but still not preferred. The fact that you have it in a function, that is called on a button click, means it is not during page render, and shouldn't be used. A more practical approach is to have a <div> on the page and add text to it when necessary, using something like ".innerHTML". That way, things are dynamic and not overwritten in the actual document.
It's getElementById, not getElementsById.