If I have a text input and have set a default value in the HTML, is there anyway to access the original value after jquery has changed the current value using .val()?
It was my understanding that jQuery should be changing the value property and not the value attribute?
Edit: Note I'm not asking how I could store the default value to retrieve it later (e.g. in data or in a var) I'm interested in why jQuery is modifying the attribute of the input field (and in turn the defaultValue) and not just the property.
For this example:
<input id="me" type="hidden" value="starting value" />
<script>
var $field = $('#me');
console.log($field.val());
console.log($field.prop('defaultValue'));
console.log($field.val('new value'));
console.log($field.val());
console.log($field.prop('defaultValue'));
console.log($field.attr('value'));
console.log($field.prop('value'));
</script>
We see:
starting value
starting value
[input#me, context: document, selector: "#me", jquery: "2.1.0", constructor: function, toArray: function…]
new value
new value
new value
new value
Fiddle:
http://jsfiddle.net/jLsqmxg7/1/
jQuery "val" setter always change both the attribute and the property. They do this to not confuse the developer with a ambiguous behavior. If you really want to change only the property and let the tag attribute with the same value do this:
var $input = $("<input>", {value: 'original'}); // Using the jQuery constructor to create a input :)
$input[0].value = "foo"; // Changing the value property of this HTMLInputElement instance
console.log($input.val()); // foo
console.log($input.prop('value')); // foo
console.log($input.attr('value')); // original
With this, you're changing only the HTMLInputElement value property, not the tag attribute.
So, was I say, this turns the code a little confunsing.
Related
HTML:
<span class="rbx-text-navbar-right text-header" id="nav-robux-amount">11</span>
CODE:
element = document.getElementById("nav-robux-amount")
if (element){
window.alert(element.value)
}
window.alert shows that the value of element is undefined
The .value property only exists on inputs.
The 'element' isn't a constant variable.
If you want to get the content, you can do the following:
const element = document.getElementById("nav-robux-amount");
if (element) window.alert(element.textContent)
Note: innerHTML is not as good as textContent, as it is vulnerable to attacks.
I'm trying to assign a variable to another variable and try to do only one way binding. But when value is updated in view, it updates to original variable too. How do I stop this two way binding while assigning variable to another.
For example:
function personController ($scope) {
var templateValue= "original value";
$scope.myVal= templateValue;
}
In view:
<input type="text" ng-model="myVal" />
Result:
When we type something in textbox, it updates value in myVal and templateValue too, i.e value in templateValue changes to whatever I just typed in the input box. Is there a way to assign variable to another variable doing only one way binding? I want two way binding between $scope.myVal and the input box but not between templateValue and input box.
You can't "force one-way binding" because of the weay JavaScript works.
In your example, updating myVal will not actually update templateValue.
function personController($scope) {
var templateValue = "original value";
$scope.myVal = templateValue;
}
If you have the following structure, then yes, changing myVal.test will update templateValue.test because they both reference the same object in memory.
function personController($scope) {
var templateValue = { test: "original value" };
$scope.myVal = templateValue;
}
if you want myVal and templateValue to reference different objects but have the same content, make a copy of the original object:
$scope.myVal = angular.copy(templateValue);
I also suggest familiarising yourself with Javascript by reference vs. by value.
Consider the following code snippet:
inputTextField=document.getElementById("Phone_input");
var value = inputTextField.value;
value=value.substring(0,10);
where Phone_input is an <input type="text"/> element. Why during the running of this script there is no changes of actual value of the <input type="text"/>. We're changing value by the reference which indicates to inputTextField.value.
The variable value is not a reference, so after the change you must write it back into the textfield:
value=value.substring(0,10);
inputTextField.value = value;
Or, in one line:
inputTextField.value = inputTextField.value.substring(0,10);
Javascript always passes by value, but in an array or object, the value is a reference to it, so you can 'change' the contents.
In this case you have to do it this way:
var inputTextField=document.getElementById("Phone_input");
inputTextField.value = inputTextField.value.substring(0,10);
Do you know why this
function deleteInputOnClick(input){
champ = document.getElementById(input);
if(champ.value =='E-mail'){
champ.value = "";
}
}
works but this way
function deleteInputOnClick(input){
champ = document.getElementById(input).value;
if(champ=='E-mail'){
champ= "";
}
}
it doesn't ?
It's probably a stupid little error but I really don't see where it could be.
Thank's
You're not setting the value back on the element in the second way, you're just assigning it to a local variable, you still need to do document.getElementById(input).value = champ;
That is because is champ is a variable that has been assigned the value of the input element.
Changing its value will not change the value of the input (as it is not a two-way binding, you just assigned the value to it)
So you need to directly target the value property of the input to alter its value
If you are trying to avoid using the .value to a lot of places you can cache both the input element and its value for different uses..
function deleteInputOnClick(input){
var champ = document.getElementById(input),
value = champ.value;
if(value=='E-mail'){
champ.value = "";
}
}
document.getElementById(input).value returns a string value while document.getElementById(input) returns a reference (an object). So in one case only the value of the local variable is changed, in the other the original object still links to the DOM value.
Have a look at this question: Javascript by reference vs. by value
I’ve read that you can disable (make physically unclickable) an HTML button simply by appending disable to its tag, but not as an attribute, as follows:
<input type="button" name=myButton value="disable" disabled>
Since this setting is not an attribute, how can I add this in dynamically via JavaScript to disable a button that was previously enabled?
Since this setting is not an attribute
It is an attribute.
Some attributes are defined as boolean, which means you can specify their value and leave everything else out. i.e. Instead of disabled="disabled", you include only the bold part. In HTML 4, you should include only the bold part as the full version is marked as a feature with limited support (although that is less true now then when the spec was written).
As of HTML 5, the rules have changed and now you include only the name and not the value. This makes no practical difference because the name and the value are the same.
The DOM property is also called disabled and is a boolean that takes true or false.
foo.disabled = true;
In theory you can also foo.setAttribute('disabled', 'disabled'); and foo.removeAttribute("disabled"), but I wouldn't trust this with older versions of Internet Explorer (which are notoriously buggy when it comes to setAttribute).
to disable
document.getElementById("btnPlaceOrder").disabled = true;
to enable
document.getElementById("btnPlaceOrder").disabled = false;
It is an attribute, but a boolean one (so it doesn't need a name, just a value -- I know, it's weird). You can set the property equivalent in Javascript:
document.getElementsByName("myButton")[0].disabled = true;
Try the following:
document.getElementById("id").setAttribute("disabled", "disabled");
The official way to set the disabled attribute on an HTMLInputElement is this:
var input = document.querySelector('[name="myButton"]');
// Without querySelector API
// var input = document.getElementsByName('myButton').item(0);
// disable
input.setAttribute('disabled', true);
// enable
input.removeAttribute('disabled');
While #kaushar's answer is sufficient for enabling and disabling an HTMLInputElement, and is probably preferable for cross-browser compatibility due to IE's historically buggy setAttribute, it only works because Element properties shadow Element attributes. If a property is set, then the DOM uses the value of the property by default rather than the value of the equivalent attribute.
There is a very important difference between properties and attributes. An example of a true HTMLInputElement property is input.value, and below demonstrates how shadowing works:
var input = document.querySelector('#test');
// the attribute works as expected
console.log('old attribute:', input.getAttribute('value'));
// the property is equal to the attribute when the property is not explicitly set
console.log('old property:', input.value);
// change the input's value property
input.value = "My New Value";
// the attribute remains there because it still exists in the DOM markup
console.log('new attribute:', input.getAttribute('value'));
// but the property is equal to the set value due to the shadowing effect
console.log('new property:', input.value);
<input id="test" type="text" value="Hello World" />
That is what it means to say that properties shadow attributes. This concept also applies to inherited properties on the prototype chain:
function Parent() {
this.property = 'ParentInstance';
}
Parent.prototype.property = 'ParentPrototype';
// ES5 inheritance
Child.prototype = Object.create(Parent.prototype);
Child.prototype.constructor = Child;
function Child() {
// ES5 super()
Parent.call(this);
this.property = 'ChildInstance';
}
Child.prototype.property = 'ChildPrototype';
logChain('new Parent()');
log('-------------------------------');
logChain('Object.create(Parent.prototype)');
log('-----------');
logChain('new Child()');
log('------------------------------');
logChain('Object.create(Child.prototype)');
// below is for demonstration purposes
// don't ever actually use document.write(), eval(), or access __proto__
function log(value) {
document.write(`<pre>${value}</pre>`);
}
function logChain(code) {
log(code);
var object = eval(code);
do {
log(`${object.constructor.name} ${object instanceof object.constructor ? 'instance' : 'prototype'} property: ${JSON.stringify(object.property)}`);
object = object.__proto__;
} while (object !== null);
}
I hope this clarifies any confusion about the difference between properties and attributes.
It's still an attribute. Setting it to:
<input type="button" name=myButton value="disable" disabled="disabled">
... is valid.
If you have the button object, called b: b.disabled=false;
I think the best way could be:
$("#ctl00_ContentPlaceHolder1_btnPlaceOrder").attr('disabled', true);
It works fine cross-browser.
<button disabled=true>text here</button>
You can still use an attribute. Just use the 'disabled' attribute instead of 'value'.