Wrap around javascript object to .Net usercontrol - javascript

I have a question i don't know how to start with...
We all know that DOM elements have their own events such as 'onChange'. Well a TextBox can fire onChange events and anyone can register to them.
I have a .NET usercontrol with 2 textboxes (country code + phone). The textboxes are validated using a .NET CustomValidator. I have server-side methods to handle the control such as 'Value' witch gives-me a unique string with cc+phone.
What about client side? ...
I would like to wrap around the 2 textboxes and the customvalidator in a "javascript control". I would love to create functions to work with my control as an unique entity.
What i would like to do was things like:
var x = document.getElementById('myControlId'); // where my control id was the wrap around
x.value("+351875647356); // witch will fill the two text boxes respectively.
Is this possible? What the way to follow?
Thank U All.

It's possible to do wnat you want by creating a javascript object ala a c#/vb.net 1class to represent your control. Your javascript instance would keep references to the individual elements and you would use custom methods to do the heavy lifting.
<script>
function MyUserControl (ccID, phoneID) {
// set references to elements
var _ccInput = document.getElementById(ccID);
var _phoneInput = document.getElementById(phoneID);
this.setValues = function (value) {
// TODO process your input here
// _ccInput.value = ... ;
// _phoneInput .value = ... ;
}
}
</script>
You could create a new instance of the object by generating the javascript from the server side.
string script = string.format("var myControl = new MyUserControl('{0}','{1}');",
ccTextbox.ClientID, phoneTextbox.ClientID);
ClientScript.RegisterStartupScript(this.GetType(), "uniqueKeyName", script, true);
after it's created on the client side, you can reference it from some javascript.
<script>
myControl.setValues("+351875647356");
</script>

Related

javascript how to insert new elements at different locations in page

I'm writing a chrome extension that will add helper text instructions/reminders to specific location in the "new order" form we use at work. I'm really new to coding (basically using this project as a way to learn). I've created something that works - but I'm convinced there's a more elegant solution that I just haven't been able to figure out.
var helpText = "this is the message"
var customAlert = makeAlert(helpText) //create html container for msg
function makerAlert(helpText){...} //createElem, add class/style, append children
I'm okay with that bit (above). But should i be storing information on each message in objects instead? why would/wouldn't i? what information would go in it?
function alertPlacer(customAlert){
var par = document.getElementsByClassName("class-name")[i];
var sib = par.childNodes[j];
par.insertBefore(customAlert, sib);
};
really struggling with this bit (above). I have actually made alertPlacer() functions for each message because i can't figure out how to create a function that will take different class name & index parameters. should i be breaking this up more? if i stored these bits of info in an object, would that be useful?
relevant info:
because the target locations are within a form, almost nothing has an "id" attribute. so i have to use getElementsByClassName & an index.
for each message, I know the target parent className & index and the child node index to "insert before".
i would like to stick with javascript-only solution.
functions can take multiple arguments:
function alertPlacer(customAlert,className,parIndex,childIndex){
var par = document.getElementsByClassName(className)[parIndex]; var sib = par.childNodes[childIndex];
par.insertBefore(customAlert, sib);
};
And you call your function like
alertPlacer(yourAlert,"class-name",6,9);

save subset of dom for later use preserve eventlisteners and values entered

Hello Guys is there any method I can save a part (subtree) of the DOM for later use?
What I want to achieve is the following:
I create a two forms with pure javascript.
form1 = document.createElement('form1');
input = document.createElement('input');
input.addEventListener(Listener);
form1.appendChild('input');
....
The forms are build the same way.
Somewhere I have a div in my page whereto I appendChild('form1');
Suppose I have also a button on my page. The button should switch between the forms. So when I push it I want to SAVE THE STATE OF form1 (I want to keep the eventlisteners attached and also the texts that the user entered in input fields) for example in a variable and remove(detach) after the form1 from the DOM and bind form2.
I know this could be solved with css and toggle the forms by making one hidden and the other visible but I'm in fact interested in saving the subtree of the DOM as a snapshot.
I hope you understand my question since English is not my native language.
Thanks in advance.
The button should switch between the forms. So when I push it I want
to SAVE THE STATE OF form1 (I want to keep the eventlisteners attached
and also the texts that the user entered in input fields)
The createElement creates an element and returns it as a reference which you store in a variable. Note that this is a live reference. You could take advantage of that in this use-case.
Caution: Do NOT use this on production. This is not recommended. Use simple UI/UX elements to show/hide parts of your page by way of
CSS and/or Javascript. The example below is solely to demonstrate the way things work.
Store the references to your forms in variables. Use appendChild to add those to your container. Overwrite innerHTML to remove the element from the container, and use appendChild again to swap with the other variable. All event handlers, and the input element states will be saved as-is, because of the variable being a reference.
Example: (Type different values in inputs to see state while switching.)
var forms = [],
btn = document.getElementById('btn'),
display = document.getElementById('display'),
result = document.getElementById('result'),
currentForm = 0;
;
start();
function start() {
btn.addEventListener('click', switcher);
forms[0] = createForm(0);
forms[1] = createForm(1);
display.appendChild(forms[0]);
}
function switcher() {
display.innerHTML = '';
if (currentForm === 0) {
display.appendChild(forms[++currentForm]);
} else {
display.appendChild(forms[--currentForm]);
}
}
function createForm(idx) {
var frm, inp, lbl;
frm = document.createElement('form');
inp = document.createElement('input');
inp.addEventListener('input', show);
lbl = document.createElement('label');
lbl.textContent = "Form # " + (idx + 1) + ": ";
frm.appendChild(lbl);
frm.appendChild(inp);
return frm;
}
function show(e) { result.textContent = e.target.value; }
<button id="btn">Switch</button>
<hr>
<div id="display"></div>
<hr>
<span>Keeping typing in the input above: </span><span id="result"></span>
As mentioned before, use document fragment for storing the fragments which you can refer later.
If I understand your question correctly, the Document.createDocumentFragment() is not too suitable in your case because you need to keep changes after the fragmented piece of document will be inserted into the renderer (into the "real" page's DOM)?
If so, then you could try to use experimental createHTMLDocument() and store it somewhere (in localStorage for example) what gives you the ability to synchronise both documents - your "real" one and it's copy.
But actually this question includes also avoiding superfluous repaint/reflow etc so it is a good moment to dive into documentation ;)

JavaScript: Detect form submission completion - Further

I tried to comment on the existing post, however I cannot until I have at least 50 'Reputation'.
The question I have is very much the same but my form submits to it's self. I wanted to use JavaScript to detect form data and display it if present, but inset a file if not.
The default action is to insert one of several 'Inserts'. Originally I had the form post to a separate ASP classic processor, but I want it all contained on the same ASP document.
In psudo, I want {If Form then Print Data Else Print 'Welcome' insert).
My psudo above is more VBScriptish, but it's a JavaScript function I want (If (Form.Data==True){Do Nothing}else{SetInset('Welcome.asp');)
I do hope that's a readable question. As I say, much the same question as above link. I'm just kinda trying to justify the question.
<body onload="goSec();AutoRun()">
function AutoRun(){
setAppDiv('AboutUs.asp', 'apDiv1');
}
function chkQryInsert() {
var z=document.location.search;
var zx=z.substr(1);
var params = {}, queries, temp, i, l;
// Split into key/value pairs
queries = zx.split("&");
// Convert the array of strings into an object
for ( i = 0, l = queries.length; i < l; i++ ) {
temp = queries[i].split('=');
params[temp[0]] = temp[1];
if (temp[0]=='Insert'){
setAppDiv(temp[1],'apDiv1');
}
else{
setAppDiv('AboutUs.asp', 'apDiv1');
}
}
}
Why not intercept the post using a button and process your answers before posting back to the server, makes more sense.
Just set the button's onClick event to the name of a JavaScript function. In the JavaScript function you can include a document.forms["myform"].submit();.
To take this a step further you could also include something like this to allow a level of Ajax like functionality, loading an ASP partial page into a particular div.
-- EDIT --
Also, consider best practice when you want to join different forms together - is it really worthwhile doing that? I always separate my mark-up and script from each other; it makes it immeasurably more readable.

CKEditor - grab content from editor to setup live total word count

I'm trying to access the live content from each instance of CKEditor so I can setup a total word count. Before using CKEditor I would get the textarea's content with .getElementById(), and then I would get the live word count by passing the textarea element into my Countable() function which appends an event listener to the area. Is there a way to grab the live content of a CKEditor instance? I know it's an iframe so I'm not sure if it's possible to grab the live content.
Code I used to use with simple textarea:
var area1 = document.getElementById('textarea1');
Countable.live(area1, function(counter1) {
jQuery("#word_count1").text(counter1.words);
a1_count = counter1.words;
total_count();
});
This depends a lot on your Countable function and it's requirements - it would have helped to seen it and to know it's requirements. You can get the contents of each CKEditor instance in a few different methods, this is one
var contentArray = [];
var i = 0;
for (var instance in CKEDITOR.instances) {
var tmpEditor = CKEDITOR.instances[instance];
contentArray[i] = tmpEditor.getData();
i++;
}
Now the contents are in the contentArray. But form your code it looks like Countable needs an element. I'm unsure as to what kind of element reference it can use, but something like this might get you further:
var editor = CKEDITOR.instances.editor1; // change "editor1" to suit your editor
var element = editor.editable().$; // Get a reference to the body of the instance
Countable.live(element, function(counter1) {
jQuery("#word_count1").text(counter1.words);
a1_count = counter1.words;
total_count();
});
Now of course this only supports one editor instance, but the two examples combined might do the trick. Hopefully you don't use inline instances (it needs some additional work but is doable). Also note that naturally these return the source, not the text.
Also not that you do not want to loop this very quickly, it is very cpu intensive. I recommend a slow loop combined with the the CKEditor change event and maybe some other events that trigger the update. Do not trigger on every change, rather set a timeout to buffer the update trigger (you don't want to do the update when the user is typing).

How do I get the current NotesDocument using Javascript?

In a Lotus Notes Project it's simple to access the current document automatically in the QueryOpen method for example, extracting it from NotesUIDocument, which is a parameter.
Sub Queryopen(Source As Notesuidocument, Mode As Integer, Isnewdoc As Variant, Continue As Variant)
//Here I get the document
Dim doc as NotesDocument
Set doc = Source.document
End Sub
How can I do the same, but working on the web, using Javascript? Not necessarily in the QueryOpen method, of course.
If you just want to access document fields, then it is an easy task to do:
var doc = document.forms[0];
var yourfield = doc.YourFieldName; // take care: fieldname is case sensitive
// to get a field- value;
var theValue = yourfield.value;
// to set a field value
yourfield.value = "AnotherValue";
In XPages this is done completely different as there you have JavaScript classes with similar / same methods / properties as the NotesDocument- class to mimic the LotusScript behaviour

Categories