Trying to use element ID to access object values native javascript - 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)

Related

How to store user input locally using 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.

multiplication inside an input with "*" operator

I am trying to get a multiplication entered in an input replaced by its solution.
Basicaly, when you enter 3*3 into the input, I would like my javascript code to replace 3*3 by 9.
Probably not so hard to obtain but I'm a total noob with javascript here. I get this so far, but I should miss a crucial point!
Thanks for your help :)
function multiply() {
var string = document.getElementById("mult").value;
var array = string.split("*");
var res = Number(array[0]*array[1]);
document.getElementById("res").value = res;
}
input{width:80px; text-align:right;}
input[readonly]{border:0;}
entrer: <input type="text" id="mult" onblur="multiply()">
<br>result: <input type="text" id="res" readonly>
Your code actually works as it is now. Just make sure you tab out of the input field after typing in the equation and you'll see it do its job. That's because your code is running on the blur event, which is when the focus leaves an element.
But, as far as your conversion code goes:
Number(array[0]*array[1])
Attempts to convert the product of array[0] and array[1], when what you need is to convert each array value to a number first and then do the math.
Number(array[0]) * Number(array[1])
Now, instead of Number(), you can just prepend a + to each value that needs conversion.
+array[0] * +array[1]
But, in reality, anytime you attempt to do multiplication, division or subtraction on strings, they are automatically converted to numbers, so you really don't even need that here.
Lastly, since you are just displaying the result and don't want the user to be able to modify it, just put it into a regular element, like a span instead of a form field element that you then have to set to readonly. Form fields are primarily for collecting information, not displaying it. When you do work with a non-form field element, you don't use the value property, you use .textContent (when there is straight text) or .innerHTML (when the string contains HTML to be parsed).
function multiply() {
var string = document.getElementById("mult").value;
var array = string.split("*");
var res = array[0] * array[1];
document.getElementById("res").textContent = res;
}
input{width:80px; text-align:right;}
input[readonly]{border:0;}
entrer: <input type="text" id="mult" onblur="multiply()">
<br>result: <span id="res"></span>

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.

Javascript and using variables instead of strings in bracket notation

I have a PHP script that takes a text list with a variable number of questions and generates HTML form code that looks like this.
What did you think of X?<br />
<input type="hidden" name="$survey[0][0]" value="What did you think of X?">
<input type="radio" name="$survey[0][1]" value="1">Didn't like it.
<input type="radio" name="$survey[0][1]" value="2">I was indifferent.
<input type="radio" name="$survey[0][1]" value="3">Liked it.
$survey[n][0] is the question, $survey[n][1] is the answer, and n is the variable number of questions.
To validate using Javascript, I have a loop that loops through the questions, and a loop inside it that makes sure each question has an answer. My problem is referencing the elements with [] in their names. Here's what I think is the relevant part of my code.
var formElements = document.forms["form"].elements;
var groupCount = document.getElementsByTagName("li").length;
var groupNdx = 0;
var groupName = "";
var btnCount = 0;
while (groupNdx < groupCount) {
groupName = "'$survey[" + groupNdx + "][1]'";
btnCount = formElements[groupName].length;
That last line doesn't work because formElements[groupName] is "undefined."
formElements['$survey[3][1]'] works just fine, but that hardcodes the element's name, and I'd need to repeat the code for each question, and worse, it's a variable number of questions.
As I was typing, the Similar Questions sidebar suggested I read Why aren't variable names converted to strings when using bracket notation in javascript?, so now I that's just how it is in Javascript.
But then what workaround would you suggest? I could just forget about validating with Javascript since I also validate the form with PHP, but I understand it's good practice to validate forms at both the client and server sides. Thanks for your help!
You have an extra set of single quotes that you shouldn't here:
groupName = "'$survey[" + groupNdx + "][1]'";
That adds single quotes into the key itself. Change that to:
groupName = "$survey[" + groupNdx + "][1]";
Notice that x["'key'"] is a different from x['key'] in Javascript. The first has a key of 'key' (including the quotes) while the second has just the string: key

Generic method to display error for a not null input box

Desired Result
I'm attempting to create a generic method in Javascript (JQUERY) which checks the page for any and every element whether it is nullable or not.
As a example I'm using a login.
Both the username and password are not nullable. In my head I think it may be possible to have a error label, which is standard hidden, with a for='<inputbox name here>'. Then I can loop through all labels which have the class that shows that the label belongs to a input.
Example
<label for="i_1_s_1">Name: </label>
<input type="text" name="i_1_s_1">
<label class="notnullerror" for="i_1_s_1">hidden</label>
<label for="i_1_s_2">Password: </label>
<input type="text" name="i_1_s_2">
<label class="notnullerror" for="i_1_s_2">hidden</label>
Problem
I'm unaware what the best practice is for this. Basicly what I want is a
foreach (var element = document.getElementsByClass('notnullerror')
{
document.getElementsByName(element.for.value);
}
However, this is done in javascript and not jquery and ofcourse, this will not work. How can I manage to make this the way I want?
And, if this is not best practice for showing a error message on a not nullable input, please comment on what is.
This will work: it finds all notnullerror elements and gets the element that corresponds to the for attribute for each of them.
$(function() {
$('.notnullerror').each(function() {
var forEl= $('input[name="' + $(this).attr('for') + '"]');
//do something here
});
});
It is more common to validate form controls when the form is submitted, rather than running individual tests. You can loop over the controls and validate each based on an attribute value, e.g. if it has a class of notnullerror, test it and display an appropriate error message if necessary.
e.g. (assuming you have a hasClassName function or similar):
var element, elements = form.elements;
for (var i=0, iLen=elements.length; i<iLen; i++) {
element = elements[i];
if (hasClassName(element, 'notnullerror') && element.value == '') {
// deal with error
}
// perform other validation tests
}
Incidentally, the value of a form control is always a string, and therefore can never be == or === to null, though it might be equal to the string "null".

Categories

Resources