Building an xml string with the form elements in javascript - javascript

I'm working in building an xml string with the element values in a HTML form with java script. I'm able to get all the values of the form and build an xml easily with the below code. But the problem is there are a few repeating groups which makes the process hard. Means that, the repeating groups are FIELD SETS and for example if there is a field set named xxxRepeatingGroup and yyyRepeatingGroup, the xml should be as follows.
<xxxRepeatingGroup>
<xxx>
all the element values inside the field set with the name of the element as tag name and the value in between the tags here
</xxx>
<xxx>
all the element values inside the next field set(the repeating thing with different values) here
</xxx>
</xxxRepeatingGroup>
<yyyRepeatingGroup>
<yyy>
all the element values inside the field set with the name of the element as tag name and the value in between the tags here
</yyy>
<yyy>
all the element values inside the next field set(the repeating thing with different values) here
</yyy>
</yyyRepeatingGroup>
I'm not able to find a logic to add the <xxxRepeatingGroup>, <yyyRepeatingGroup>, <xxx> and <yyy> tags and I will not be able to hard code these tags as I need to use the same method in all the places.
Below is my java script function:
function getElementnames() {
var msg = "";
for (j=0;j < document.forms.mf.elements.length;j++) {
if (document.forms.mf.elements[j].type != 'button' && document.forms.mf.elements[j].type != 'submit' && document.forms.mf.elements[j].type == undefined )
{
msg += startElement(document.forms.mf.elements[j].name ) + document.forms.mf.elements[j].value + endElement(document.forms.mf.elements[j].name );
}
}
alert(msg);
}
function startElement(startname) {
var startname="<"+ startname +">";
return startname;
}
function endElement(endname) {
var endname ="</"+ endname +">";
return endname;
}
Please help...

I found out a way to do this by adding the element which I require as the tag name with type hidden and place it where ever I need the repeating group tags.

Related

Does it make sense to check properties separately or together?

This question stems from a previous question that I asked. How do you access the for loop of the parent component within a child component which has the inputs?
I want to know is it possible to just check for validity from each property separately instead of together?
So here is the logic that I have for trying to just check for the title input field and then the url field.
onUrlUpdate($event) {
var exp = /\b((http|https):\/\/?)[^\s()<>]+(?:\([\w\d]+\)|([^[:punct:]\s]|\/?))/;
// completely overkill, but just used to demonstrate a point
var url = this.urls.find(_url => {
// we can see here that the $event.url is actually the same object as the urls[i] that was
// passed to the child. We do not lose the reference when it is passed to the child or back
// up to the parent.
return $event.url === _url
});
if (url.url.match(exp)) {
url[$event.prop] = $event.newValue;
console.log(`Updated URL's "${$event.prop}" property with the value "${$event.newValue}"`);
} else if(url.title === ''){
console.log('not valid text ');
}
}
The output I am getting is
not valid text
and this is every time I input any text both in the title and url fields. Is there a way for me to check just for the title field? and then use the regex for the url field? Or would I have to split both fields into separate div classes?
Here is the link to the example I am modifying https://stackblitz.com/edit/angular-empty-project-zoy4st?file=app%2Fparent.component.ts
To check for the props separately, all you need to do is add a condition in the update function based on $event.prop. If $event.prop is url, then you validate url, if is title you validate title.
That being said, there is a problem with your current validation. You are checking the value of the existing url object, and not the new value coming in. I have updated it here, it seems to work ok:
https://stackblitz.com/edit/angular-empty-project-tcdfup?file=app/parent.component.ts

Sharepoint Multiline Values on Load

I am trying to capture all of the fields of a SharePoint form using JavaScript during the initial load of the edit form. Somehow, only the first two multi-line fields are being captured properly. When I change the order of the fields this works. For example:
Field 1
Field 2
Field 3
Fields 1 & 2 are captured.
If I change the order they appear:
Field 2
Field 3
Field 1
Fields 2 & 3 are captured.
This doesn't appear to be affected by the code itself, but something to do with loading in SharePoint. But here is the code anyways:
$(window).load(function()
{
if(document.readyState === 'complete')
{
getFields();
getValues();
var myStatement = $("textarea[Title='Problem Statement']").closest("span").find("iframe[Title='Rich Text Editor']").contents().text();
var myScope = $("textarea[Title='Scope']").closest("span").find("iframe[Title='Rich Text Editor']").contents().text();
}
});
I am also using SPUtility to capture values and am having difficult getting support elsewhere.
SPUtility code:
scope = SPUtility.GetSPField('Scope');
scopeVal = scope.GetValue();
All of the fields are being captured per the above code in getFields() and getValues() called in the above code during window.load.
Any help or advice is appreciated.
Every field is embedded in a <td> that contains the following HTML comment:
<!-- FieldName="Field1"
FieldInternalName="Field1"
FieldType="SPFieldNote"
-->
While you can't explicitly query the DOM for this comment, you can query to get all the fields on the form and then loop through them, checking their innerHTML property to see if they contain the desired comment string.
By this means, you can determine the exact parent <td> element for any desired field. This allows you to be more precise than by using jQuery's .closest() function.
The other thing to keep in mind is that enhanced rich text, rich text, and plain text multiline fields are each rendered differently, and will thus require different query selector parameters to obtain their values.
The following example code gets the values of multiline fields with internal names of Field1, Field2, or Field3, and stores the values in an object.
var richTextFieldNames = ["Field1","Field2","Field3"];
var richTextFieldValues = {};
var fieldRows = document.querySelectorAll(".ms-formtable td.ms-formbody");
for(var i = 0, len = richTextFieldNames.length; i<len; i++){
currentFieldName = richTextFieldNames[i];
for(var j = 0, jlen = fieldRows.length; j<jlen; j++){
var currentRow = fieldRows[j];
if(currentRow.innerHTML.indexOf("FieldInternalName=\""+currentFieldName+"\"") > -1){
var element = currentRow.querySelector(".ms-rtestate-field[role=\"textbox\"]"); // enhanced rich text
if(!element){
var iframe = currentRow.querySelector("iframe[title=\"Rich Text Editor\"]");
if(iframe){
element = iframe.contentDocument.querySelector("body"); // rich text
}else{
element = currentRow.querySelector("textarea"); // plain text
}
}
richTextFieldValues[currentFieldName] = element.innerText ? element.innerText : element.textContent;
break;
}
}
}
The values can then be accessed as properties of the richTextFieldValues object by using array or dot notation, e.g. var myScope = richTextFieldValues["Scope"]; or richTextFieldValues.Scope; (assuming Scope is the internal name of a multi-line field).

JavaScript populating and clearing <input> textbox

I got 6 "textboxex" and an Array with them.
<input id="slot0" type="text" /> id from 0 to 5, also Array named "slotarray". I want arrray and textboxes to be bound slotarray[0] with input id="slot0" etc.
First i needed function that will find first empty field in array (no matter if corresponding textbox is empty - but should) and put there string (short string - shortcode like "abc" or "sp1").
This function also need to populate bound textbox with long string.
If slotarray[2] == 'abc' then with the same number in ID (here be id="slot2") need to contain long string like "Abrasive Brilliant Conexant".
Here what i got
click to populate
and then function
function populate(shortstring,longstring) {
for (var i=0; i<6; i++) {
if (slotarray[i] == '') {
slotarray[i] = shortsrting;
slotid = 'slot' + i;
document.getElementById(slotid).value = longstring;
break;
}
}
}
With clearing at the moment of creating: ( Array('','','','','','') ), and textbox .value=''; its working as it should.
But then i figured out that i need function to clear textbox and bound array field. Not all but one specific for one clic. So instead of 6 functions i start to wrote
clear this field
for each of textbox, with different numbers and ids ofcourse, and clearing function:
function clear(arrayid, slotid) {
slotarray[arrayid] = '';
document.getElementById(slotid).value = '';
}
But this function do not clearing textbox neither array. I see that textbox has text, and i know that array isn't cleared because first function works finding first empty object...
What am i doing wrong here? its definition of "empty"/"cleared" filed/textbox? maybe i need to use more complex conditions? maybe it is something else.
Maybe i don't need array (i can manage to get rid of short-codes) and just make functions work only on textboxes?
Ok - i prepared jsfiddle demo with this, but even populating don't work..
http://jsfiddle.net/BYt49/11/
You can't use the keyword clear because refers to the (deprecated) function document.clear; so try to change the name of your "clear" function.
Ok, whatever you have written is fine. Just change to way you call your javascript.
Here is jsfiddle: http://jsfiddle.net/BYt49/20/

How can I update the background color of a dynamic input control?

I'm successfully creating some dynamic input textboxes using the following javascript:
var type = "Textbox";
var foo = document.getElementById("fooBar");
for (i = 1; i <= totalQty; i = i + 1) {
var textbox = document.createElement("input");
//Assign different attributes to the element.
textbox.setAttribute("type", type + i);
//textbox.setAttribute("value", type + i);
textbox.setAttribute("name", type + i);
textbox.setAttribute("id", type + i);
textbox.setAttribute("style", "width:300px");
textbox.setAttribute("width", "300px");
//Append the element in page (in span).
var newline = document.createElement("br");
foo.appendChild(newline);
foo.appendChild(textbox);
}
Everything works fine with that. Once the user keys in data and clicks submit however, I need to go back and set the background-color of any textboxes with an error to red. I found some code to do the actual coloring:
textbox.style.backgroundColor = "#fa6767";
...and I know the exact name of the textbox with the error (i.e. "Textbox1", "Textbox2", "Textbox3", etc) but I'm not sure how to programatically assign this background color code to the specific textbox. I can't use something like this, since all code is dynamically generated:
errorTextbox = $("#Textbox1");
Any suggestions?
It looks like you're building a form validation script. Here's an easier way to do this:
1) Create an entry in your stlyesheet for your error class. Adding and removing a class requires fewer steps than assigning properties individually.
.error {
background-color: #ff0000;
}
2) Give all the textboxes you wish to validate a unique class name "valMe", for example.
3) Then loop through them during the validation step:
$('.valMe').each(function() {
$(this).removeClass('error');
if($(this).text=='') {
$(this).addClass('error');
}
})
By using "this" you refer to the current element, so you don't even need to know the ID of the element.
If you already know the name (in this case identical to the id) of the element, you can use jQuery to select the element by forming the selector using string concatenation. Assuming you have a variable that stores the name/id of the text box that has the error, then it's a relatively simple process:
var errorTextboxName = 'Textbox1';
$('#' + errorTextboxName).css('background-color', 'red');
I ended up going with the following:
document.getElementById('Textbox1'.style.backgroundColor = "#fa6767";
I originally didn't think I would be able to capture my "Textbox1" control in this fashion since when I viewed the html source code, there was no "Textbox1" due to the fact I dynamically created it.
Thanks.

getting selected values from an array of select box in to javascript

I have created dynamic select box using jquery. I have created the select box as an array name=Child[]. See my code
for(i=1;i<=val;i++){
var newParagraph = $('<dl class="thirty fl"><dt>Child '+i+'</dt> <dd><select name="child[]"><option value="">--select--</option><option value="1">1</option><option value="2">2</option><option value="3">3</option</select></dd></dl>');
$('#childDynamic').append(newParagraph);
}
In form validation section (in javascript), how I validate this select box? I don't know how to get the values from an array of select box using JavaScript
Anyone can help me?
Thanks in advance
(You don't actually have an array of select elements, given that html doesn't have arrays. But anyway...)
If you use the name attribute as the selector you can get a jQuery object containing the select elements:
$('#childDynamic select[name="child\\[\\]"]')
...which you can then process as you see fit.
Because square brackets have special meaning in jQuery selectors they need to be escaped with backslashes, and to include backslashes in a string literal they need to be escaped too.
Anyway, I don't know what kind of validation you want to apply, but if you wanted to loop through each select and check its value in some way you could do something like this:
var valid = true;
$('#childDynamic select[name="child\\[\\]"]').each(function() {
var val = $(this).val();
// example validation: make sure something other than the default
// blank value is selected
if (val === "") {
valid = false;
}
});
if (!valid) {
// do something
}

Categories

Resources