How can I use defaultValue with hidden element [duplicate] - javascript

Assume you have input element:
<input id="aaa" type="text" value="unchanged" />
Then launch js script:
var e = document.getElementById("aaa");
e.value = "changed";
alert(e.defaultValue + "/" + e.value);
Result will be "unchanged/changed". Unfortunately, when your input element is hidden:
<input id="aaa" type="hidden" value="unchanged" />
...the same js script seem not to be working any more. Result is "changed/changed".
Is this a proper way? If so, why only hidden form elements act different?

The "defaultValue" property is only maintained in a way you apparently expect for "text", "file", and "password" fields.
Here is the relevant portion of the DOM spec.
I suspect the reason for this is that user activity on its own cannot change the value of hidden elements. If you want to preserve the initial values, run something at "load" or "ready" to stash the value somewhere.

For hidden input elements, defaultValue isn't actually implemented. The reason why you get the same result ast .value is because the browser your using is just defaulting.
See here for a discussion of this with Firefox.

Related

Javascript setInterval not working as expected [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');

getElementsByName not working

Looked up several "Answers" to this problem, but it was mostly just people not treating the result returned by getElementsByName() as a NodeList!
Edit: I am trying to hide/show elements based on an element being clicked. I could hardcode this using document.getElementById and just add one everytime I have an element I want to hide/display. But it would be ideal if I could retrieve all elements named something and just run a loop on them to hide/show. Then I could just tag an element with a name when writing and this loop would work without alteration. Below my code is simply trying to popup an alert with the value for testing purposes. As for now, it consistently breaks with a null error. I am using and designing for internet explorer 9 as this is what the company uses.
Code:
<input type="radio" name="Area" value="Engineering" id="EngineeringCheck" onclick="javascript: ShowContentEngineering();" />Engineering
<script type="text/javascript">
function ShowContentEngineering() {
alert(document.getElementsByName('EngineeringAreas')[0].value)
document.getElementById('InformationBlock').style.display = 'block';
}
</script>
<h5 name="EngineeringAreas" value="luls"> WHAT THE HECK </h5>
Code above breaks saying that the object at getElementsByName('EngineeringAreas')[0] is null. Clearly, right below it, it is not null... Am I confusing getElementsByName('string')[0].value with the value of the element? Or is it retrieving some other value?
Ideally, I'd add other elements later, tag them with "EngineeringAreas" and never have to mess with the hide/show function.
Edit: Here is the error message:
Unhandled exception at line 53, column 9 in http://localhost:57264/Home/Index
0x800a138f - Microsoft JScript runtime error: Unable to get value of the property 'value': object is null or undefined
Here you go... seems:
onclick="javascript: <--- not necessary - just reference the function name
ShowContentEngineering needs to be set in the window context
You're referencing the "value" attribute of an element that doesn't allow value attributes (h5)
I made it work instead grabbing the innerHTML of the h5
Code
<input type="radio" name="Area" value="Engineering" id="EngineeringCheck" onclick="ShowContentEngineering();" />Engineering
<h5 name="EngineeringAreas"> WHAT THE HECK </h5>
<script>
window.ShowContentEngineering = function() {
alert(document.getElementsByName('EngineeringAreas')[0].innerHTML)
document.getElementById('InformationBlock').style.display = 'block';
}
</script>
Here's a working fiddle: https://jsfiddle.net/mu970a8k/
Insert .attributes[1] between .getElementsByName('EngineeringAreas') and .value. The 1 points to the second attribute in the <h5> element named EngineeringAreas, which is value. Placing .value after .attributes[1] should return the value text “luls” in the alert box. The alert code should then be set up like this:
alert(document.getElementsByName('EngineeringAreas')[0].attributes[1].value);
More Info: http://www.w3schools.com/jsref/prop_attr_value.asp

Create an input field using pure Javascript

Im trying to create such element only with JS:
<input type="text" value="default">
To do so, I tried this code:
var mi = document.createElement("input");
mi.type= "text"
mi.value = "default"
But when I run it in Chrome Dev Tools, it only creates this element:
<input type="text">
What am I missing?
Setting a property of a HTMLElement isn't exactly the same as setting it's attribute to the same thing.
You most likely wanted to use element.setAttribute
var mi = document.createElement("input");
mi.setAttribute('type', 'text');
mi.setAttribute('value', 'default');
Now you can see
new XMLSerializer().serializeToString(mi);
// "<input type="text" value="default">"
In your example, the value displayed by the <input> will still be default, it just isn't set as the attribute.
Further note that if the user changes the value of <input>, e.g. types into it, setting the attribute will not change the value any longer, but setting the value property will still change it. Again, this is because an attribute is different to a property.
var i = document.createElement("input"); //input element, text
i.setAttribute('type',"text");
i.setAttribute('name',"username");
i.setAttribute('value',"default");
I think you are missing the ; after "text".

Setting input value to attribute value in JQuery

I have a number of <input /> boxes which I want to start off having a value of something like "Enter your name...".
When you focus them, the value becomes empty and you can type away. When you blur them, if nothing has been entered, then it goes back to "Enter your name...".
I thought of having something like this:
<input id="name" _startValue="Enter your name..." />
Then, something like this:
$(document).ready($("input").val($(this).attr(_startValue)));
This initially should set the value to _startValue but it does nothing. Replacing the line with:
$(document).ready($("input").val("hello"));
does work, however, so the problem must be with the $(this) or the attr().
First of all, how do I get this to work. Secondly, if I am trying to do this in a really retarded way, what is a good way to get this functionality?
I believe its better to use a placeholder like:
<input id="name" placeholder="Enter your name..." />
There are already libraries for this, and if you are already using jquery you should use them.
https://github.com/mathiasbynens/jquery-placeholder
just add the attribute "placeholder" and invoque the function:
<input placeholder="my placeholder">
<script type="text/javascript">
$("document").ready(function(){
$("input").placeholder();
});
</script>
Note that you only need to add the plugin if you need old browser support (in IE specially), otherwise, the attribute is enough.
Also, consider that if you code this, it will take you errors like submitting the default value of the form. What jquery plugins do generally is to make a <span> or whatever and place it on top of the input when the input is empty, and hide it when the input is not empty.
// v---you're not passing a function
$(document).ready($("input").val($(this).attr(_startValue)));
// `this` isn't magic-------^---- It doesn't just mean what you want
Should be more like this:
$(document).ready(function() {
$("input").val(function() {
return $(this).attr("_startValue");
});
});
A common way to mimic placeholders is to put the placeholder text in the element's value, then check the value on focus like:
if (this.value == this.defaultValue) this.value = '';
and then on blur:
if (this.value == '') this.value = this.defaultValue;
Please don't use placeholders instead of labels or onscreen help (e.g. format for dates). If a browser doesn't support the placeholder attribute, it's probably best not to emulate them if using it for the default value is an issue.
After all, placeholders are a "nice to have", they should not be fundamental to using the form correctly.

How to prevent user from typing in text field without disabling the field?

I tried:
$('input').keyup(function() {
$(this).attr('val', '');
});
but it removes the entered text slightly after a letter is entered. Is there anyway to prevent the user from entering text completely without resorting to disabling the text field?
A non-Javascript alternative that can be easily overlooked: can you use the readonly attribute instead of the disabled attribute? It prevents editing the text in the input, but browsers style the input differently (less likely to "grey it out")
e.g. <input readonly type="text" ...>
if you don't want the field to look "disabled" or smth, just use this:
onkeydown="return false;"
it's basically the same that greengit and Derek said but a little shorter
$('input').keydown(function(e) {
e.preventDefault();
return false;
});
$('input').keypress(function(e) {
e.preventDefault();
});
If you want to prevent the user from adding anything, but provide them with the ability to erase characters:
<input value="CAN'T ADD TO THIS" maxlength="0" />
Setting the maxlength attribute of an input to "0" makes it so that the user is unable to add content, but still erase content as they wish.
But If you want it to be truly constant and unchangeable:
<input value="THIS IS READONLY" onkeydown="return false" />
Setting the onkeydown attribute to return false makes the input ignore user keypresses on it, thus preventing them from changing or affecting the value.
One other method that could be used depending on the need $('input').onfocus(function(){this.blur()}); I think this is how you would write it. I am not proficient in jquery.
For a css-only solution, try setting pointer-events: none on the input.
Markup
<asp:TextBox ID="txtDateOfBirth" runat="server" onkeydown="javascript:preventInput(event);" onpaste="return false;"
TabIndex="1">
Script
function preventInput(evnt) {
//Checked In IE9,Chrome,FireFox
if (evnt.which != 9) evnt.preventDefault();}
I like to add one that also works with dynamic javascript DOM creation like D3 where it is impossible to add:
//.attr(function(){if(condition){"readonly"]else{""}) //INCORRECT CODE !
to prevent actions on a HTML input DOM element add readonly to class:
var d = document.getElementById("div1");
d.className += " readonly";
OR in D3:
.classed("readonly", function(){
if(condition){return true}else{return false}
})
AND add to CSS or less:
.readonly {
pointer-events: none;
}
the nice thing about this solution is that you can dynamically turn it on and of in a function so it can be integrated in for example D3 at creation time (not possible with the single "readonly" attribute).
to remove the element from class:
document.getElementById("MyID").className =
document.getElementById("MyID").className.replace(/\breadonly\b/,'');
or use Jquery:
$( "div" ).removeClass( "readonly" )
or toggle the class:
$( "div" ).toggleClass( "readonly", addOrRemove );
Just to be complete, good luck =^)
just use onkeydown="return false" to the control tag like shown below, it will not accept values from user.
<asp:TextBox ID="txtDate" runat="server" AutoPostBack="True"
ontextchanged="txtDate_TextChanged" onkeydown="return false" >
</asp:TextBox>
One option is to bind a handler to the input event.
The advantage of this approach is that we don't prevent keyboard behaviors that the user expects (e.g. tab, page up/down, etc.).
Another advantage is that it also handles the case when the input value is changed by pasting text through the context menu.
This approach works best if you only care about keeping the input empty. If you want to maintain a specific value, you'll have to track that somewhere else (in a data attribute?) since it will not be available when the input event is received.
const inputEl = document.querySelector('input');
inputEl.addEventListener('input', (event) => {
event.target.value = '';
});
<input type="text" />
Tested in Safari 10, Firefox 49, Chrome 54, IE 11.
The best solution is to unfocus input once user clicks it so it makes it kinda readonly
onFocus={e => e.target.blur()}

Categories

Resources