Example:
<button type="button" value="5">5</button>
What I'm trying to do is create a javascript calculator. When the button is pushed, I would like to be able to display that value. Currently, I cannot seem to figure out how to retrieve the value and am unsure if it's valid to use a number.
According to W3Schools
value: text
This means "value" attribute always receives a text (string).
You can always parse the number if in need.
i.e.
// having myButtonValue as the value from button
var number = +myButtonValue
In this case it would be most appropriate to use the data attribute .. Like so:
<button type="button" data-value="5">5</button>
Then you can retrieve it simply using :
var el = document.querySelector('your_button');
console.log(el.getAttribute('data-value'));
NOTE That I am using querySelector as a generic term .. You could give it a class, name or ID -- And retrieve it IE getElementById()
Try using an input instead:
<input id="b5" type="button" value="5" />
you can then parse the value into a number:
const value = document.getElementById("b5").value;
Any component can have any attribute, but the button for selecting integers values may not be the most HTML semantically correct.
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');
This question already has answers here:
How do I get the value of text input field using JavaScript?
(16 answers)
Closed 4 years ago.
How can I input data in HTML using for example <input> and then interpretet it? What I mean is, I want to input age for exaplme and treat it as variable in order to built the function of age in the script later.
You just need to get the <input> value with javascript.
For example:
<input type="text" id="age" />
And in javascript:
var x = document.getElementById("age");
var age = x.value;
Now you can treat the age as a variable
If you don't want to use jQuery then you can use JavaScript's getElementById function. An example:
HTML:
<input id="someInputField" type="text" name="someInput">
JavaScript:
var inputValue = document.getElementById("someInputField").value;
You can also get the value by name using the getElementByName method.
See the docs for more:
https://developer.mozilla.org/en-US/docs/Web/API/Document/getElementById
First, you would need to select it from the DOM.
const inputField = document.querySelector('#my-input');
then you can view the current value in it with inputField.value
as far as I understand, your concern is using the HTML elements such as labels and spans for user input. while you can always style form elements to look the way you want, but to achieve this you can use HTML's contenteditable attribute:
<span contenteditable="true" id="input">This is an editable paragraph.</span>
on the JavaScript end, you can use jquery to easily detect the onChange events and call a function to act upon:
$('#input').on('change', function(){
alert($(this).val() );
// or any other operation you'd want to perform
});
How to find the value of text field using onblur() in next input field.
I tried:
function get_value() {
var inv_nrs;
inv_nrs = document.getElementsByTagName('text1').value;
alert(inv_nrs);
}
text1 is name of input which I am trying to get value.
text2 is name of input where onblur() is triggered.
Two problems:
To get elements by their name attribute, use document.getElementsByName(), not document.getElementsByTagName.
Since these functions return a collection, not a single element, you have to index them to get a specific element.
So the function should be:
function get_value() {
var inv_nrs;
inv_nrs = document.getElementsByName('text1')[0].value;
alert(inv_nrs);
}
Here's a simple snippet which illustrates a way to do this.
(You may wish to use alert in place of console.log)
document.getElementById("text2").onblur = function() {
console.log(document.getElementById("text1").value)
}
<input type="text" id="text1" value="123" />
<input type="text" id="text2" />
Are you looking for an element with id = "text1" or real name = "text1"?
At least if it's their id try getElementById("text1"), that returns one single element. If you talking about the name-attribute, take getElementByName("text1"), this may return more than one element (if there are more then one with the same name).
i think you want this???
function get_value()
{
var inv_nrs;
inv_nrs = document.getElementById('txt1').value;
document.getElementById('txt2').value=inv_nrs;
}
<input type="text" id="txt1" >
<input type="text" id="txt2" onblur="get_value()">
If you search with tagname then you need to insert a tagname:
document.getElementsByTagName('input')[whole_number].value which also
returns a live HTMLCollection
Eg. document.getElementsByTagName("input")[0].value; ,if this is the first textbox in your page.
You can get the value of an html element also on different ways:
document.getElementsByName('text1')[whole_number].value which also
returns a live NodeList
Eg. document.getElementsByName("searchTsxt")[0].value; if this is the
first textbox with name 'searchtext' in your page.
You can also get element by Id:
document.getElementById('IDHere').value to get the value of desired
box
You can also get it by way of Classname:
Use document.getElementsByClassName('class_name')[whole_number].value
which returns a Live HTMLCollection
Good luck
I'm trying to add a function where you select a color of a shirt from a select-element and add it to the textarea when you press the button.
Also if anyone can give advice to do the same with a group of radio buttons, that would help a lot.
JavaScript
function addShirt() {
buildStr += document.shirtInfo.color.value;
}
HTML
<form name="shirtInfo">
<h1>Shirts</h1>
<select name="color">
<option>White Shirt</option>
<option>Black Shirt</option>
<option>Grey Shirt</option>
</select>
<input type="button" name="complete" value="Submit" onclick="addShirt()"/>
<textarea name="receipt" rows="10" cols="15"></textarea>
Please use IDs in your HTML. Anyone trying to access your DOM will find it a lot easier to modify if they can just call an ID.
So, all you really want to do is add to the value of the textarea.
// First, define the type of variable that you want (I chose an array)
// You don't have to, but it's easier for me to iterate over
var buildstr = [];
// I'm adding this event listener on the Javascript side
// so it doesn't require you changing the HTML to modify it
document.shirtInfo.complete.addEventListener("click", function(e) {
// Take the value of the dropdown and add it to the end of the array
buildstr.push(document.shirtInfo.color.value);
// Then overwrite the value of the textarea with the array
document.shirtInfo.receipt.value = buildstr;
})
You can use the getElementsByName javascript function to access your textarea in javascript. Once you have access to the DOM element representing your textarea in javascript, you can use the innerHTML property to change its content.
function addShirt() {
document.getElementsByName("receipt")[0].innerHTML += document.shirtInfo.color.value;
}
You should take note that getElementsByName returns an array. That is the reason why you have to take the first element of that array. You could also use getElementById, which returns only one element, after having added a unique id attribute to your textarea.
To make your results clearer, you might want to add a new line after each color you add :
document.getElementsByName("receipt")[0].innerHTML += document.shirtInfo.color.value + "\n";
I try to get input value of my form. I already try many solutions but still no results. Here is form input:
<input class="form-control" id="account_ya_price_list_url shop_key_input" name="account[ya_price_list_url]" type="text" style="/* margin-right: 20px; */">
Js:
console.log($('#shop_key_input').html());
console.log($('#shop_key_input').val());
console.log($('#shop_key_input').value);
var div = document.getElementById('shop_key_input');
var div2 = document.getElementsByName('account[ya_price_list_url]').first;
console.log(div2.innerHTML );
console.log(div.innerHTML );
console.log(div2.value );
console.log(div.value );
All of this or undefined or null. What I am doing wrong?
The value of the id attribute needs to be an id not a space separated list of ids (it does not work like the class attribute).
id="account_ya_price_list_url shop_key_input"
should be
id="shop_key_input"
then #shop_key_input will match it.
Only one ID is allowed per element.
So try using just #shop_key_input and using either
document.getElementById('shop_key_input'); or $('#shop_key_input')
use class to get the value of textbox
$('.form-control').val();