Let's say I gave this code:
<input type="hidden" id="field" name="field" value="1">
<button id="change">Change</button>
And this javascript:
alert($("#field").val());
$("#change").on("click", function(){
var newValue = parseInt($("#field").val()) + 1;
$("#field").val(newValue);
alert($("#field").val());
});
If I change the value, go to a different page and then use the back button, in chrome and firefox the latest value is shown while in IE the default value.
How to fix that without using sessionstorage?
Fiddle
This is not a standard practice, may be Firefox and Chrome are caching the values. But you should not rely on it.
If you refresh the page using Ctrl + F5, it will not work.
you can not persist the value in the page itself..., any full page reload will clear any values which you have changed... so unless you save the state to some sort of persist layer... depending on the bowser the back button will behave in different ways... some much older browsers with no caching will reload the whole page.
Some may cache the actual javascript before the modifications and therefore load the old javascript and with the old value form the cache as well.
It is better to handle this in some sort of persist layer
see:
Ajax, back button and DOM updates
Please try to set value with:
$("#field").attr("value", newValue);
Don't use .val() method. I have a similar issue and I solved with it because IE not refresh a hidden value with .val().
Related
I have a <input type = 'file'>. To enable/disable it I use jQuery("#my_input").prop('disabled' ,true/false).
If I disable it, then refresh the page, jQuery outputs:
console.log(jQuery("#my_input").prop('disabled' )) ==> true
even though the 'disabled' prop is not included in the html.
Clearing the cache does not fix it.
Firefox has long been saving input values through refreshes, and now the latest builds also save input / button's disabled status through refreshes.
I'm not sure whether this is intended or a bug, but for the time being an workaround is to just set the inputs' disabled status to their default ones inside a DOM ready handler.
jQuery(function($) {
$("#my_input").prop('disabled', false);
});
Demonstrating the issue: Fiddle (open with Firefox)
And now fixed with the snippet above: Fiddle
You can also apply autocomplete="off" to the element and its disabled status won't persist through refreshes.
Fiddle
Note that this will prevent any form of auto-completion in the element. Of course, this is an excellent solution for file inputs and buttons, however depending on your use case (e.g. when it involves text inputs) you may prefer the former solution. Thanks to #dsdsdsdsd for the tip!
p.s. This has been reported to Mozilla already: Bugzilla ticket.
Firefox should include it in html also.
What happens if you use:
jQuery("#my_input").attr('disabled' ,true)
I have a input text box disabled:
<input type="text" name="name" disabled="disabled" />
In IE and in Chrome you can copy and paste the value populated in that input field but in Firefox you cannot.
Firefox does not allow clipboard manipulation through JavaScript for valid security concerns.
Any suggestion? Is there a work around this?
readonly="readonly" will do the job
it should be supported by the major browsers
I don't like using readonly="readonly", ever. It leaves the field focusable and reachable via tab keypress and, if, god forbid, the user hits the backspace key while the read-only field is focused, then most browsers treat it like the user hit the 'back' button and bring up the previously viewed page. Not what you want to see happen when you're filling out a large form, especially if you are using some archaic browser that doesn't preserve the form data when you hit the 'next' button to return to it. Also very, very bad when using some single-page web application, where 'back' takes you to a whole other world, and 'next' doesn't even restore your form, much less its data.
I've worked around this by rendering DIVs instead of input fields when I need the field disabled (or PRE instead of a textarea). Not always easy to do dynamically but I've managed to make fairly short work of it with AngularJS templates.
If you have time, head over to the Mozilla Bugzilla and ask them to fix it.
tl;dr: Support for selecting and copying text in a disabled field is unreliable; use the readonly attribute or a non-input element, such as a <span> instead, if this functionality is necessary. Use JavaScript to modify the behavior of the readonly input to prevent unwanted behavior such as going back a page when someone hits the backspace key while the readonly input has focus.
*UPDATE: 2018.12.24
The spec has changed since this answer was originally posted (thanks to Wrightboy for pointing this out); it now includes the following caveat with regards to disabled fields:
Any other behavior related to user interaction with disabled controls, such as whether text can be selected or copied, is not defined in this standard.
— https://html.spec.whatwg.org/multipage/input.html#the-readonly-attribute
Disabled fields still cannot receive focus nor click events.
Because the standard does not define whether or not text within disabled controls can be selected or copied and because at least one major browser doesn't support that functionality, it's probably best to avoid relying on that behavior.
Original Answer
This is the expected behavior for a disabled field (as of the original date of this answer). IE and Chrome are being generous, but Firefox is behaving appropriately.
If you want to prevent the user from changing the value of the field, but you still want them to be able to read it, and/or copy it's value, then you should use the readonly attribute. This will allow them to set focus to the element (necessary for copying), and also access the field via the tab button.
If you are concerned about a user accidentally hitting the backspace button inside the readonly field and causing the browser to navigate back a page, you can use the following code to prevent that behavior:
document.addEventListener("DOMContentLoaded", function() {
var inputs = document.querySelectorAll('[readonly]');
for(var i=0; i < inputs.length; i++){
inputs[i].addEventListener('keydown', function(e){
var key = e.which || e.keyCode || 0;
if(key === 8){
e.preventDefault();
}
})
}
});
<input value="Hello World" readonly=readonly />
As quick answer, one can have another not disabled element to enable + copy/paste + redisable your input text, like this:
$('#btnCopy').click(function(){
$('#txtInputDisabled').removeAttr('disabled');
$('#txtInputDisabled').select();
document.execCommand("copy");
$('#txtInputDisabled').attr('disabled','disabled');
});
You can se my complete response to this post
Refer to my post to the same question. It does the following:
Makes the textbox just like readonly without using the readonly attribute on the input tag, but will honor tab index and set focus
Supports all clipboard functions win and mac with mouse or keyboard
Allows undo, redo and select all
Restrict HTML input to only allow paste
You can accomplish this in share point by utilizing the contenteditable attribute as follows with jquery.
$("#fieldID").attr("contenteditable", "false");
This will allow the user to highlight the text and copy it but will not allow them to enter anything in the field.
What would be the best way to clear an input field on $.(document).ready()?
What I'd like to happen is when the user reloads or navigates away and navigates back to the page, the input field clears when the DOM is ready.
I've tried innerHTML and value="" but those don't seem to work.
$.(document).ready(function{
$("input:text").val("");
});
When using a jQuery representation of a DOM element, use the val method:
$('input:text').val('');
Have you tried http://api.jquery.com/val/?
Setting the value should work, but don't use $(document).ready() or $(window).load() .
Depending on the browser those events may not fire if the user navigates using back/forward.
Just put it somewhere at the end of the document, beyond the last input-element.
On my site, I have two checkboxes created in my ASP.NET MVC view like so:
Html.RadioButton("check", "true", "true" == (string) ViewData["someKey"], new { id = "check1"});
Html.RadioButton("check", "false", "false" == (string) ViewData["someKey"], new { id = "check2"});
I am positive that ViewData["someKey"] has the value "true" in it.
In my JS init function, I perform the following check:
alert($('#check1').is(':checked') + " " + $('#check2').is(':checked'));
In Firefox (and only Firefox), my alert dialog will show the following (it works as expected in every other browser):
Initial page load: true false
Normal refresh via Ctrl + R: false false
Refresh skipping cache via Ctrl + Shift + R: true false
I have tried many different methods of looking at the checkbox value, including $('#check1').attr('checked') without success. If I examine the HTML in Firebug, I can see that the first radio button has the property checked="checked" in it.
Why is the checkbox value changing in FF when I refresh, and how can I mitigate this? Since this seems to be a FF-only bug, how can I change my code to make it work?
This SO question seemed to ask something similar, but none of the proposed solutions seem to work in this case.
Edit: I should also point out that when the radio button is rendered after the refresh in FF, it's not actually being displayed as checked either, despite what the HTML is telling me.
Edit2: Adding raw HTML as per request
<input id="check1" type="radio" value="True" name="check" checked="checked"/>
<input id="check2" type="radio" value="False" name="check"/>
Can we see the generated HTML? Are you really creating two radio buttons with both the same name and the same value?
Remember when you hit refresh, browsers try to preserve the form field contents of the page before the refresh. This includes radio button state. If you have two indistinguishable radio buttons that would seem to be a good way to confuse a browser trying to re-establish the form state.
It sounds like your script could be running before the page is fully loaded. Where did you put the Javascript code? If you haven't already, try moving the code to the end of the <body> block.
I had the same problem a few days ago and the issue was that I was doing the "check" before the item was fully loaded or rendered, it was a DropDownList that I rendered with jQuery.
My case was very specific, but I had to rework the code to take this into account...
It seems that the problem isn't with checking whether or not the radio buttons are checked, but more that they buttons are actually unchecked even though the HTML code says otherwise.
I've posted a followup question to this one here as an addendum to this topic.
EDIT: This page has a good description of the problem and the solutions you can take to solve it.
I used this to force firefox to reset the radiobuttons checked upon refresh.
$(function(){ $('input[name="radiobuttongroup"]')[0].checked = true; });
where [0] is the index of the radiobutton in the specific group ( [0] = first radio button, [1] = second radio button, ..)
We've had a similar bug in firefox when using jquery to change the selection. Even though the code changed correctly according to firebug none of the radio buttons was selected. The solution we found is to remove the radio buttons from the DOM and just put them back.
var allradiobuttons = $('...');
allradiobuttons.click(function() {
var radiobutton = $(this);
allradiobuttons.removeAttr("checked");
radiobutton.attr("checked", "checked");
var parent = radiobutton.parent();
parent.html(parent.html()); // This is a weird fix
}
i have the following html :
<input type="text" id="searchbox" name="q" value="Search Pictures..." onclick=" if(this.value=='Search Pictures...'){this.value='';}" />
It's works when i open the page for the first time, but when i type something and search , then i come back to the page, or refresh, i find the past keyword still sticky instead of "Search Pictures..."
Any available tag to avoid this problem ?
Thanks
If you've set the value on the tag to "Search Pictures..." as you have, then whenever the page loads without having somehow persisted a newer value beforehand, you will get the "Search Pictures..." as the value.
To persist input data, you have several ways available depending on what environment you're developing with.
By the way... don't write:
this.value === 'blah blah, copy of text from value attribute'
Just simply use defaultValue property:
this.value == this.defaultValue
It's much simpler and cleaner.
I guess it's on firefox.
You can add the attribute autocomplete="off"
HTTP is stateless and does not persist form values between requests.
Every single time you load the page the 'hard-coded' VALUE 'Search Pictures...' will replace anything in the input element from the previous request. You need to persist the value by retrieving the posted value from the form collection and writing it back in. How you do this depends on the platform you are working on - presumably you are using some kind of server-side framework or language (e.g. PHP or ASP.NET)?