Javascript and defaultValue of hidden input elements - 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

Strange behaviour when input element switches type to hidden

I discovered a strange behavior of input text/hidden elements and I would like to know why this happens.
I have an input text box that has a value, let's say "test". I delete the input element value and I change the type of this element into "hidden". If now I switch it back to "text" the original value is there! If you don't fully delete the value of the text element but change it your changes are preserved. Why if you clear the element value this change is not preserved?
I created a fiddle that can show you what I mean.
function toggler() {
var iobj = document.getElementById('test');
if (iobj.type == 'text') {
iobj.type = 'hidden';
} else {
iobj.type = 'text';
}
}
<button name="toggle" type="button" onclick="toggler()">Toggle</button><br /><br />
<input type="text" name="test" id="test" value="sample" />
This has something to do with how different browsers handle defaultValue property of the inputs, whenever their type is changed. In this case, when the input type is changed and the .value is empty, Firefox uses the last non-empty value as .defaultValue property of the input. When the type is changed into text, Firefox uses the .defaultValue property for setting current .value property of the input. Chrome doesn't do this, i.e. it uses the last value, empty or non-empty, as the .defaultValue.
Here is a demo on jsfiddle. Comparing the logged values on Firefox and Chrome console, should demonstrate the different behaviors.
I should also mention that according to my experience/knowledge, Firefox is more standards-compliant than other browsers.
That being said, changing type of an input has never been a good idea. Form elements are very different and browsers handle the case in different ways.

Insert the value retrieved from localstorage to the input field

I am using localStorage where in I am able to store in previous page and retrive it in this page. (Checked it using alert).
name12=localStorage.getItem("content");
Now my requirement is to display it into the input field and make it non-editable.
Please help me out with it. I have tried different things but I am not able to get it right.
Used onblur="localStorage.setItem(this.name, this.value) in the input tag
and also tried to use
if name_2.value = name12; in script tag
To make a field uneditable, you can use the html attribute disabled on the input field. http://www.w3schools.com/tags/att_input_disabled.asp
To set a default value for a field, you can use the html attribute value. In your case since the value is dynamic, you probably want do not want to do that inline in the html. One possible solution is to set the value attribute through javascript like below.
<script type="text/javascript">
var name2 = document.getElementById("name_2");
name2.value = localStorage.getItem("content");;
</script>
Set the value of an input field
You have to assign the value to input using javascript.
<input username" id="name_2" type="text" placeholder="name" name="name_2" required="required" autofocus="autofocus">
<script>
var n = "5"; // read from storage here
var inpt = document.getElementById("name_2");
inpt.value = n;
inpt.disabled = true;
</script>
There are many places to find this information. Try reading the jquery documentation when you get stuck. For example, here is a page that describes how to set the value of an input element. StackOverflow also has many questions about this topic. A quick google search brings up this question about setting the value of input elements. We can also find SO questions about disabling input elements easily, like this one.
I encourage that you attempt to use more resources to find what you need before bringing your questions here.
Based on the answers to the questions I linked, we can set the input and then disable it to keep the value from changing:
$('#input').val(name12);
$('#input').prop('disabled', true);

Setting element value in Javascript [duplicate]

This question already has answers here:
HTML - attributes vs properties [duplicate]
(2 answers)
Closed 8 years ago.
I have the below element:
<input type="text" value="" tabindex="1" size="15" onblur="UpCaseSearch(this)" name="name">
which is an empty text field.
I want to set text into that field and I can successfully do that using a command like that (when I say successfully I mean that I can see that field populated with text test:
window.frames[1].document.getElementsByName('name')[2].value = "test"
I have 2 questions however:
When I look at that element on the page I see that the value attribute is still empty "". Why is that? Where is the actual text that I can see in that field is coming from?
If I try the below command, it will actually set the value but then the field remains empty:
window.frames[1].document.getElementsByName('name')[2].setAttribute('value', 'test')
So it looks like that's not the same value in both cases. Is that right?
Try this:
window.frames[1].document.getElementsByName('srchsnam')[2].value = "Test"
Let me know if it worked!
In short, the value attribute in source-code (and dom) serves as 'defaultValue'.
For example, imagine this input-field (which is a common way to use this functionality):
<input type="text"
value="your name here"
onfocus="if (this.value===this.defaultValue) this.value='';"
onblur="if (this.value==='') this.value=this.defaultValue;" >
In other words, to set the default value in html-markup (<input value="your_value" type="text">) and from javascript you set the value-attribute (using the methods: var val=elm.getAttribute('value') and elm.setAttribute('value', val).
This is also why (as you have seen) these attributes propagate to the element's outerHTML (and thus the element's parent innerHTML).
However to get/set the element's current value property you use: var val=elm.value and elm.value=val.
Sidenote: Almost the same goes for a textarea: you can use .defaultValue on a textarea to retrieve it's textContent (but you'd override/change that by setting it's innerHTML) while you get/set the current value using elm.value.
Hope this helps!

Checkbox irregularities with jQuery

Here's some html:
<form>
<input type="checkbox" id="check-123" />
<input type="text" id="text-123" onchange="doSomething('123')" />
</form>
And here's some javascript:
function doSomething(key)
{
var textbox = $('#text-'+key);
var checkbox = $('#check-'+key);
checkbox.attr('checked',(textbox.val()!="") );
}
My goal here is to check the checkbox anytime there's a value in the text box, and uncheck when that value is removed. This appears to work fine in the html (I can see checked="checked" being added to the checkbox), but the checkbox only appears checked the first time something is entered in the textbox.
Why would a checkbox show unchecked even if checked="checked" was added to the html?
Use element properties rather than attributes to change their state via javascript
checkbox.prop('checked',(textbox.val()!="") );
From the jQuery docs on .attr() and .prop():
As of jQuery 1.6, the .attr() method returns undefined for attributes that have not been set. To retrieve and change DOM properties such as the checked, selected, or disabled state of form elements, use the .prop() method.
The emphasis is jQuery's own. Only the checked property will reflect and control the checkbox's current state. The checked attribute shouldn't be used to control the checkbox state.
consider something like:
function doSomething(el) {
el.form['check-' + el.name.split('-')[1]].checked = !!el.value;
}
<form>
<input type="checkbox" name="check-123">
<input type="text" name="text-123" onchange="doSomething(this)">
</form>
I've seen some funny things with the checked attribute in IE8 and lower. In some cases I've had to set both the property and the attribute, even though modern browsers seem to be okay with just adjusting the property:
checkbox.prop('checked',textbox.val()!="");//property
Note, the following is only necessary if you come across any browser related inconsistencies.
if(textbox.val()!="")
{
checkbox.attr('checked','checked');
}
else
{
checkbox.removeAttr('checked');
}

Clear default values using onsubmit

I need to clear the default values from input fields using js, but all of my attempts so far have failed to target and clear the fields. I was hoping to use onSubmit to excute a function to clear all default values (if the user has not changed them) before the form is submitted.
<form method='get' class='custom_search widget custom_search_custom_fields__search' onSubmit='clearDefaults' action='http://www.example.com' >
<input name='cs-Price-2' id='cs-Price-2' class='short_form' value='Min. Price' />
<input name='cs-Price-3' id='cs-Price-3' class='short_form' value='Max Price' />
<input type='submit' name='search' class='formbutton' value=''/>
</form>
How would you accomplish this?
Read the ids+values of all your fields when the page first loads (using something like jquery to get all "textarea", "input" and "select" tags for example)
On submit, compare the now contained values to what you stored on loading the page
Replace the ones that have not changed with empty values
If it's still unclear, describe where you're getting stuck and I'll describe more in depth.
Edit: Adding some code, using jQuery. It's only for the textarea-tag and it doesn't respond to the actual events, but hopefully it explains the idea further:
// Keep default values here
var defaults = {};
// Run something like this on load
$('textarea').each(function(i, e) {
defaults[$(e).attr('id')] = $(e).text();
});
// Run something like this before submit
$('textarea').each(function(i, e){
if (defaults[$(e).attr('id')] === $(e).text())
$(e).text('');
})
Edit: Adding some more code for more detailed help. This should be somewhat complete code (with a quality disclaimer since I'm by no means a jQuery expert) and just requires to be included on your page. Nothing else has to be done, except giving all your input tags unique ids and type="text" (but they should have that anyway):
$(document).ready(function(){
// Default values will live here
var defaults = {};
// This reads and stores all text input defaults for later use
$('input[type=text]').each(function(){
defaults[$(this).attr('id')] = $(this).text();
});
// For each of your submit buttons,
// add an event handler for the submit event
// that finds all text inputs and clears the ones not changed
$('input[type=submit]').each(function(){
$(this).submit(function(){
$('input[type=text]').each(function(){
if (defaults[$(this).attr('id')] === $(this).text())
$(this).text('');
});
});
});
});
If this still doesn't make any sense, you should read some tutorials about jQuery and/or javascript.
Note: This is currently only supported in Google Chrome and Safari. I do not expect this to be a satisfactory answer to your problem, but I think it should be noted how this problem can be tackled in HTML 5.
HTML 5 introduced the placeholder attribute, which does not get submitted unless it was replaced:
<form>
<input name="q" placeholder="Search Bookmarks and History">
<input type="submit" value="Search">
</form>
Further reading:
DiveintoHTML5.ep.io: Live Example... And checking if the placeholder tag is supported
DiveintoHTML5.ep.io: Placeholder text
1) Instead of checking for changes on the client side you can check for the changes on the client side.
In the Page_Init function you will have values stored in the viewstate & the values in the text fields or whichever controls you are using.
You can compare the values and if they are not equal then set the Text to blank.
2) May I ask, what functionality are you trying to achieve ?
U can achieve it by using this in your submit function
function clearDefaults()
{
if(document.getElementById('cs-Price-2').value=="Min. Price")
{
document.getElementById('cs-Price-2').value='';
}
}

Categories