How can I grab osclass theme HTML from plugin using JavaScript? - javascript

I have a variable called btn that I assign to a document.querySelector() function. I know the query selection is right because it grabs the element I want when I run it through the browser console. Nonetheless, the assignment produces a null result. Is this because I cannot grab HTML in this way with osclass framework?
I'm developing a plugin. This plugin alters the registration form. I'm adding a text field wherein I've used an event listener to detect input. If there's input, I want the form to do something when the submit button is clicked. There's no problem detecting this form field, I suspect because I've just added it in the plugin folder. I cannot, however, grab HTML from the theme. I think part of this is because I'm trying to grab it before the HTML loads. Even so, I've tried deferring the script and using an inline script to run the code after the DOM content loads. No success.
Here's the bit of HTML I want to grab.
<div class="controls">
<button type="submit" class="ui-button ui-button-middle ui-button-main"><?php _e("Create", 'bender'); ?></button>
</div>
Here's the code I'm using to do that, and the code I want to execute:
var btn = document.querySelector("div.controls button");
btn.addEventListener("submit", function() {
console.log("Honey is sweet!");
});
Finally here's how I'm running the script:
<script type="text/javascript" async="" defer="" src="<?php echo osc_base_url().'oc-content/plugins/honeypot/fieldcheck.js';?>"></script>
I should mention I'm running this as a function with the osclass hook: osc_add_hook('user_register_form', 'twf_honeypot_form_field');
I expect the variable to grab the button, and the event listener to be added to to the button. Once the form is submitted, it should log the message in the console. What's happening instead is this error: Uncaught TypeError: Cannot read property 'addEventListener' of null.
If you've used osclass, is this because the HTML lives elsewhere? I thought that, if I deferred the script, this code wouldn't execute until the page loaded, and I'd still be able to grab the HTML. If not, how can I grab this bit of HTML from a theme file?

Turns out this line was the problem: osc_add_hook('user_register_form', 'twf_honeypot_form_field'). The code wouldn't execute before the dom loaded, even if I specified for it to do so in the script itself because the script still executed only here. I put the script call in a function and added a new hook: osc_add_hook('after_html', 'twf_deny'); Should have guessed there was a hook for that use case.

Related

Javascript Function Inside Dynamically Added User Control Inside Update Panel Is Not Defined

I've got an ASP.NET Webforms page that is largely dynamically generated based on information received from a database. The controls get injected into an UpdatePanel. For the most part everything is working, except one control contains a javascript function that is executed when the user clicks a button inside the control. The control works perfectly on a test page, but when used inside this dynamically created page, clicking the button returns a JS console error saying that the function "is not defined" even though a page source inspection through the browser shows that it is present. Trying to execute the function through the chrome developer tools console after that control is injected onto the page gives the same error. How do I make the function available to execute?
At a high level / pseudocode it looks like the below:
<Page>
...
<DynamicWizardControl>
<UpdatePanel>
<!--dyanamically injected stuff-->
<WizardDocumentSubmissionControl>
<DocumentSubmissionControl ID="Attachments" runat="server">
<asp:Textbox ID='txtFile' runat='server'></asp:Textbox>
<asp:Button ID='btnAdd' runat='server' Text='Add File' />
<script>
function submitFile<%=btnAdd.ClientID%>() {
alert($('#<%=txtFile.ClientID%>').val());
}
</script>
</DocumentSubmissionControl>
</WizardDocumentSubmissionControl>
<!--End Dynamically Injected Stuff-->
</UpdatePanel>
</DynamicWizardControl>
</Page>
Code Behind for the WizardDocumentSubmissionControl
Page_Load
Attachments.JSSubmitButton.OnClientClick = Attachments.SubmitFileJSFunctionName
Code Behind for the DocumentSubmissionControl
Public ReadOnly Property SubmitFileJSFunctionName As String
Get
Return "submitFile" & btnAdd.ClientID
End Get
End Property
Public ReadOnly Property JSSubmitButton As Button
Get
Return btnAddJS
End Get
End Property
So it seems like the dynamically injected control doesn't register the javascript to the DOM. I got it to work by using the ScriptManager.RegisterClientScriptBlock to register the entire javascript function which is something I was hoping to avoid because I feel that the JS should live inside the HTML portion of the control, not the code behind. If anyone knows of any better method, please let me know.

javascript function gets called twice

I am trying to call a javascript function on clicking a link. Actually i want to submit a form on clicking a link using post method so i am trying to do the below-
<a href="javascript:submitCategory(this)" >Handicrafts</a>
and in javascript
function submitCategory(varthis)
{
alert(varthis.value);
}
I have few important questions:
1>When i click on the link the function submitCategory gets called twice. After much analysis found that i had two js files included and removing one of them made the function getting called only once.
meaning
when i have included
<script type ="text/javascript" src="jquery.js"></script>
<script type ="text/javascript" src="cWed.js"></script>
submitCategory function gets called twice
and when i remove one of them and include
<script type ="text/javascript" src="jquery.js"></script>
submitCategory function gets called only once.
Why is it like this?
2> alert(thisvar.value) should return Handicrafts but it returns undefined. why could this be?
3>what exactly is the meaning of href="javascript:submitCategory(this)"? i have not come across this in any tutorial. and including this here should refer to the element "a" right?
1. You do not need to use the qualifier 'javascript:'
2. when you hook the event in html, always try to do it like event_handler(event). Note : event is the event object. and not some random variable here. You can read more about it in numerous places on the web. In your case varthis is the event object. to access this element use varthis.target and then to get its inner html you can use varthis.target.innerHTML
3. when the function is called you have to either explicitly get the html content of the calling element via the event tag, or just use jquery. You cannot pass variables in the way you think you are passing right now.
4. if you are actually trying to submit a form, I would recommend hooking the onSubmit event in script rather than HTML and put your custom form submit code there. If you do not need to do anything custom in form submission, you can just put the url of the target server function in the action attribute of the form.
Sample code :
<form>
Submit Category
</form>
<script type="text/javascript">
$('#submitCategoryLink').on('click', function (e) {
alert(e.target.innerHTML)
});
</script>
Since you haven't posted the contents of cWed.js it's difficult to know why you're getting a double submission, but my guess is that it contains a click handler of its own, which is duplicating the default handler.
The reason varthis.value doesn't work is because .value is only used for <input> and <select> elements, it contains the value that the user entered or selected from the menu. To get the text content of an element you should use .innerHTML.
A URI that begins with javascript: means that instead of fetching a page from a network location, the browser should execute the Javascript code after that prefix. It's not an officially recognized URI scheme (there was an Internet-Draft RFC, but it expired 2 years ago) , but all browsers support it.
When code is executing from a javascript: URI, this is the window, not the element that was clicked on. You need to use an onclick handler to get this set to the element.
The following works:
<a href="javascript:void(0)" onclick="submitCategory(this); return false;" >Handicrafts</a>
function submitCategory(varthis)
{
alert(varthis.innerHTML);
}
FIDDLE

Inline Editing But Instance Doesn't Exist

I have my own custom non-jQuery ajax which I use for programming web applications. I recently ran into problems with IE9 using TinyMCE, so am trying to switch to CKeditor
The editable text is being wrapped in a div, like so:
<div id='content'>
<div id='editable' contenteditable='true'>
page of inline text filled with ajax when links throughout the site are clicked
</div>
</div>
When I try to getData on the editable content using the examples in the documentation, I get an error.
I do this:
CKEDITOR.instances.editable.getData();
And get this:
Uncaught TypeError: Cannot call method 'getData' of undefined
So I figure that it doesn't know where the editor is in the dom... I've tried working through all editors to get the editor name, but that doesn't work-- no name appears to be found.
I've tried this:
for(var i in CKEDITOR.instances) {
alert(CKEDITOR.instances[i].name);
}
The alert is just blank-- so there's no name associated with it apparently.
I should also mention, that despite my best efforts, I cannot seem to get the editable text to have a menu appear above it like it does in the Massive Inline Editing Example
Thanks for any assistance you can bring.
Jason Silver
UPDATE:
I'm showing off my lack of knowledge here, but I had never come across "contenteditable='true'" before, so thought that because I was able to type inline, therefore the editor was instantiated somehow... but now I'm wondering if the editor is even being applied to my div.
UPDATE 2:
When the page is loaded and the script is initially called, the div does not exist. The editable div is sent into the DOM using AJAX. #Zee left a comment below that made me wonder if there is some other command that should be called in order to apply the editor to that div, so I created a button in the page with the following onclick as a way to test this approach: (adapted from the ajax example)
var editor,html='';config = {};editor=CKEDITOR.appendTo('editable',config, html );
That gives the following error in Chrome:
> Uncaught TypeError: Cannot call method 'equals' of undefined
> + CKEDITOR.tools.extend.getEditor ckeditor.js:101
> b ckeditor.js:252
> CKEDITOR.appendTo ckeditor.js:257
> onclick www.pediatricjunction.com:410
Am I headed in the right direction? Is there another way to programmatically tell CKEditor to apply the editor to a div?
UPDATE 3:
Thanks to #Reinmar I had something new to try. The most obvious way for me to test to see if this was the solution was to put a button above the content editable div that called CKEDITOR.inlineAll() and inline('editable') respectively:
<input type='button' onclick=\"CKEDITOR.inlineAll();\" value='InlineAll'/>
<input type='button' onclick=\"CKEDITOR.inline('editable');\" value='Inline'/>
<input type='button' onclick=\"var editor = CKEDITOR.inline( document.getElementById( 'editable' ) );\" value='getElementById'/>
This returned the same type of error in Chrome for all three buttons, namely:
Uncaught TypeError: Cannot call method 'equals' of undefined ckeditor.js:101
+ CKEDITOR.tools.extend.getEditor ckeditor.js:101
CKEDITOR.inline ckeditor.js:249
CKEDITOR.inlineAll ckeditor.js:250
onclick
UPDATE 4:
Upon further fiddling, I've tracked down the problem being related to json2007.js, which is a script I use which works with Real Simple History (RSH.js). These scripts have the purpose of tracking ajax history, so as I move forward and back through the browser, the AJAX page views is not lost.
Here's the fiddle page: http://jsfiddle.net/jasonsilver/3CqPv/2/
When you want to initialize inline editor there are two ways:
If element which is editable (has contenteditable attribute) exists when page is loaded CKEditor will automatically initialize an instance for it. Its name will be taken from that element's id or it will be editor<number>. You can find editors initialized automatically on this sample.
If this element is created dynamically, then you need to initialize editor on your own.
E.g. after appending <div id="editor" contenteditable="true">X</div> to the document you should call:
CKEDITOR.inline( 'editor' )
or
CKEDITOR.inlineAll()
See docs and docs.
You can find editor initialized this way on this sample.
The appendTo method has different use. You can initialize themed (not inline) editor inside specified element. This method also accepts data of editor (as 3rd arg), when all other methods (CKEDITOR.inline, CKEDITOR.replace, CKEDITOR.inlineAll) take data from the element they are replacing/using.
Update
I checked that libraries you use together with CKEditor are poorly written and cause errors you mentioned. Remove json2007.js and rsh.js and CKEditor works fine.
OK, so I have tracked down the problem.
The library I was using for tracking Ajax history and remembering commands for the back button, called Real Simple History, was using a script called json2007 which was intrusive and extended native prototypes to the point where things broke.
RSH.js is kind of old, and I wasn't using it to it's full potential anyway, so my final solution was to rewrite the essential code I needed for that, namely, a listener that watched for anchor (hash) changes in the URL, then parsed those changes and resubmitted the ajax command.
var current_hash = window.location.hash;
function check_hash() {
if ( window.location.hash != current_hash ) {
current_hash = window.location.hash;
refreshAjax();
}
}
hashCheck = setInterval( "check_hash()", 50 );
'refreshAjax()' was an existing function anyway, so this is actually a more elegant solution than I was using with Real Simple History.
After stripping out the json2007.js script, everything else just worked, and CKEditor is beautiful.
Thanks so much for your help, #Reinmar... I appreciate your patience and effort.

Connect links inside an dijit.dialog

i have some trouble to connect an link inside an dijit.dialog.
Iam calling an "other" html file inside the Dialog (dialog.href="xxx.html") inside this file iam trying to connect some links by id, to fire an alert box. But nothing happens ? Possible that this isnt possible ??
Thats the part from my xxx.html file..
<script type="text/javascript">
dojo.addOnLoad(function( ) {
dojo.connect(dojo.byId('testLink'), 'onClick', alert('xx'));
}); </script>
TEST
Dialog is extended from ContentPane so it supports all the same parameters (href, etc.). With that said, when a page is included via the href property any <script> tags are not evaluated they are just added to the DOM. This leaves you with two choices:
refactor xxx.html, so the script can be run by the dialog's onLoad handler
embed the event handlers into the html tags; i.e. <input type="button" onClick="alert('xx');" />
Another option would be to use dojox.layout.ContentPane. It'll parse <script> tags. It's in dojox though so it's liable to change in future version. And another downside is that this would require creating your own Dialog class that's a subclass of dojox.layout.ContentPane.
There's also an article on dojocampus about executing javascript in content panes which talks a little bit about using dojox.layout.ContentPane to roll your own Dialog widgets.

Generated Javascript Does not execute

I am busy writing a simple Adobe Air app using HTML, jQuery and some jQuery plugin to load RSS feeds.
The problem I am having is that I am generating a section of HTML components (buttons) so that I can execute specific code on button click. But when the page is displayed the button never executes; I have tried using the built-in log function as well as alert, but none of them execute. The weird part is when I copy the HTML component into a part of the page that is not generated it executes fine.
I insert the following into a div using jQuery and it does not execute.
'<input type="button" onclick="LoadPage()" value="Test" />'
If I just insert it into the HTML it works fine.
I am using version 1.3.2 of jQuery; I am also using this plugin to load the data into a div, and I have modified line 82 to include the html component above.
I should note that when I inspect the page using AIR's introspector the HTML is valid.
What could be going wrong?
I don't see the problem. The following works fine for me:
$(document).ready(function() {
$('#mainDiv').html('<input type="button" onclick="LoadPage()" value="Test" />');
});
function LoadPage()
{
alert("Hello");
}
If you want to use jquery to handle the click you can use the live event.
I also had that problem some time ago, and this solved the problem.
If you give your button an id would look something like this:
$("#YourButtonId").live("click", function (){....
Got the same problem with 'onClick' instead of 'onclick' ?
Also check if the function isn't called 'Loadpage' instead of 'LoadPage'.
I sometimes have case sensitive problems in javascript, not sure if it are functions that are case sensitive.

Categories

Resources