I'm using jStorage to store the value of an input, when I click the save button. Then I want to set the stored value as the current input value on page load. It ain't working too well though.
HTML
<input type='text' id='name'>
<div id="save">Save</div>
JS
$('#save').click(function() {
$.jStorage.set("key", $("#name").val());
});
var input_value = $.jStorage.get("key");
It's a little tangled up:
$.jStorage.set("key", $("#name").val());
var input_value = $.jStorage.get("key");
When you're passing a selector to jQuery you have to pass a valid string, not just the raw CSS selector syntax. That is, you've got to get the selector expression into JavaScript first, and you do that by creating a string constant.
edit — If you want your <input> to show the last-saved value when the page loads, you'd do something like this:
$(function() {
$('#name').val( $.jStorage.get("key") || "" );
});
Wrapping the activity in a $(function() { ... }) wrapper ensures that the code won't run until the <input> field has been seen and parsed by the browser, but still very soon after the user sees the page load (essentially immediately).
Adding the extra || "" bit after the jStorage call ensures that if the value is null or undefined the user won't see that. If there's no stored value, in other words, that'll have the input just be empty. You could put any other default value in there of course.
Related
The html for the textbox I was to get the value from is created from a .js file -- from javascript. I tried this to get the value that I enter into myTxtBox which is defined by a className:
<input type='text' class='myTxtBox editable' name='myTxtBox' value='' maxlength='200' size='90'/>
....
I try to retrieve the value I enter into myTxtBox as follows:
var txtval = document.getElementsByClassName('myTxtBox');
alert(txtval);
...more stuff where I set a breakpoint
the alert says I have [object htmlcollection]
intellisense does not give me .value -- I only get txtVal.valueOf, but when I break into the code and hover over txtval I get a listing for >Methods, ..., >myTxtBox. When I expand the >myTxtBox list if I scroll to the bottom of that listing I DO see "value" in >myTxtBox list and it DOES equal what I entered on the web page.
How do I retrieve that value? I have tried all sorts of options from the intellisense, but it either gives an error msg or [object htmlcollection] on the alert. How do I retrieve the value I entered? Or -- do I use something different than document.getElementsByClassName('myTxtBox') for my scenario?
You would need to return the index + value as getElementsByClassName returns a HtmlCollection so there are many elements to it.. try this:
var val = document.getElementsByClassName('myTxtBox')[0].value
alert(val)
getElementsByClassName returns a HtmlCollection which is array like. Do this like this:
var txtval = document.getElementsByClassName('myTxtBox')[0].value
alert(txtval)
I discovered that I could add an ID to my input element 'myTxtBox' and use jquery to retrieve the desired value, so I did this -- added an ID to the textbox and use jquery in the alert to do a document.getelementbyID
//--generate the html section here
"...<input type='text' class='myTxttBox editable datepicker' id='myTxtBox' name='myTxtBox' value='' size='10'/>..."
function NextButton_Click()
{
try
{
alert($("#PositionStartDateTextBox").val()); <---and this displays the value entered into this textbox
....
The whole deal is I have to evaluate some date textboxes because users can enter values in manually -- I guess the best fix would be for this textbox to not be editable. That would be another question -- how to add a datepicker and not have an editable textbox.
I am using the form where in a situation i have to use placeholder or title to insert the value in the database, i know we can use
$form.serialize which picks all the values of the form, but in my case value field is always going to be empty and i want to pick placeholders value and title value if placeholder is not defined just like serialization,
is there custom build jquery code or something already build in, how can i can use it just like $(form).serializePlaceholder or $(form).serializrtitle
well if some cases like IE8, placeholders are not supported, it should automatically pick title or i can define it in such a way that if placeholder is not defined, pick title
Try replacing empty values with their placeholder when the form is submitted, like so:
jQuery(function($) {
$('form').on('submit', function(e) {
e.preventDefault();
$(this).children('input, textarea').each(function() {
if(!$(this).val()) {
$(this).val($(this).attr('placeholder'));
}
});
$(this).submit();
});
});
An answer to your question lies in this bin I created. I think it solves your problem and if it does, I would like to ask you politely to remove the last comment you added on the thread you had with D4V1D.
Cheers!
I have a simple textarea and It has a default value. I want to hold this value everytime. User should not remove this value but he can add extra string.
<textarea>This is contstant</textarea>
As you see above. It has a default value. How can I protect this value? But user can add something after default value like below.
<textarea>This is contstant and extra things by user</textarea>
So how can do a partially editable textarea with default value?
You can attach an event handler to the <textarea> that does a simple validation every time it changes. If it tries to change to where your constant is partially destroyed, overwrite the X characters of the string value.
$('#foo').keydown(function () {
if ($(this).val().indexOf("This is constant. ") !== 0) {
var length = "This is constant. ".length;
var current = $(this).val();
var after = current.slice(length);
$(this).val("This is constant. " + after);
}
});
Here is a example on JSFiddle.
I recommend using JQuery for this because <textarea> doesn't actually have a value, or I think even a text attribute that you can check. JQuery just abstracts away <textarea>'s quirks.
I would go this way:
Style the textarea to remove the border.
Put a div on top which contains the constant text.
Wrap both elements in a div to give it a common border.
That way, the constant text will appear as if it was part of the textarea but it's not.
When you submit the form, prepend the static text to the field value.
Using jQuery, I change the value of an input text field through some process. After the process is done, I need to capture this change and apply it to another process. My problem is that I can't seem to capture this change and assign it to a variable. I know the changes are happening because the DOM is getting updated. Furthermore, this variable assignment works in IE, but not for the other browsers I tested.
Below is a snippet to prove my point (and you can see this online here: http://jsfiddle.net/xMwAE/).
<form>
<input type="hidden" name="my_hidden" value="Hidden Field" />
<input type="text" name="my_text" value="Text Field" />
</form>
$().ready(function() {
$('input[name=my_hidden]').val('Hello Hidden Field');
$('input[name=my_text]').val('Hello Text Field');
// Display
var temp = $('form').html();
// Though the DOM is updated with the new values. The variable temp
// does not capture the changes to the input text field, but captures
// the change in the hidden field. When in IE, temp captures the
// changes in both fields.
alert(temp);
});
Obviously, I need consistent behavior across browsers. Any ideas what's going on?
I don't get any trusted idea what happens, but somehow there should be a difference between setting the value as a member (input.value) or setting the value as a attribute-node.
This works for me :
$('input[name=my_text]').each(function()
{ this.setAttribute('value','Hello Text Field');});
I guess its a bug in innerHTML, see bugzilla: https://bugzilla.mozilla.org/show_bug.cgi?id=535992
Alternatively, you can store the values of your fields into array and use however you like like this:
var data = [];
$('form :input').each(function(){
data.push(this.value);
});
Now you can check for values like this:
alert(data[0]);
alert(data[1]);
Unfortunately form.reset() function doesn't reset hidden inputs of the form.
Checked in FF3 and Chromium.
Does any one have an idea how to do the reset for hidden fields as well?
Seems the easiest way of doing that is having <input style="display: none" type="text"/> field instead of <input type="hidden"/> field.
At this case default reset process regularly.
This is correct as per the standard, unfortunately. A bad spec wart IMO. IE provides hidden fields with a resettable defaultValue nonetheless. See this discussion: it's not (alas) going to change in HTML5.
(Luckily, there is rarely any need to reset a form. As a UI feature it's generally frowned upon.)
Since you can't get the original value of the value attribute at all, you would have to duplicate it in another attribute and fetch that. eg.:
<form id="f">
<input type="hidden" name="foo" value="bar" class="value=bar"/>
function resetForm() {
var f= document.getElementById('f');
f.reset();
f.elements.foo.value= Element_getClassValue(f.elements.foo, 'value');
}
function Element_getClassValue(el, classname) {
var prefix= classname+'=';
var classes= el.className.split(/\s+/);
for (var i= classes.length; i-->0;)
if (classes[i].substring(0, prefix.length)===prefix)
return classes[i].substring(prefix.length);
return '';
}
Alternative ways of smuggling that value in might include HTML5 data, another spare attribute like title, an immediately-following <!-- comment --> to read the value from, explicit additional JS information, or extra hidden fields just to hold the default values.
Whatever approach, it would have to clutter up the HTML; it can't be created by script at document ready time because some browsers will have already overridden the field's value with a remembered value (from a reload or back button press) by that time that code executes.
Another answer, in case anyone comes here looking for one.
Serialize the form after the page loads and use those values to reset the hidden fields later:
var serializedForm = $('#myForm').serialize();
Then, to reset the form:
function fullReset(){
$('#myForm').reset(); // resets everything except hidden fields
var formFields = decodeURIComponent(serializedForm).split('&'); //split up the serialized form into variable pairs
//put it into an associative array
var splitFields = new Array();
for(i in formFields){
vals= formFields[i].split('=');
splitFields[vals[0]] = vals[1];
}
$('#myForm').find('input[type=hidden]').each(function(){
this.value = splitFields[this.name];
});
}
You can use jQuery - this will empty hidden fields:
$('form').on('reset', function() {
$("input[type='hidden']", $(this)).val('');
});
Tip: just make sure you're not resetting csrf token field or anything else that shouldn't be emptied. You can narrow down element's specification if needed.
If you want to reset the field to a default value you can use(not tested):
$('form').on('reset', function() {
$("input[type='hidden']", $(this)).each(function() {
var $t = $(this);
$t.val($t.data('defaultvalue'));
});
});
and save the default value in the data-defaultvalue="Something" property.
I found it easier to just set a default value when the document is loaded then trap the reset and reset the hidden puppies back to their original value. For example,
//fix form reset (hidden fields don't get reset - this will fix that pain in the arse issue)
$( document ).ready(function() {
$("#myForm").find("input:hidden").each(function() {
$(this).data("myDefaultValue", $(this).val());
});
$("#myForm").off("reset.myarse");
$("#myForm").on("reset.myarse", function() {
var myDefaultValue = $(this).data("myDefaultValue");
if (myDefaultValue != null) {
$(this).val(myDefaultValue);
}
});
}
Hope this helps someone out :)
$('#form :reset').on('click',function(e)({
e.preventDefault();
e.stopImmediatePropagation();
$("#form input:hidden,#form :text,#form textarea").val('');
});
For select, checkbox, radio, it's better you know (hold) the default values and in that event handler, you set them to their default values.
Create a button and add JavaScript to the onClick event which clears the fields.
That said, I'm curious why you want to reset these fields. Usually, they contain internal data. If I would clear them in my code, the post of the form would fail (for example after the user has entered the new data and tries to submit the form).
[EDIT] I misunderstood your question. If you're worried that someone might tamper with the values in the hidden fields, then there is no way to reset them. For example, you can call reset() on the form but not on a field in the form.
You could think that you could save the values in a JavaScript file and use that to reset the values but when a user can tamper with the hidden fields, he can tamper with the JavaScript as well.
So from a security point of view, if you need to reset hidden fields, then avoid them in the first place and save the information in the session on the server.
How I would do it is put an event listener on the change event of the hidden field. In that listener function you could save the initial value to the DOM element storage (mootools, jquery) and then listen to the reset event of the form to restore the initial values stored in the hidden form field storage.
This will do:
$("#form input:hidden").val('').trigger('change');
You can reset hidden input field value using below line, you just need to change your form id instead of frmForm.
$("#frmForm input:hidden").val(' ');