How to store user input locally using JavaScript - javascript

I'm creating a cross-platform app and I want the user bio to be stored locally and stay there after refresh and close/reopen.
Thanks
var newBio = document.getElementById("bio").value;
var storeBio = localStorage.setItem(newBio);
document.getElementById("bio").innerHTML = localStorage.getItem(storeBio);
<input id="bio" type="text" name="search" placeholder="Bio" onmouseout="showBotNav(); saveBio()"><br>

Look at the the examle in MDN documentation or elsewhere if you don't know how to write something.
.getItem needs a name as an argument. And .setItem needs two (name and value) but you provided only one argument storeBio wich is incorrect( also because function localStorage.setItem
can't be a name).
In your html you declared saveBio function. Why not show us save and get functions as is?
function saveBio() {
var newBio = document.getElementById("bio").value;
localStorage.setItem('bio', newBio);
}
function getBio() {
// why you were using (correct way) ".value" when setting bio
// but here you are using .innerHTML ?
document.getElementById("bio") //.innerHTML =
.value = localStorage.getItem('bio')
// by the way innerHTML is only present on elements with closing tag. Input element is not one of
}
// here you calling function when page is loaded
getBio()
<input id="bio" type="text" name="search" placeholder="Bio" onmouseout="showBotNav(); saveBio()"><br>
The posted question indicates that you did not include enough effort to solve your problem. We are always glad to help and support new coders here on SO but you need to help yourself first.

Related

JavaScript - Input value undefined

HiI'm new to web development and tring to understand some basics. To make it short, I have an input like this:
<input type="text" id="field" name="field" placeholder="Write something here...">
On separate file with JS extension I want to get the value from this input. I tried doing so in two ways, one in vanilla JS:
var value = document.getElementById('field').value;
This returns the correct value, and second with jQuery:
var value2 = $('#field').value;
And getting an 'undefined" from the second.
Why is this so?
Ok,so you do this by using
var value = $("#field").val();
The reason the first approach works is because it returns the HTML element object and you assess its value property.(you can access any property of that element using . operator)
However using jquery returns JQUERY object and since it does not have a value property u can not access it. You need to use jqueries val function.
In jquery you use the method val(). It would look like this :
var value2 = $('#field').val();

Alternative in regular expression's ending

I have the following DOM structure:
<form>
<input type="text" id="a">
<button>Submit</button>
</form>
or:
<form>
<input type="text" id="a">
</form>
which one depends on what user have done, it's created dynamically.
I want to be able to add another input right below the previous one (it can not exist yet and be the first one). To do that, I wanna get all text until the place I'm adding new input. How can I get that text using regex?
I tried the following:
'(.*?)[<button.*?>Submit<\/button><\/form>|<\/form>]'
But it doesn't work, because it displays empty string as a result.
var afterRegex = new RegExp('(.*?)[<button.*?>Submit<\/button><\/form>|<\/form>]', 'i');
var appendAfter = $(".downloadCode textarea").val().match(afterRegex)[1];
alert(appendAfter);
I'm a little confused by your code, but, based on what you've said (and that you've tagged your question with jQuery), I think that you can accomplish what you are trying to do with this code:
var $newInput = **CREATE_YOUR_NEW_INPUT_ELEMENT_HERE**;
var $form = $("form");
var $lastInput = $form.find("input:last");
// no inputs, make the new input the first element in the form
if ($lastInput.length < 1) {
$form.prepend($newInput);
}
// at least on existing input, add the new input after the last one
else {
$lastInput.after($newInput);
}
You should not parse HTML using Regexp. No, seriously.
That being said, the correct syntax for multi-character alternatives is (?:alternativeA|alternativeB):
(.*?)(?:<button.*?>Submit<\/button><\/form>|<\/form>)
Note that this does not work if you have whitespace characters in between. Yet another reason not to use Regexps here.

crm 2011 xrm.page.getattribute returns null when there is value

I'm not really skillful with JScript but I've written the following code within a function webResource that is supposed to run when the form loads (OnLoad)
var creationDateName = "createdon";
var today = new Date();
var creationDateAttr = Xrm.Page.getAttribute(creationDateName);
if(creationDateAttr!=null)
{
/* Some more code */
}
The problem is that Xrm.Page.getAttribute(creationDateName) returns null when there is a value on the field (the field is not being displayed in form but when looking up it has a value). Funky thing about it is that in my test organization the same code worked like a charm, but when I copied and paste it on the production organization to release the solution it doesn't work properly that's what confuses me a lot. Any idea what might be happening?
You need to use getValue to return the value in the field. Your code is merely checking that the field exists on the Page.
You also need to be aware that in Create mode, these values are not set, so you can't retrieve them. In Update mode they will work. So you need to check that the Page is in Update mode too:
var formType = Xrm.Page.ui.getFormType();
if (formType === 2) // Update
{
var creationDate = Xrm.Page.getAttribute(creationDateName).getValue();
}
it gives you the attribute not the value..
to get the value you have to write code as below
var creationDateAttr = Xrm.Page.getAttribute(creationDateName);
var valueDateAttr=creationDateAttr.getValue();
OR
var creationDateAttrValue = Xrm.Page.getAttribute(creationDateName).getValue();
hope this will help
Silly me, I forgot to add the field I was looking for that's why it return null but thanks to Donal for the answer, actually I was trying to verify if the field was full or was null. Thanks

Trying to use element ID to access object values native javascript

I'm trying to write some code to validate a form. I only want to use native js (ie no jQuery etc) and in addition I want to steer clear of inline events.
The (simplified version of the) form looks as follows:
<body onload="addListener()">
<div class="center">
<form method="get" name="signUpForm">
<input type="text" id="firstName"><br />
<input type="text" id="lastName"><br />
<input type="text" id="age"><br />
<input type="submit" value="Submit">
</form>
</div>
What I've then done is created an object to contain relevant information as it pertains to each field (have just added the initial one here to give you the idea:
var Field = { req: true,
minlength: 2,
maxlength: 20,
errorMessage: "",
regex: /[^a-zA-Z- ]/}
var firstName = Object.create(Field);
firstName.maxlength = 30;
firstName.errorMessage = "Please enter a first name between one and twenty letters. Please use only uppercase and lowercase letters spaces and hyphens.";
firstName.regex = /[^a-zA-Z- ]/;
What I now want to do is use the id of the field which triggers the event to access the information contained in the Field object.
The two very simple functions I've written thus far tom attempt this are:
function addListener(){
document.body.addEventListener('keyup', eventIdentify);
}
function eventIdentify(){
var target = event.target || event.srcElement;
var id = target.id
console.log(id.maxlength);
}
However and this where it becomes a bit of a nightmare, id.maxlength keeps returning undefined.
If I try it with: "console.log(firstName.maxlength);" then it's fine but obviously that defeats the point. Not sure what's going on here, I suspect it's something to do with the id being used to reference two different things (the element id and the object) but I'm pretty new to this and not sure.
Would gratefully appreciate it if someone couold point me in the right direction.
Thanks in advance
Stef
target.id is a string, and as such it does not have a maxlength property. A quick solution would be to access de variable that is named as your id:
console.log(window[target.id].maxlength)
Still, a better way would be to create an object and incluse the other objects you already have:
var obj={};
obj.firstName=firstName;
And then you can do:
console.log(obj[target.id].maxlength)

Set hidden input value with javascript

function GetWidth(){
var TBL_width = document.getElementById('wrap_tbl').offsetWidth;
return TBL_width;
}
var w = GetWidth();
<input type="hidden" id="tbl" value= w />
Is this possible?
I want to store a JavaScript variable in value attribute of a hidden input element. Please guide me how to do this
Jquery version:
$("#tbl").val(w);
Pure JavaScript version:
document.getElementById("tbl").value = w;
There is no difference between hidden and "unhidden" inputs in this case.
Advice: If your's GetWidth function has only one line, and the line isn't too much sophisticated, you can extract it from the method.
function setWidth(){
var TBL_width = document.getElementById('wrap_tbl').offsetWidth;
document.getElementById("tbl").value = TBL_width;
}
Use javascript to set the value property of your hidden element:
var w=GetWidth();
document.getElementById('tbl').value = w;
or jQuery-style:
var w=GetWidth();
$('#tbl').val(w);
This will definitely not work ... and you already realized that :-)
Look what you did with the element "wrap_tbl" ... you accessed it by using document.getElementById(). You can do the exact same thing to access hidden elements
document.getElementById('tbl').value = w;
You could set the value use javascript.
document.getElementById('tbl').value=w;
If you use jQuery, just $('#tbl').val(w);
As the value asignament to the input has already answered, one question,
Do you need it as a param to be sent on submit?
if not, one suggestion: you can allways use the jquery data method
$('body').data('myDesiredName','myDesiredValue');
and to retrieve it
alert($('body').data('myDeesiredName')); //will alert 'myDesiredValue'
this way you can allways store multiple values and variables without the need of hidden elements,
happy coding ;)

Categories

Resources