How to change value of a input textbox using dom.byid? - javascript

I am trying to change value of an Input Textbox using several options of dojo but somehow those are not working. On the other hand when I am trying to change the text using document.getElememtById option I am able to do so. Can someone please explain why my dojo options are not working ?
if (response.responseJSON.errorMessage){
dom.byId("AuthInfo").innerHTML=response.responseJSON.errorMessage;
// dom.byId("AuthPassowrd").value="";
// domAttr.set("AuthPassowrd", "value", "");
// domConstruct.empty("AuthPassword");
document.getElementById("AuthPassword").value="";
}
and my html code is-
<input type="password" placeholder="Enter password" id="AuthPassword"/>

I'm not sure if it's a typo in this code only, but you wrote "AuthPassowrd" in stead of "AuthPassword". If it's only the case here (and not the real code), read my original answer.
Original answer
Are you sure you imported the correct modules (dojo/dom, dojo/dom-attr and dojo/dom-construct)? The examples are working fine for me. I made a JSFiddle to show you how it works. You can import these modules by using:
require(["dojo/dom", "dojo/dom-attr", "dojo/dom-construct"], function(dom, domAttr, domConstruct) {
// Here you can use dom, domAttr and domConstruct
});
Make sure the DOM is loaded before you execute your commands. Operations on DOM nodes can only be executed when that part of the DOM (or the entire page) is loaded. Usually you can wait until the DOM is ready with the dojo/domReady! plugin:
require(["dojo/domReady!], function() {
// Will only be executed when the dom is ready
});
In your third commented line of code you use domConstruct.empty("AuthPassword");. This won't work for clearing the input field but is used to delete all child nodes from a DOM node. The value of the textbox is not a childnode, so it won't work.

You should just replace this:
domAttr.set("AuthPassowrd", "value", "");
with:
domAttr.set(dom.byId("AuthPassword"), "value", "");

Related

DOM manipulation with mathjax

I'm trying to make a button that when pressed at least once, a math symbol/equation made from MathJax appears in a designated spot on my webpage. So far, this is what I have
//in JS
//when button is pressed, then x^2 appears
document.getElementById("button").addEventListener("click", function() {
MathJax.HTML.addElement(document.body, "div", {
id: "sqrt"
}, ["$$x^2$$"]);
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/mathjax/2.7.3/MathJax.js"></script>
<!--Press button for x^2 to appear-->
<button id="button">Press</button>
<!--x^2 appears here-->
<p id="sqrt"></p>
but every time I press the button, I don't get x^2, I literally get a string. I know the MathJax.HTML.addElement works when it's outside the event listener, but I'm trying to do this with a button. Any ideas would be helpful.
Thank you
Edit: My question is different because it's asking why, when I submit a button, it's showing my the literal string $$x^2$$ instead of the symbol. I know the document on the MathJax page mentions something about it, but I'm a complete novice and don't understand it. I was hoping someone could help me.
Link to a repl.it showing the problem:
https://mathjax-experiement--dolphinsupreme.repl.co
Edit 2: The x^2 symbol isn't showing up on the repl.it link, I'm not sure why because it's showing up on repl.it built-in page.
Once you have loaded mathJax, you need either a configuration script, or specify options through url:
eg ?config=TeX-AMS-MML_HTMLorMML&dummy=.js
see Loading and Configuring MathJax
MathJax works as a preprocessor, and renders mathematical expressions in the DOM where it's needed.
Everything else that contains mathematical expressions which comes from variables in your script, json or whatever must be interpreted (typesetted) to be properly rendered, once it's appended to the DOM.
MathJax.Hub.Typeset()
Outside the event listener, if MathJax.HTML.addElement(); is immediatly invoked when the DOM is loading, it will first add the element to the DOM, then is processed with the whole document (or the nodes you have specified in your configuration), that's why it works.
Later when you click a button to display a mathematical expression from a variable, you have to invoke Typeset() again:
MathJax.Hub.Typeset(".sqrt");
Indeed, addElement(), won't render your element:
addElement(parent, type[, attributes[, content]])
Creates a DOM element and appends it to the parent node provided. It is equivalent to
parent.appendChild(MathJax.HTML.Element(type,attributes,content))
However, mathjax works asynchronously, as rendering may take a while (otherwise, browser may freeze until it's done), so what will happen if you click while mathjax engine is still occupied to render something elsewhere in your page? To avoid your call to be forgotten, it is safer to enqueue your desired typeset in the mathjax queue:
MathJax.Hub.Queue(["Typeset",MathJax.Hub,".sqrt"]);
If the queue is empty, this will throw immediatly, if not, it will insured you that your action will be thrown at the end of the process.
Everything is exposed here.
Side Note :
In your snippet, you do not configure mathjax properly.
You also add an element with always the same id, which is not valid.
If you just want to replace the content of your div, don't use addElement.
Otherwise you should work with class and create unique ids. See the snippet for details.
// this works as I explain above (don't forget to escape backslash in your string)
//console.log("\\"); as a reminder!
MathJax.HTML.addElement(document.body, "div", {class: "sqrt",id:"sqrt_"+length},["\\begin{equation}x+1\\over\\sqrt{1-x^2}\\end{equation}"]);
document.getElementById("button1").addEventListener("click", function() {
var length = document.getElementsByClassName(".sqrt").length;
var expression = document.getElementById("expression").value || `$$x^2$$`;
MathJax.HTML.addElement(document.body, "div", {class: "sqrt",id:"sqrt_"+length},[expression]);
MathJax.Hub.Queue(["Typeset",MathJax.Hub,"#sqrt_"+length]);
});
document.getElementById("button2").addEventListener("click", function() {
var expression = document.getElementById("expression").value || `$$x^2$$`;
document.getElementsByClassName("sqrt")[0].innerHTML = expression;
MathJax.Hub.Queue(["Typeset",MathJax.Hub,".sqrt"]);
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/mathjax/2.7.3/MathJax.js?config=TeX-AMS-MML_HTMLorMML&dummy=.js"></script>
<textarea id="expression"></textarea>
<!--Press button for x^2 to appear-->
<button id="button1">Add</button>
<button id="button2">Replace</button>
<!--x^2 appears here-->
<p class="sqrt">\begin{equation}
x+1\over\sqrt{1-x^2}
\end{equation}</p>

kicking off ajax query to php mysql DB by use of onblur

I'm trying (and failing) to make an ajax process work when people leave a form input field. I need it to happen for each input field, of any type, on the form.
I'm trying to modify the following (which does work):
$("document").ready(function() {
$("#getcontent").click(getContent);
});
function getContent() {
$("#example").load("sampletextcontent.txt");
}
(there would be a button with id="getcontent" in the html, and a div with id="example" also in the html. When button clicked, contents of external file sampletextcontent.txt is displayed within said div)
jquery IS being used, version 2.0.3 jquery.min.js
So I am trying (and this is where I am failing) is to convert the above to become:
$("document").ready(function() {
$("#input_1_1").onblur(doSend);
$("#input_1_2").onblur(doSend);
$("#input_1_3").onblur(doSend);
$("#input_1_4").onblur(doSend);
$("#input_1_5").onblur(doSend); // etc for as many fields there are
})
function doSend() {
// Do some ajax stuff to send the entire value of all form fields in here
}
But it does not seem to like the concept of using the replacement of the ".click" to ".onblur" here. Why is this? Isn't onblur a valid JS function/item?
Sorry I'm not a JS guru, I have great problems understanding JS.
C
Edit - sorry I was not clear about the code I am trying to get working. There is no button in the version I want to work, it's just wanting to trigger by when a user clicks/tabs away from each input field. Sorry about not making that clear before.
For dynamic jQuery event binding, I would try switching out the .click and .blur functions with the .on function.
As an example, I would try the following:
$('body').on('click', '#getcontent', function(){
DoSomething();
});
and
$('body').on('blur', '#input_1_1', function(){
DoSomething();
});
The documentation for the on function can be found http://api.jquery.com/on/.
Here is another Stack Overflow article that also explains this: Event binding on dynamically created elements?.
Thanks to the comments and answer attempts. However the answer that I'm using, that actually does answer the specific question is the following. Simply change:
$("document").ready(function() {
$("#input_1_1").onblur(doSend);
$("#input_1_2").onblur(doSend);
$("#input_1_3").onblur(doSend);
$("#input_1_4").onblur(doSend);
$("#input_1_5").onblur(doSend); // etc for as many fields there are
})
To become:
$("document").ready(function() {
$("#input_1_1").blur(doSend);
$("#input_1_2").blur(doSend);
$("#input_1_3").blur(doSend);
$("#input_1_4").blur(doSend);
$("#input_1_5").blur(doSend); // etc for as many fields there are
})
And it works. This retains the ability to call different functions per field if I so wish, and is very straightforward for a JS novice like me to work with.
A better cleaner solution may be implemented later, but for now this will do and directly answers the original question.

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.

Removing data attributes from HTML using jQuery

Can't seem to get this one to work...
I have a page that hides certain links. When the DOM is loaded, I'm using jQuery to toggle some of those elements. This is driven by using a data attribute like so:
<div class="d_btn" data-usr='48'>
<div class="hidden_button">
Then, I have the code:
$.each($(".d_btn"), function() {
var btn = $(this).data('usr');
if ( btn == '48' ){
$(this).children('.hidden_button').toggle();
}
The above all works as planned. The problem is that I am trying to remove the data-usr from the class .d_btn once the if statement is evaluated. I've tried the following and nothing works (i.e., after the page is loaded, the source still shows the data-usr attribute:
$(this).removeAttr("data-usr");
$(this).removeData("usr");
I've been working on this for a couple of hours now and...nothing! Help is greatly appreciated!
UPDATE
I've tried the great suggestions of setting the data attribute to an empty string but I'm still not getting the desired result.
To explain a little further, The reason I'm trying to remove the attribute is so when an ajax response adds another item to the page, the previously added items would already have the button either shown or hidden. Upon AJAX response, I'm calling the same function once the DOM is loaded.
Currently, when something is added via AJAX, it toggles all the buttons (showing the ones that were hidden and vice versa.) Ugh...
I'm also fully willing to try alternatives to my approach. Thanks!
UPDATE
Well, the light bulb just flashed and I am able to do what I want to do by just using .show() instead of .toggle()
Anyway, I'd still like to find an answer to this question because the page will be potentially checking hundreds of items whenever something is added - this seems horribly inefficient (even for a computer, hahaha.)
Why don't you set the value to a random value or empty variable instead if removeAttr does not work..
$(this).attr("data-usr" , '');
$(this).prop("data-usr" , '');
Changing the DOM doesn't affect the source. It affects the DOM, which you can view with the Inspector/Developer Tools. Right click => View Source will give you the original source of the page, not the actual current source as modified by JavaScript.
Set it to a blank string:
$(this).attr("data-usr", "");
I second what Kolink said: check the DOM, not the source. (Chrome: Ctrl + Shift + i).
As others have stated. Checking the source will only show the original unedited source for the webpage. What you need to do is check the DOM using developer tools.
I've just checked everything in Chrome's inspector on jsfiddle here and the attribute is definitely being removed as well as the data.

jQuery breaks if function does not exists

Tinymce stops working if on the same page I use the selectmenu from https://github.com/fnagel/jquery-ui
Tinymce with default configuration
and selectmenu:
$('select.flags').selectmenu();
EDIT:
The problem is that on the page with tinymce i dont load the script for the selectmenu function. Should I remove it from the js that runs all the functions or is there any way to modify it to run only if the function exists and will be able to be ran
Here is an easy way to make 'function does not exist' problems go away.
$.fn.selectmenu = $.fn.selectmenu || $.noop
$('select.jquery_smenu').selectmenu(); //do what you will
or you could do it like this:
if( $.fn.selectmenu ){
$('select.jquery_smenu').selectmenu(); //do what you will
}
for the record, function does not exist or var is not a function is a javascript problem more than a jQuery one. Hope this helps!
Is tiny working with this script added to the page, but not initialized for the selects?
You apply selectmenu to every single select on your page.
tinymce uses selects and your surely don't want to change these.
Give your selects a class like
<select class="jquery_smenu"> ....
and change your selector:
$('select.jquery_smenu').selectmenu();
I can not test if thats the reason why tiny stops working, but you should change that.

Categories

Resources