Alert showing when it shouldnt be (XML Parse) - javascript

<script>
async function loadData() {
var data = await fetch("Product.xml");
var parsedData = await data.text();
var parser = new DOMParser();
var Product_document = parser.parseFromString(parsedData,"text/xml");
var results = "";
var AlertBox = ""
var user_id_input = document.getElementById("user_id").value;
var todos = Product_document.getElementsByTagName("product");
for(var i = 0; i < todos.length; i++) {
var Name = todos[i].getElementsByTagName("Name")[0].childNodes[0].nodeValue;
var Code = todos[i].getElementsByTagName("Code")[0].childNodes[0].nodeValue;
var Quantity = todos[i].getElementsByTagName("Quantity")[0].childNodes[0].nodeValue;
var Description = todos[i].getElementsByTagName("Description")[0].childNodes[0].nodeValue;
var Price = todos[i].getElementsByTagName("Price")[0].childNodes[0].nodeValue;
if(user_id_input === Code) {
results = "<div>"
+ "Code: " + Code
+ ",<br/> Name: " + Name
+ ", <br/>Quantity: " + Quantity
+ ",<br/> Description " + Description
+ ",<br/> Price " + Price
+ "</div><br/>";
AlertBox= "True";
}
if(AlertBox !== "True") {
alert("Error");
}
}
document.getElementById("results").innerHTML = results;
}
</script>
I'm trying to code a web app that takes user input, parses an XML file and then displays some information. I have that part working.
My problem is, I want there to be an Error alert if the Input does not match any of the XML elements. I have coded one in, but for every element the app checks that doesn't match the user input the app is giving me an error alert. And I have no idea how to solve it.
enter image description here
I've tried adding a variable that changes to true if the input matches and only allowing the alert to show up if that variable is false and I still get the Alert.
enter image description here

Based on your code I think the reason why it is not working is the nodeValue property as this returns null.
When called on an element tag (nodeType 1) nodeValue returns null. nodeValue will return the actual text content when it is called from a text element (nodeType 3). The 'Code' tag is of type element and has a child of type text therefore you don't get the desired text value. You can read more on nodeType here.
To get the correct result from nodeValue you need to call it like this:
var Name = todos[i].getElementsByTagName("Name")[0].childNodes[0].firstChild.nodeValue;.
As you want to get the text content from an element you can also use the following code instead:
var Name = todos[i].getElementsByTagName("Name")[0].childNodes[0].textContent;
The if condition should now also be executed correctly as long as the user_id_input variable has also the correct value. If the function loadData is executed before the user has entered values into the form fields, you need to execute the function when your form has been submitted. This way you can make sure that the user has entered values to all required fields. You can read more about HTML Forms and managing them via JavaScript here if needed.
I would also suggest to use let and const instead of var.
Additionally I think you would like to use your variable AlertBox as a boolean. If that is the case please use the boolean datatype in JavaScript. You can write it like this:
let AlertBox = false; or let AlertBox = true;

Related

Take variable values and put them in another file

I'm coding the game blockly, I have a variable called lineCount which counts the number of line breaks. however this variable is in a file called lib-dialog.js. When I insert the value of this variable with innerHTML I can get the value of lines by creating a div in the soy.js file (File by which I need to treat the result) But I need this value in a variable to put an if(lines == 6) { }
// Add the user's code.
if (BlocklyGames.workspace) {
var linesText = document.getElementById('dialogLinesText');
linesText.textContent = '';
// Line produces warning when compiling Puzzle since there is no JavaScript
// generator. But this function is never called in Puzzle, so no matter.
var code = Blockly.JavaScript.workspaceToCode(BlocklyGames.workspace);
code = BlocklyInterface.stripCode(code);
var noComments = code.replace(/\/\/[^\n]*/g, ''); // Inline comments.
noComments = noComments.replace(/\/\*.*\*\//g, ''); /* Block comments. */
noComments = noComments.replace(/[ \t]+\n/g, '\n'); // Trailing spaces.
noComments = noComments.replace(/\n+/g, '\n'); // Blank lines.
noComments = noComments.trim();
var lineCount = noComments.split('\n').length;
var pre = document.getElementById('containerCode');
pre.textContent = code;
if (typeof prettyPrintOne == 'function') {
code = pre.innerHTML;
code = prettyPrintOne(code, 'js');
pre.innerHTML = code;
}
if (lineCount == 1) {
var text = BlocklyGames.getMsg('Games_linesOfCode1');
} else {
var text = BlocklyGames.getMsg('Games_linesOfCode2')
.replace('%1', String(lineCount));
}
linesText.appendChild(document.createTextNode(text));
document.getElementById("contarBloco").innerHTML = lineCount;
var contandoBloco = lineCount;
}
I need to take the variable lineCount and put its value in another js.but I'm only managing to insert it into a div with innerHTML
it is better you use localstorage . Set the value of localcount in the local storage and get wherever you want
var lineCount = noComments.split('\n').length;
localStorage.setItem("lineCount", lineCount); // in first file
var count = localStorage.getItem("lineCount") // in second file
with this logic you will get the value but it will be string then for that you either use directly string or convert into integer using parseInt method
parseInt(count);
may be it will help . Thanks
I don't know if your Javascript files are modules, if so, you can return a function in your lib-dialog.js page and return it.
Example
lib-dialog.js =
let Dialog = (function() {
function SetLineCountVariable(LocalLineCount){
LineCount = LocalLineCount;
}
return SetLineCountVariable
})();
And in your soy.js file
let Soy = (function() {
Dialog.SetLineCountVariable(6);
})();
And do not forgot to call your JS file in order in your HTML page
Another way, if you only want the variable result in your another JS file, in your lib-dialog.js, show the result of LineCount in html tag and get it in your another JS file with document.getElementById

DocumentApp for Google Apps Script not returning all attributes of an element?

When I attempt to get attributes from an element using the getAttributes() method from the Google Apps Script DocumentApp library for a Google Doc, not all attributes show up; specifically the GLYPH_TYPE attribute for a listItem element.
Due to the lack of functionality within Google Docs for checklists, I'm writing a code script to automatically calculate the percent completion of a list based on the symbol present of each list item belonging to a list. In order to do this, I am retrieving all listItems relevant to a listID, and then attempting to check their GLYPH_TYPE attribute in order to differentiate which items have been completed (which the user indicates by clicking the symbol left of the list item and changing it to a checkmark). It is the latter that I am having issues with; when I call getAttributes() for either the Paragraph or the listItem object for the list item, GLYPH_TYPE isn't present at all.
Here's a method where I am simply trying to extract the GLYPH_TYPE attribute for a listItem;
function getGlyphTypeFromListItem(documentId){
var doc =
DocumentApp.openById("1mzVQUccSH_suf8KoTkbVN4XjIOcfbYDuie3GV_M1Fg8");
var body = doc.getBody();
Logger.log(body.getParagraphs()[0].getAttributes());
Logger.log(body.getParagraphs()
[0].findElement(DocumentApp.ElementType.LIST_ITEM).getElement()
.getAttributes());
}
When I run this method I get the responses:
[19-01-20 18:22:02:242 MST] {FONT_SIZE=11, ITALIC=true, HORIZONTAL_ALIGNMENT=null, INDENT_END=null, INDENT_START=144.0,LINE_SPACING=null, LINK_URL=null, UNDERLINE=true,
BACKGROUND_COLOR=null, INDENT_FIRST_LINE=126.0, LEFT_TO_RIGHT=true,
SPACING_BEFORE=null, HEADING=Normal, SPACING_AFTER=null,
STRIKETHROUGH=null, FOREGROUND_COLOR=null, BOLD=true,
FONT_FAMILY=Roboto Condensed}
[19-01-20 18:30:21:253 MST] {FONT_SIZE=11, ITALIC=true,
HORIZONTAL_ALIGNMENT=null, INDENT_END=null, INDENT_START=144.0,
LINE_SPACING=null, LINK_URL=null, UNDERLINE=true, BACKGROUND_COLOR=null,
INDENT_FIRST_LINE=126.0, LEFT_TO_RIGHT=true, SPACING_BEFORE=null,
HEADING=Normal, SPACING_AFTER=null, STRIKETHROUGH=null, FOREGROUND_COLOR=null,
BOLD=true, FONT_FAMILY=Roboto Condensed}
As you can see, GLYPH_TYPE is completely absent from both of the logs; is there something I'm missing? Also, have any of you found a more intuitive way to track the completion of "checklists" within Google Docs?
Thank you in advance!
Google documentation says that the "Paragraph" getAtributes method (doc) "retrieves the element's attributes. The result is an object containing a property for each valid element attribute where each property name corresponds to an item in the DocumentApp.Attribute enumeration." GLYPH_TYPE is recorded as one of the properties of "Enum Attribute".
I agree with the OP that the GLYPH TYPE is not reported when a paragraph is analysed.
However if the Paragraph Type = DocumentApp.ElementType.LIST_ITEM, then getAttributes does report the GLYPH_TYPE, as well as some additional data (Refer image below). It is difficult to say whether there is a bug in the Google code, or (perhaps) an error in the documentation.
So far as the OP code is concerned, I got the same results.
But it's interesting to note a ListItem is returned by getParagraphs but a ListItem is NOT a 'paragraph'. ("A Paragraph may contain Equation, Footnote, HorizontalRule, InlineDrawing, InlineImage, PageBreak, and Text elements." (docs)). The getParagraphs method "retrieves all the Paragraphs contained in the section (including ListItems)" (docs). It's an odd, almost contradictory result, but I think this may be a reason why the OP's code was unsuccessful.
This was my code (adapted from the OP).
function so54282539() {
var doc = DocumentApp.getActiveDocument();
var body = doc.getBody();
// variable to count the list#
var listcounter = 0;
// get the Paragraphs
var paras = doc.getParagraphs();
//Logger.log("DEBUG: paras = "+paras);//DEBUG
Logger.log("DEBUG:Number of paragraphs: " + paras.length); //DEBUG
// get the List Items
var lists = doc.getListItems();
//Logger.log("DEBUG: Lists: "+lists);//DEBUG
Logger.log("DEBUG: Number of lists: " + lists.length); //DEBUG
Logger.log(" "); //DEBUG
//Loop through the Paragraphs (i)
for (var i = 0; i < paras.length; i++) {
var mytypeof = paras[i].getType();
Logger.log("DEBUG: Paragraph#i=" + (i + 1) + ", Type: " + mytypeof); //DEBUG
// if thgis parapgraph is a list item, then get more information
if (mytypeof === DocumentApp.ElementType.LIST_ITEM) {
var paraattributes = paras[i].getAttributes();
// list the paragraph attributes
for (var key in paraattributes) {
if (paraattributes.hasOwnProperty(key)) {
Logger.log("Paragraph Attribute: " + key + " -> " + paraattributes[key]);
}
}
// List the GLPH TYPE
Logger.log("Glyph: " + lists[listcounter].getGlyphType());
var otherattributes = lists[listcounter].getAttributes();
// List the List_Item Attributes
for (var listkey in otherattributes) {
if (otherattributes.hasOwnProperty(listkey)) {
Logger.log("List_Item Attribute: " + listkey + " -> " + otherattributes[listkey]);
}
}
listcounter = listcounter + 1;
}
}
}
Typical Attribute comparison - Paragraph vs List_Item
List_Item Attributes
Document layout
I tried this:
function getGlyphType(){
var doc=DocumentApp.getActiveDocument();
var body=doc.getBody();
var children=body.getNumChildren();
var gA=[];
for(var i=0;i<children;i++){
var child=body.getChild(i);
if(child.getType()==DocumentApp.ElementType.LIST_ITEM){
gA.push(child.asListItem().getAttributes()['GLYPH_TYPE']);
}
var ui=HtmlService.createHtmlOutput(gA.join(', '));
DocumentApp.getUi().showModelessDialog(ui, 'Info')
}
}
I could get whether its a number or a bullet but I couldn't determine what type of bullet it was.

why is document.getElementsByName("name") is not returning any values?

I am creating an html element and assigning id and name values programmatically and later when i am trying to access those elements by name it is not returning any value
say for example i create a html input element and assign id = "Number_1" and name = "Name_1"
document.getElementsByName("Name_1").length is always 0
where as below code works and returns correct value
document.getElementById("Number_1" ).name = "Name_1"
why is this happening?
var count = 0;
for(var i =0;i<SomeValue;i++){
count++;
var cell = row.insertCell(i);
cell.className = "lineItemTable";
var inputElement = document.createElement("input");
inputElement.type = "text";
inputElement.id = "Number_"+count;
inputElement.name="Name_"+count;
cell.appendChild(inputElement);
}
In Internet Explorer, you can't add a "name" after creating the element:
var inputElement = document.createElement("<input name='Name_" + count + "'>");
You have to create it like that, providing the name as an attribute in the "html".
edit — OK this is rich.
At some point, Microsoft published this note in their "Compat Cookbook". Key point:
As of Windows Internet Explorer 9, the createElement triggers an "object not found" exception when you use angle brackets (< >).
That note contains a link to the documentation for the createElement method, which still insists that the "NAME" attribute can only be set by using the "eTag" text, as in my example above.
Thus it looks like what you need to do is something like this:
function makeInput( name ) {
try {
return document.createElement("<input name='" + name + "'>");
}
catch (x) {
var inp = document.createElement("input");
inp.name = name;
return inp;
}
}

Receiving the data from a form to a table which is already created

I tried to receive the data from a form to another using the following code it worked.
var fname = document.getElementsByName("fname")[0];
fname.value = getUrlVars()["fname"];
Now i want to receive the data from form to a table which is already created.
I used the code as
$("table").html("<tr><td>"+fname +"</td><td>"); its not working.
In this statement,
var fname = document.getElementsByName("fname");
fname.innerHTML = "fname";
What is the element with name "fname"?
If its a form element like textbox then it should be like,
var fname = document.getElementsByName("fname");
fname.value = "fname";
your code will only work if the element is not a form element like p or div, etc tags.
Edited Code:
I hope your second page is student.html and you have written the receiveData() in this page. Then you need to read the url and set the parameter value to the element. Like the one am writing below, provided your wrote the same name in form 2 as in form1,
var fname = document.getElementsByName("fname")[0];
fname.value = getUrlVars()["fname"];
2ndly yo can do this for textbox, but for the radio and dropdown you need to write som if-else statement.
Refer this http://papermashup.com/read-url-get-variables-withjavascript/
Hope you are getting what am willing to say.
Re-Edited Code:
Add this function with the receiveData() function.
function getUrlVars() {
var vars = {};
var parts = window.location.href.replace(/[?&]+([^=&]+)=([^&]*)/gi,
function(m,key,value) {
vars[key] = value;
});
return vars;
}
Code for Radio Button,
var sex = document.getElementsByName("sex");
sexValue = getUrlVars()["sex"];
for(i=0;i<sex.length;i++)
{
if(sex[i].value==sexValue)
{
sex[i].checked=true;
break;
}
}
Two issues with the code.
This is a useless statement, you need to save the result to some variable (not to mention Nmae):
document.getElementsByNmae("lname")
Should be:
var lname = document.getElementsByName("lname");
And then (setinnerHTML -> innerHTML):
lname.innerHTML="lname";
Use docs not your own imagination:
var newEl = document.getElementById("newElDay");
newEl.innerHTML = document.getElementById("oldElDay").innerHTML;
Apart from other problems which people have mentioned, perhaps you are missing this as the last line of your Javascript code inside Receivedata() :
document.getElementById('myform').submit();

function to change argument to another sign

I dynamically create this list element and information a user has typed in shows up in it when a button is clicked 'info' is text and shuld show as it is but 'grade' is a number that i want to convert to another sign with the function changeNumber() but I am new to javascript and cant figure out how to make this function, can anyone give a suggestion or point me in the right direction?
var list = $("#filmlista");
var list_array = new Array();
function updateFilmList()
{
document.getElementById("name").value = '';
document.getElementById("star").value = 0;
var listan = list_array[0][0];
var grade = list_array[0][1];
var element = '<li class="lista">' + list + '<span class="grade">'+ changeNumber(grade) +'</span></li>';
list.append(element);
}
should I use innerHTML? not shure I understand how it works? and how do I use the replace method if I have to replace many different numbers to the amount of signs the number is?
for example if the number is 5 it should show up as: *****, if number is 3 show up as: *** and so on
Here's some code that should do the trick:
Add this function into your script.
function changeNumber(number) {
var finalProduct = "";
for (var i = 0; i < number; i++) {
finalProduct += "*";
}
return finalProduct;
}
Replace the updateFilmsList with this code.
document.getElementById("name").value = '';
document.getElementById("star").value = 0;
var listan = list_array[0][0];
var grade = changeNumber(list_array[0][1]);
var element = '<li class="lista">' + list + '<span class="grade">'+ grade +'</span></li>';
list.append(element);
It looks like you're trying to do something like PHP's str_repeat. In that case, take a look at str_repeat from PHPJS
There are options other than a loop:
function charString(n, c) {
n = n? ++n : 0;
return new Array(n).join(c);
}
charString(3, '*'); // ***
You can use innerHTML to set the text content of an element provided none of the text might be mistaken for markup. Otherwise, set the textContent (W3C compliant) or innerText (IE proprietary but widely implemented) property as appropriate.

Categories

Resources