Get Value for element - if fail get InnerHTML - javascript

Basically I'm creating a chrome extension that can pull data from a webpage to speed up data entry. I'm trying to make this as easy for the users as possible, which is causing me some headache myself. I'm allowing them to put an id or a name for a field to lookup, and on my end, I have to determine if it's an input, or just text they're wanting pulled and see if the element exists with the id, and if not, check for an element with their provided value as a name. This has to be done with multiple fields that they provide.
I've tried a few iterations of code to do this. Currently I'm stuck on trying to get this code below to do the trick, but obviously it isn't working. Is there a better way to accomplish this via javascript only?
var msg = {
"first": "first_name_id_name",
"last": "last_name_id_name",
"email": "email_id_name",
"phone": "phone_id_name"
}
var fields_to_find = JSON.parse(msg);
var data_to_push = {};
var current;
var ele;
for (var key in fields_to_find) {
if (fields_to_find.hasOwnProperty(key)) {
console.log(fields_to_find[key]);
ele = document.getElementById(fields_to_find[key]);
if (!ele.value) {
ele = document.getElementById(fields_to_find[key]);
if (ele.innerHTML.length == 0) {
ele = document.getElementsByName(fields_to_find[key]);
if (!ele.value) {
ele = document.getElementsByName(fields_to_find[key]);
if (ele.innerHTML.length == 0) {
current = "";
} else {
current = ele.innerHTML;
}
} else {
current = ele.value;
}
} else {
current = ele.innerHTML;
}
} else {
current = ele.value;
}
data_to_push[key] = current;
}
}
console.log(data_to_push);
<input type="text" id="first_name_id_name" value="John">
<p name="last_name_id_name">Doe</p>
<input type="text" name="email_id_name" value="johndoe#example.com">
<p id="phone_id_name">123-555-1234</p>
Any help you can provide would be awesome and much appreciated.
Thanks for your time!

You could strip off a lot of the superfluous nested if statements with a couple backup values like below. Also, because JSON is a native object in JS, you don't have to do a JSON.parse on your msg object.
var msg = {
first: "first_name_id_name",
last: "last_name_id_name",
email: "email_id_name",
phone: "phone_id_name"
};
var data_to_push = {};
var current;
var ele;
for (var key in msg) {
if (msg.hasOwnProperty(key)) {
console.log(msg[key]);
ele = document.getElementById(msg[key]) || document.getElementsByName(msg[key])[0];
if (ele) {
current = ele.value || ele.innerHTML || '';
} else {
current = '';
}
data_to_push[key] = current;
}
}
console.log(data_to_push);
<input type="text" id="first_name_id_name" value="John">
<p name="last_name_id_name">Doe</p>
<input type="text" name="email_id_name" value="johndoe#example.com">
<p id="phone_id_name">123-555-1234</p>

1 : Use ' for msg variable.
2 : You do not need a lot of conditions.
There are a lot of Incorrect codes, to see all the changes check full code :
var msg = '{ "first": "first_name_id_name","last": "last_name_id_name","email": "email_id_name", "phone": "phone_id_name"}' ;
var fields_to_find = JSON.parse( msg ),
data_to_push = {},
current ,
ele ;
for ( var key in fields_to_find ) {
if ( fields_to_find.hasOwnProperty ( key ) ) {
console.log( fields_to_find[key] );
ele = document.getElementById( fields_to_find[key] ) ? document.getElementById( fields_to_find[key] ) : document.getElementsByName( fields_to_find[key] )[0];
if ( ele ) { data_to_push[key] = ( ele.innerHTML ) ? ele.innerHTML : ( ele.value ? ele.value : '' ) ; }
}
}
console.log(data_to_push);
<input type="text" id="first_name_id_name" value="John">
<p name="last_name_id_name">Doe</p>
<input type="text" name="email_id_name" value="johndoe#example.com">
<p id="phone_id_name">123-555-1234</p>

Related

Button adding user input to the array. Then typing out the data in array to a <div>

I'm fairly new to coding so please ignore any unwritten rules I might be missing.
Any feedback is appreciated.
Basically, I have three text inputs, Name:, Age:, and Password:
If not all fields are filled and error message will occur, but if everything is filled in and the user presses the button I need the information to be saved to an array, and for the information (only Name: & Age:) to be typed out below, along with two other "personas" that are to be added via (Push) method.
However, I'm not getting these different stages to work together. I am receiving different errors each time I change something. As previously stated I am a novice within coding and will take any help I can get.
function buttonclick() {
validate();
addToArray();
}
function validate() {
var name = document.getElementById("NameInput");
var age = document.getElementById("AgeInput");
var password = document.getElementById("PasswordInput");
if (name.value == "" || password.value == "" || age.value == "") {
alert("Field is required");
return false;
} else {
true;
}
if (password.value == "IHM") {
true;
} else {
alert("Not a valid password")
return false;
}
}
function addToArray() {
let persons = [];
let person1 = {
Uname: "Marcus",
Uage: 34
}
let person2 = {
Uname: "Cihan",
Uage: 35
}
// Gets name from the input
let Uname = document.getElementById("NameInput").value;
// Gets age from the input
let Uage = document.getElementById("AgeInput").value;
// Adds antoher name to the array?
persons.push(person1, person2);
// Sorts the array
persons.sort();
/* Is this needed?
const write = () => {
NameInput.forEach()
AgeInput.forEach()
}*
<div>
<input type="text" placeholder="Name" id="NameInput">
</div>
<div>
<input type="number" placeholder="Age" id="AgeInput">
</div>
<div>
<input type="password" placeholder="Password" id="PasswordInput">
</div>
<button onclick="buttonclick()" type="button">Submit</button>
<div id="output"></div>
I see your code in the vsCode, and your array gets the two objects if you check in the console, I add an object of user name and age- from inputs. I hope that im understand.. that my code:
enter code here function buttonclick() {
validate(addToArray);
}
var uname = document.getElementById("NameInput");
var age = document.getElementById("AgeInput");
function validate(cb) {
var password = document.getElementById("PasswordInput");
if (name.value == "" || password.value == "" || age.value == "") {
alert("Field is required");
return false;
} else {
true;
}
if (password.value == "IHM") {
true;
} else {
alert("Not a valid password")
return false;
}
cb();
}
function addToArray() {
let persons = [];
let person1 = {
Uname: "Marcus",
Uage: 34
}
let person2 = {
Uname: "Cihan",
Uage: 35
}
// Gets name from the input
let objOfUserInputs = {};
objOfUserInputs.uname = uname.value;
objOfUserInputs.uage = age.value;
// Gets age from the input
let Uage = document.getElementById("AgeInput").value;
// Adds antoher name to the array?
persons.push(person1, person2, objOfUserInputs);
// Sorts the array
persons.sort();
console.log(persons);
}
First step: You don't need to write true in the conditionals, you could just return if you don't need to check the returned value
eg.:
For the first conditional, you don't even need the else part
if (name.value == "" || password.value == "" || age.value == "") {
alert("Field is required");
return
}
For the second conditional
if (password.value == "IHM"){
return true
} else {
alert ('Wrong password')
}
You could even write it like this, since if the condition is met, the function will return and the alert won't trigger
if (password.value == "IHM"){
return true
}
alert ('Wrong password')
Try it out.
Then you want to append those values to the array (if i understood correctly) and you want them to be displayed, alongside with the others.
I suggest you create a similar object and then push that object to the array, then you can sort it
So, create the object from the user input:
let Uname = document.getElementById("NameInput").value;
let Uage = parseInt(document.getElementById("AgeInput").value);
//You need to use parseInt() if you want that item to be an integer
let person3 = {
Uname: Uname,
Uage: Uage
}
And then push every object to the array
persons.push(person1, person2, person3);
//return the array
return persons
to sort the array, by name i imagine, just using sort would not suffice, as you want to sort on the 'name' property, so you have to pass a function to sort that orders the items by their name.
You can check it here: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/sort
persons.sort(function (a, b) {
var nameA = a.name.toUpperCase(); // ignore upper and lowercase
var nameB = b.name.toUpperCase(); // ignore upper and lowercase
if (nameA < nameB) {
return -1;
}
if (nameA > nameB) {
return 1;
}
// names must be equal
return 0;
});
The last step, if i understand correctly, is placing all the items, in the ordered array, inside the output div, so let's keep the write() function.
You have to iterate through each element, and then you need to insert the HTML that you have created inside the 'output' div.
There are a few ways to to this, you can create elements in the js, or you can append the HTML directly to the div.
Let's say you want to place them in an unordered list.
//pass the result from the addToArray() funtion to the write() function
function write(persons){
let output = document.getElementById('output')
//clean output div otherwise everytime it will append new content
output.innerHTML = ""
let ul = document.createElement('ul')
//Iterate
for( let i of persons){
let li = document.createElement('li')
li.innerHTML = `${i.Uname} - ${i.Uage}`
ul.appendChild(li)
}
output.appendChild(ul)
}
and finally the onclick function, you need to make sure that everything is as you want before adding it to the output div, so check if the verify function has returned true(or whatever you prefer), and the create the array and write it to the div
function buttonclick() {
if (validate() === true){
write(addToArray())
}
}
here is it in full
<body>
<div>
<input type="text" placeholder="Name" id="NameInput">
</div>
<div>
<input type="number" placeholder="Age" id="AgeInput">
</div>
<div>
<input type="password" placeholder="Password" id="PasswordInput">
</div>
<button onclick="buttonclick()" type ="button">Submit</button>
<div id="output"></div>
<script>
function buttonclick() {
if (validate() === true){
write(addToArray())
}
}
function validate() {
var name = document.getElementById("NameInput");
var age = document.getElementById("AgeInput");
var password = document.getElementById("PasswordInput");
if (name.value == "" || password.value == "" || age.value == "") {
alert("Field is required");
return
}
if (password.value == "IHM") {
return true
}
alert("Not a valid password")
}
function addToArray() {
let persons = [];
let person1 = {
Uname: "Marcus",
Uage: 34
}
let person2 = {
Uname: "Cihan",
Uage: 35
}
// Gets name from the input
let Uname = document.getElementById("NameInput").value;
// Gets age from the input
let Uage = parseInt(document.getElementById("AgeInput").value);
//Create the object
let person3 = {
Uname: Uname,
Uage: Uage
}
// Adds antoher name to the array?
persons.push(person1, person2, person3);
// Sorts the array
persons.sort(function (a, b) {
var nameA = a.Uname.toUpperCase(); // ignore upper and lowercase
var nameB = b.Uname.toUpperCase(); // ignore upper and lowercase
if (nameA < nameB) {
return -1;
}
if (nameA > nameB) {
return 1;
}
// names must be equal
return 0;
});
return persons
}
function write(persons) {
let output = document.getElementById('output')
//clean output div otherwise everytime it will append new content
output.innerHTML = ""
let ul = document.createElement('ul')
//Iterate
for (let i of persons) {
let li = document.createElement('li')
li.innerHTML = `${i.Uname} - ${i.Uage}`
//Append items to ul
ul.appendChild(li)
}
//Append ul to the 'output' div
output.appendChild(ul)
}
</script>
</body>
There are many ways you can accomplish this, i have tried to stay as close as possible to your example so you can understand better, i hope it'll help you, have a good day.

How to compare 2 text input values?

I'm trying to create a simple game where you have to answer the correct answer from a calculation.
I already have the function to generate random calculations, but i don't know how to compare it with the result which the user writted.
I tried to make the if, so when the user press the submit button, then the app will try to determine if that's the correct answer.
var numArray = ["10/2", "5x5", "12-22", "5-6", "20-70"];
var question = document.getElementById("textQuestion");
var answer = document.getElementById("textAnswer");
function rollDice() {
document.form[0].textQuestion.value = numArray[Math.floor(Math.random() * numArray.length)];
}
function equal() {
var dif = document.forms[0].textQuestion.value
if (dif != document.forms[0].textAnswer.value) {
life--;
}
}
<form>
<input type="textview" id="textQuestion">
<br>
<textarea id="textAnswer" form="post" placeholder="Answer"></textarea>
</form>
<input type="button" name="start" onclick="">
document.forms[0].textQuestion.value looking for an element with name=textQuestion, which doesn't exist. Use getElementById instead or add name attribute (needed to work with the input value on server-side).
function equal() {
if (document.getElementById('textQuestion').value != document.getElementById('textAnswer').value) {
life--; // life is undefined
}
}
// don't forget to call `equal` and other functions.
This is probably what you're looking for. I simply alert(true || false ) based on match between the random and the user input. Check the Snippet for functionality and comment accordingly.
var numArray = ["10/2", "5x5", "12-22", "5-6", "20-70"];
var questionElement = document.getElementById("textQuestion");
var answerElement = document.getElementById("textAnswer");
function rollDice() {
var question = numArray[Math.floor(Math.random() * numArray.length)];
questionElement.setAttribute("value", question);
}
//rolldice() so that the user can see the question to answer
rollDice();
function equal()
{
var dif = eval(questionElement.value); //get the random equation and evaluate the answer before comparing
var answer = Number(answerElement.value); //get the answer from unser input
var result = false; //set match to false initially
if(dif === answer){
result = true; //if match confirmed return true
}
//alert the match result
alert(result);
}
document.getElementById("start").addEventListener
(
"click",
function()
{
equal();
}
);
<input type="textview" id="textQuestion" value="">
<br>
<textarea id="textAnswer" form="post" placeholder="Answer"></textarea>
<input type="button" id="start" value="Start">
There's more I would fix and add for what you're trying to achieve.
First of you need a QA mechanism to store both the question and the correct answer. An object literal seems perfect for that case: {q: "", a:""}.
You need to store the current dice number, so you can reuse it when needed (see qa_curr variable)
Than you could check the user trimmed answer equals the QA.a
Example:
let life = 10,
qa_curr = 0;
const EL = sel => document.querySelector(sel),
el_question = EL("#question"),
el_answer = EL("#answer"),
el_check = EL("#check"),
el_lives = EL("#lives"),
qa = [{
q: "Calculate 10 / 2", // Question
a: "5", // Answer
}, {
q: "What's the result of 5 x 5",
a: "25"
}, {
q: "5 - 6",
a: "-1"
}, {
q: "Subtract 20 from 70",
a: "-50"
}];
function rollDice() {
qa_curr = ~~(Math.random() * qa.length);
el_question.textContent = qa[qa_curr].q;
el_lives.textContent = life;
}
function checkAnswer() {
const resp = el_answer.value.trim(),
is_equal = qa[qa_curr].a === el_answer.value;
let msg = "";
if (resp === '') return alert('Enter your answer!');
if (is_equal) {
msg += `CORRECT! ${qa[qa_curr].q} equals ${resp}`;
rollDice();
} else {
msg += `NOT CORRECT! ${qa[qa_curr].q} does not equals ${resp}`;
life--;
}
if (life) {
msg += `\nLives: ${life}`
} else {
msg += `\nGAME OVER. No more lifes left!`
}
// Show result msg
el_answer.value = '';
alert(msg);
}
el_check.addEventListener('click', checkAnswer);
// Start game
rollDice();
<span id="question"></span><br>
<input id="answer" placeholder="Your answer">
<input id="check" type="button" value="Check"> (Lives:<span id="lives"></span>)
The above still misses a logic to not repeat questions, at least not insequence :) but hopefully this will give you a good start.

Can I select a multi-dimensional HTML array in JavaScript as a multi-dimensional array?

If I have the following HTML on a page:
<input type="hidden" name=item[0][id]>
<input type="text" name=item[0][title]>
<input type="text" name=item[0][description]>
<input type="hidden" name=item[1][id]>
<input type="text" name=item[1][title]>
<input type="text" name=item[1][description]>
<input type="hidden" name=item[2][id]>
<input type="text" name=item[2][title]>
<input type="text" name=item[2][description]>
I would like to select the items using JavaScript (or JQuery) in such a way that I can loop over the items using the outer array.
Currently I have the following JQuery/JavaScript to handle the items:
var items = ($('[name*="item["]'));
var i = 0;
while (i < items.length) {
if (items[i++].value === '') {
// No ID set.
}
else if (items[i++].value === '') {
// No title set.
}
else if (items[i++].value === '') {
// No description set.
}
}
Is there a way to select the elements so that I can loop over them using notation more like the following (Where items.length is 3)?
for (var i = 0; i < items.length; i++) {
if (items[i][0].value === '') {
// No ID set.
}
else if (items[i][1].value === '') {
// No title set.
}
else if (items[i][2].value === '') {
// No description set.
}
}
Or even more like this?
for (var i = 0; i < items.length; i++) {
if (items[i].id.value === '') {
// No ID set.
}
else if (items[i].title.value === '') {
// No title set.
}
else if (items[i].description.value === '') {
// No description set.
}
}
Or would this require more manipulation and processing to go from selecting from the DOM to creating the data structure to loop over?
I think this is exactly what you are looking for (which is not really related to selectors):
function serialize () {
var serialized = {};
$("[name]").each(function () {
var name = $(this).attr('name');
var value = $(this).val();
var nameBits = name.split('[');
var previousRef = serialized;
for(var i = 0, l = nameBits.length; i < l; i++) {
var nameBit = nameBits[i].replace(']', '');
if(!previousRef[nameBit]) {
previousRef[nameBit] = {};
}
if(i != nameBits.length - 1) {
previousRef = previousRef[nameBit];
} else if(i == nameBits.length - 1) {
previousRef[nameBit] = value;
}
}
});
return serialized;
}
console.log(serialize());
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="hidden" name=item[0][id]>
<input type="text" name=item[0][title]>
<input type="text" name=item[0][description]>
<input type="hidden" name=item[1][id]>
<input type="text" name=item[1][title]>
<input type="text" name=item[1][description]>
<input type="hidden" name=item[2][id]>
<input type="text" name=item[2][title]>
<input type="text" name=item[2][description]>
See the related JSFiddle sample.
Here's a way to add a custom function into JQuery to get the data structure you're looking for.
$.fn.getMultiArray = function() {
var $items = [];
var index = 0;
$(this).each(function() {
var $this = $(this);
if ($this.attr('name').indexOf('item[' + index + ']') !== 0)
index++;
if (!$items[index])
$items[index] = {};
var key = $this.attr('name').replace('item[' + index + '][', '').replace(']', '');
$items[index][key] = $this;
});
return $items;
};
var $items = $('input[name^="item["]').getMultiArray();
This allows you to have the references in your "ideal" example.
var $items = $('input[name^="item["]').getMultiArray();
$items[0].id;
JS Fiddle: https://jsfiddle.net/apphffus/

Check if Number entered is correct By ID - JavaScript

Would like to know how to check true and false and in return give error message if checked and the number is incorrect..
<input name="student1" type="text" size="1" id="studentgrade1"/>
<input name="student2" type="text" size="1" id="studentgrade2"/>
<input name="student3" type="text" size="1" id="studentgrade3"/>
so here we have 3 inputbox , now i would like to check the result by entering number into those inputbox.
studentgrade1 = 78
studentgrade2 = 49
studentgrade3 = 90
<< Using JavaScript >>
So If User entered wrong number e.g "4" into inputbox of (studentgrade1) display error..
same for otherinputbox and if entered correct number display message and says.. correct.
http://jsfiddle.net/JxfcH/5/
OK your question is kinda unclear but i am assuming u want to show error
if the input to the text-box is not equal to some prerequisite value.
here is the modified checkGrade function
function checkgrade() {
var stud1 = document.getElementById("studentgrade1");
VAR errText = "";
if (stud1.exists() && (parseInt(stud1.value) == 78){return true;}
else{errText += "stud1 error";}
//do similiar processing for stud2 and stud 3.
alert(errText);
}
See demo →
I think this is what you're looking for, though I would recommend delimiting your "answer sheet" variable with commas and then using split(',') to make the array:
// answers
var result ="756789";
// turn result into array
var aResult = [];
for (var i = 0, il = result.length; i < il; i+=2) {
aResult.push(result[i]+result[i+1]);
}
function checkgrade() {
var tInput,
msg = '';
for (var i = 0, il = aResult.length; i < il; i++) {
tInput = document.getElementById('studentgrade'+(i+1));
msg += 'Grade ' + (i+1) + ' ' +
(tInput && tInput.value == aResult[i] ? '' : 'in') +
'correct!<br>';
}
document.getElementById('messageDiv').innerHTML = msg;
}
See demo →
Try this http://jsfiddle.net/JxfcH/11/
function checkgrade() {
var stud1 = document.getElementById("studentgrade1");
var stud2 = document.getElementById("studentgrade2");
var stud3 = document.getElementById("studentgrade3");
if (((parseInt(stud1.value) == 78)) && ((parseInt(stud2.value) == 49)) && ((parseInt(stud3.value) == 90)))
{
alert("correct");
}
else
{
alert("error correct those values");
}
}

Basic javascript loop/validation question

So im trying to perform a basic validation to check if a field is empty. I want to do it in a loop..
<input type="text" size="25" name="q170_Name" class="text" value="" id="q170" maxlength="100" maxsize="100" />
function validateMe() {
var dropdowns = ["q170","q172","q173","q174","q175","q176","q177"];
var totalz = (dropdowns.length);
//loop through the array
for ( var i in dropdowns ) {
if (document.getElementById(dropdowns[i]) == "") {
alert('missed one!');
}}}
I appreciate the help
if (document.getElementById(dropdowns[i]).value == "") {
alert('missed one!');
--edit
but probably there is a better way to do this:
for (var i = 0; i < document.myFormName.length; ++i) {
if( document.myFormName.elements[i].type == "text" &&
document.myFormName.elements[i].value == "") {
alert('missed one!');
}
}
I recommend you to do a simple for loop since for..in is meant to iterate over object properties, also note that you need to check the value attribute of the fields:
function validateMe() {
var dropdowns = ["q170","q172","q173","q174","q175","q176","q177"],
totalz = dropdowns.length,
i;
for (i = 0; i < totalz; i++) {
if (document.getElementById(dropdowns[i]).value == "") {
alert('Check the value of ' + dropdowns[i]);
}
}
}

Categories