Reading .text() from XML not working in IE - javascript

Hi I have this code that is all working in FF, except for the variable populated by a .text() method in IE.
The example code is below:
<script language="javascript" type="text/javascript">
$(document).find('f').each(function(){
var ff= $(this).attr("m");
var fmsg = $(this).text();
alert(ff + ' - ' +fmsg);
});
</script>
The data (document):
<data>
<f m="1">hi</f>
<f m="2">bye</f>
</data>
Why is the alert not showing '1 - hi' and '2 - bye', instead its showing an empty value for the fmsg variable. Any suggestions? Here is a working example: http://jsfiddle.net/dtuce/1/

The jQuery#text method doesn't really seem to be prepared to gather text content from XML from what I could see. (I'd gladly take pointers, though)
text: function( text ) {
if ( jQuery.isFunction(text) ) {
return this.each(function(i) {
var self = jQuery( this );
self.text( text.call(this, i, self.text()) );
});
}
if ( typeof text !== "object" && text !== undefined ) {
return this.empty().append( (this[0] && this[0].ownerDocument || document).createTextNode( text ) );
}
return jQuery.text( this );
}
There is -- as always -- a difference between the W3 adherent browsers and IE. The W3 compliant browsers expose the Node#textContent property, while IE exposes the Node#innerText property.
MDN documentation for Node#textContent
HTH,
FK

Related

Make javascript if statement display html?

I wanted an if statement to show an image or html code depending on the webpage. I got this far and the html table doesn't appear at all (appears blank):
<script type="text/javascript">
<!--
var url = document.location.pathname;
if( document.location.pathname == '/tagged/photos' ){
document.innerHTML('<table><tr> hello </tr> </table>');
}
if( document.location.pathname == '/tagged/news' ){
document.write("<b>This is my news page</b>");
}
//-->
</script>
I'd do it slightly differently
Add both markup to the page, and show/hide as approproate:
<table id="table"><tr> hello </tr></table>
<span id="title"><b>This is my news page</b></span>
<script type="text/javascript">
$(function(){
var url = document.location.pathname;
if( url == '/tagged/photos' ){
$('#title').hide();
$('#table').show();
}
if( url == '/tagged/news' )
{
$('#title').show();
$('#table').hide();
}
})
</script>
I have assumed you have JQuery since it is tagged
You're using document.innerHTML, which doesn't exist. At the very least, you need to get a proper element:
document.documentElement.innerHTML = 'some HTML';
Setting aside everything else that's wrong with this approach, I'm not sure, why would you use document.write() in one branch and someElement.innerHTML in the other.
I'd suggest the following approach:
function pagePopulate() {
// you're looking at the pathname, use a sensible (meaningful) variable-name:
var pagePath = document.location.pathname,
// this is a map, of the relationship between page and content:
pathToContent = {
// pagename : html
'photos': '<table><tbody><tr><td>photos page</td></tr></tbody></table>',
'news': '<b>This is the news page</b>'
},
// getting a reference to the <body> element:
body = document.querySelector('body');
// setting the innerHTML of the <body>,
// if pagePath = 'tagged/photos', splitting with '/' would return:
// ['tagged','photos'], calling 'pop()' returns the last element of the array
// 'photos', which returns that string to the square brackets, resulting in:
// pathToContent['photos'], which would yield the '<table>...</table>' HTML.
// if that call resulted in an undefined, or falsey, value, then the default
// (the string *after* the '||' would be used instead:
body.innerHTML = pathToContent[pagePath.split('/').pop()] || '<h2>Something went wrong</h2><img src="http://blog.stackoverflow.com/wp-content/uploads/error-lolcat-problemz.jpg" />';
}
// calling the function:
pagePopulate();
References:
|| (logical 'or' operator).
Array.prototype.pop().
document.querySelector().
String.prototype.split().

load wordpress wp_editor dynamically (ajax)

This is an answer/solution rather than a question, still there maybe some bugs, even I tried on my dev env.
I recently try to use wp_editor in widget/menu, after some search, I did not find a complete solution as I want.
I would share my solution in below after I dig into wp's code by hours:
There maybe hacking involved, however, I tried to minimize them.
To make wp_editor can work in dynamic html (which means without reload page, js changes the page structure), there are two major issues need to take care:
tinymce
qucik-tags
For [tinymce]:
a. need reset UI properly
solution is [remove mce instance] -> [get proper mce settings] -> [re-init a new mce instance]
in js code (id means textarea id):
tinymce.execCommand('mceRemoveEditor', true, id);
var init = tinymce.extend( {}, tinyMCEPreInit.mceInit[ id ] );
try { tinymce.init( init ); } catch(e){}
b. need data write back to textarea before submit
solution is [bind click to button] -> on submt :: [turn off mce] -> [turn on submit]
in js code:
jq('textarea[id="' + id + '"]').closest('form').find('input[type="submit"]').click(function(){
if( getUserSetting( 'editor' ) == 'tmce' ){
var id = mce.find( 'textarea' ).attr( 'id' );
tinymce.execCommand( 'mceRemoveEditor', false, id );
tinymce.execCommand( 'mceAddEditor', false, id );
}
return true;
});
For [Quick Tags]:
a. Re-init tags
[Get settings] -> [setup mouse event] -> [re-init QTags]
b. Switch to proper tab (mce tab or quick tag tab)
[switch to current tab mode]
both above in js code:
if ( typeof(QTags) == 'function' ) {
jq( '[id="wp-' + id + '-wrap"]' ).unbind( 'onmousedown' );
jq( '[id="wp-' + id + '-wrap"]' ).bind( 'onmousedown', function(){
wpActiveEditor = id;
});
QTags( tinyMCEPreInit.qtInit[ id ] );
QTags._buttonsInit();
switchEditors.switchto( jq( 'textarea[id="' + id + '"]' ).closest( '.widget-mce' ).find( '.wp-switch-editor.switch-' + ( getUserSetting( 'editor' ) == 'html' ? 'html' : 'tmce' ) )[0] );
}
Also, please remember if you use ajax, every time post back mce UI, you need re-do [reset mce UI] and [Qtags] in you js.
A easy solution is using js code in you post back html, and detect in php of:
$isAjax = defined( 'DOING_AJAX' ) && DOING_AJAX == true );
About default settings in js value:
mce : tinyMCEPreInit.mceInit
qtags : tinyMCEPreInit.qtInit
If you try to use default setting for widget mode, you need locate default settings.
To get widget template id, in js code:
function getTemplateWidgetId( id ){
var form = jQuery( 'textarea[id="' + id + '"]' ).closest( 'form' );
var id_base = form.find( 'input[name="id_base"]' ).val();
var widget_id = form.find( 'input[name="widget-id"]' ).val();
return id.replace( widget_id, id_base + '-__i__' );
}
So you can get settings by:
for mce:
var init;
if( typeof tinyMCEPreInit.mceInit[ id ] == 'undefined' ){
init = tinyMCEPreInit.mceInit[ id ] = tinymce.extend( {}, tinyMCEPreInit.mceInit[ getTemplateWidgetId( id ) ] );
}else{
init = tinyMCEPreInit.mceInit[ id ];
}
For Qtags:
var qInit;
if( typeof tinyMCEPreInit.qtInit[ id ] == 'undefined' ){
qInit = tinyMCEPreInit.qtInit[ id ] = jq.extend( {}, tinyMCEPreInit.qtInit[ getTemplateWidgetId( id ) ] );
qInit['id'] = id;
}else{
qInit = tinyMCEPreInit.qtInit[ id ];
}
For the complete code sample, please check : https://github.com/hezachary/wordpress-wysiwyg-widget/blob/master/widget_wp_editor.class.php
If anyone want use wp_editor in menu walk for admin, the principle should be the same.
If you have any question or better solut please comment, thanks.
Working solution:
p.s. you'd have asked at WP.SE: https://wordpress.stackexchange.com/a/192132/33667
add action in wordpress, lets say My_Action_Name (also note, textarea ID My_TextAreaID_22 ):
add_action('wp_ajax_My_Action_Name', function(){
wp_editor( $_POST['default_text'], 'My_TextAreaID_22', $settings = array( 'tinymce'=>true, 'textarea_name'=>'name77', 'wpautop' =>false, 'media_buttons' => true , 'teeny' => false, 'quicktags'=>true, ) ); exit;
});
now, in Dashboard, execute this function (note, using of My_TextAreaID_22 and My_Action_Name):
function start_Ajax_request() {
Alert("I have started");
My_New_Global_Settings = tinyMCEPreInit.mceInit.content; // Get default Wordpress SETTINGS ( I cant confirm, but if you will need to change target ID, then add this line: My_New_Global_Settings.selector = "My_TextAreaID_22"; )
jQuery.post(ajaxurl,
{ action: "My_Action_Name", default_text: "Hello World"},
function(response,status){
Alert("I have Finished");
tinymce.init(My_New_Global_Settings);
tinyMCE.execCommand('mceAddEditor', false, "My_TextAreaID_22");
quicktags({id : "My_TextAreaID_22"});
}
);
}
start_Ajax_request(); // < ---- EXECUTE
I have faced similar issue. I solved the issue by using following
1. Added following filter to open the editor always in visual mode in main page
add_filter( 'wp_default_editor', create_function('', 'return "tinymce";') );
2. In Ajax content used following for editor
wp_editor( $content, "editor_ajax", array('textarea_name'=>"content_ajax",'quicktags' => array('buttons' => 'strong,em,link,block,del,ins,img,ul,ol,li,code,close')));
3. In Ajax content added following JS code
<script src="<?php bloginfo('home')?>/wp-includes/js/quicktags.min.js"</script>
<script>
jQuery(document).ready(function(){
ed_id = "editor_ajax";
quicktags({id : ed_id,buttons:"strong,em,link,block,del,ins,img,ul,ol,li,code,more,close,dfw"});
tinyMCE.execCommand('mceAddEditor', false, fullId);
});
</script>

CakePhp2 autocomplete (jquery-ui folding) not working without ajax, only with array of available inputs

I am using cakephp2.
I want to make autocomplete in cakephp2, but not with ajax, it is array where are autocomplete`s available inputs. I have simple LocationsController (not important but i enclosed it) where i have:
class LocationsController extends AppController {
public $name = 'Locations';
public function index() {
$this->set('title_for_layout', 'Example - title');
}
}
I have a view/locations/index.ctp where i Have
<div id="big_input_normal" >
<form>
<input type="text" id="the_big_one" class="big_input_selection" />
</form>
</div>
<script>
$(function() {
var names = [ "Bratislava", "Praque", "Trstena" ];
var accentMap = {
"á": "a",
"ö": "o",
"é": "e"
};
var normalize = function( term ) {
var ret = "";
for ( var i = 0; i < term.length; i++ ) {
ret += accentMap[ term.charAt(i) ] || term.charAt(i);
}
return ret;
};
$( "#the_big_one" ).autocomplete({
source: function( request, response ) {
var matcher = new RegExp( $.ui.autocomplete.escapeRegex( request.term ), "i" );
response( $.grep( names, function( value ) {
value = value.label || value.value || value;
return matcher.test( value ) || matcher.test( normalize( value ) );
}) );
}
});
});
</script>
Ofcourse i have included in head :
<script src="./app/webroot/js/jquery-1.7.1.js"></script>
<script src="./app/webroot/js/jquery.ui.core.js"></script>
<script src="./app/webroot/js/jquery.ui.widget.js"></script>
<script src="./app/webroot/js/jquery.ui.position.js"></script>
<script src="./app/webroot/js/jquery.ui.autocomplete.js"></script>
To sum up:
I am using CAKEPHP2 (it is version 2 NOT 1.3), I want to make autocomplete with jquery, i downloaded jquery-ui and i have followed the examples folding http://jqueryui.com/demos/autocomplete/
I have made it, have a look at example codes, but there is a problem, it DOES NOT WORK.
Javascripts are after the page to client is rendered defaultly blocked ?
Or where is the problem? Please help me, am losing my mind with this primitive problem.
It looks like all of the javascript inclusions are incorrect. They should reference the js file like so:
<script src="/js/jquery-1.7.1.js"></script>
To get cake to do this automatically, you can do:
<?php echo $this->Html->script('jquery-1.7.1.js'); ?>

Is there a way to getElement xml by attribute?

I'm trying to grab an xml node by its attribute.
edit
I'm trying to retrieve an element by its attribute value using javascript xml instead of jquery. Is there a simple method for this?
It is really easy using jQuery. Suppose we have a string like this.
<document>
<value type="people">
<name>
John
</name>
</value>
<value type="vehicle">
<name>
Ford
</name>
</value>
</document>
Then
var xmlDocument = $.parseXML(str);
$(xmlDocument).find("value[type='people'] name").text()
We will get string 'John' back.
You have to find a list of elements first, then filter by their attributes.
Check out my demo here: http://jsfiddle.net/silkster/eDP5V/
I feel this justifies a new answer as it is JQuery Free
document.getElementsByAttribute = function(attribute, value, tagName, parentElement) {
var children = ($(parentElement) || document.body).getElementsByTagName((tagName || '*'));
return $A(children).inject([], function(elements, child) {
var attributeValue = child.getAttribute(attribute);
if(attributeValue != null) {
if(!value || attributeValue == value) {
elements.push(child);
}
}
return elements;
});
}
source
it has been pointed out to me that I posted the wrong script.. hehe read here
// document.getElementsByAttribute([string attributeName],[string attributeValue],[boolean isCommaHyphenOrSpaceSeparatedList:false])
document.getElementsByAttribute=function(attrN,attrV,multi){
attrV=attrV.replace(/\|/g,'\\|').replace(/\[/g,'\\[').replace(/\(/g,'\\(').replace(/\+/g,'\\+').replace(/\./g,'\\.').replace(/\*/g,'\\*').replace(/\?/g,'\\?').replace(/\//g,'\\/');
var
multi=typeof multi!='undefined'?
multi:
false,
cIterate=document.getElementsByTagName('*'),
aResponse=[],
attr,
re=new RegExp(multi?'\\b'+attrV+'\\b':'^'+attrV+'$'),
i=0,
elm;
while((elm=cIterate.item(i++))){
attr=elm.getAttributeNode(attrN);
if(attr &&
attr.specified &&
re.test(attr.value)
)
aResponse.push(elm);
}
return aResponse;
}
jquery can do this very easily. http://think2loud.com/224-reading-xml-with-jquery/

javascript validate zip regular expression

Thanks guys. I take your advice and modify the script as following. Now it seems working.
<script src="jquery-1.4.2.min.js" type="text/javascript"></script>
<script>
$(function(){
var pat=/^[0-9]{5}$/;
if ( !pat.test( $('#zip').val() ) )
{$('#zip').after('<p>zip is invalid</p>');}
})
</script>
zip (US only) <input type="text" name='zip' id='zip' maxlength="5">
.val needs to be .val()
and use .after() or .before() and not .append()
var pattern = /^[0-9]{5}$/;
if (!pattern.test($('#zip').val())) {
$('#zip').after('<p>zip is invalid</p>');
}
zip is invalid should be enclosed in quotes
and .val needs to be .val()
<script>
pattern=/^[0-9]{5}$/;
if (!pattern.test( $('#zip').val() ) )
{
$('#zip').val($('<p>',{html: "zip is invalid"}));
}
</script>
Space it out so you can see what's wrong..
pattern=/^[0-9]{5}$/;
if (
!pattern.test( $('#zip').val() )
)
{
$('#zip').after(
$('<p>',{html: "zip is invalid"})
);
}
val() and "zip is valid". Also, the var is useless unless within a function scope.
(function() {
var pattern=/^[0-9]{5}$/;
if (
!pattern.test( $('#zip').val() )
)
{
$('#zip').after(
$('<p>',{html: "zip is invalid"})
);
}
})();
Now pattern is local to that function only and nothing else. In CMS's example it's still a global unless you're taking the snippet and using it in an actual function.

Categories