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.
Related
I'm trying to access the position of the # symbol and using the following JS...
<script>
$(document).ready(function () {
$("#submitButton").click(function (e) {
var at = $('#email').val().lastIndexOf("#");
});
});
</script>
However this produces a Parse Error:
"");" is not valid at the start of a code block. Only identifiers, keywords, comments, "(" and "{" are valid.
Do I need an escape character here? When I replace the # with some other character, say a letter. It does not crash. This code works...
$("#submitButton").click(function (e) {
var at = $('#email').val().lastIndexOf("w");
e.preventDefault();
Assuming you are trying to execute the exact snippet above, the error is telling you that your code is not valid. Specifically, you are missing a closing curly brace (}) and a closing parenthesis ())
Here is what it should look like:
$("#submitButton").click(function(e) {
var at = $('#email').val().lastIndexOf("#");
console.log('at', at);
e.preventDefault();
}); // <-- Closing } and )
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<button id="submitButton">Click Me</button>
<input id="email" type="text" value="something#something.com" />
As far as the # symbol goes, you do not need to escape it in this scenario.
EDIT
The error your getting smells a lot like you're using this in an ASP.NET controller. You might just be including your JS wrong. Try including it by doing it this way:
#scripts {
<script>
$(document).ready(function () {
$("#submitButton").click(function (e) {
var at = $('#email').val().lastIndexOf("#");
});
});
</script>
}
I found it! The # symbol needs an escape character...another # symbol. This works...
var at = $('#email').val().lastIndexOf("##");
I have a data from database.
In my js file, I would like to change my CKEditor text editor's value.
My value is raw html.
I want this raw value to be written on an empty CKEditor text editor.
I tried these but got an undefined function error all the time :
CKEDITOR.instances.myEditorID.insertHtml( '<p>This is a new paragraph.</p>' );
CKEDITOR.instances.myEditorID.setData( '<p>This is the editor data.</p>' );
I tried this too but still undefined function error :
CKEDITOR.instances.YOUREDITORID.updateElement();
alert( document.getElementById( 'YOUREDITORID' ).value );
Instead of myEditorID i tried 'editor', 'editor1', 'editor2' but still doesn't work for me.
Thanks in advance.
---Update---
This is the html of my ckeditor text editor :
<textarea id="myEditorID" name="myEditor"></textarea>
<script type="text/javascript">
$(function () {
var myEditor = $('#myEditorID');
myEditor.ckeditor({
height: 200,
extraPlugins: 'charcount',
maxLength: 2000,
toolbar: 'TinyBare',
toolbar_TinyBare: [
['Bold','Italic','Underline'],
['Undo','Redo'],['Cut','Copy','Paste'],
['NumberedList','BulletedList','Table'],['CharCount']
]
}).ckeditor().editor.on('key', function(obj) {
if (obj.data.keyCode === 8 || obj.data.keyCode === 46) {
return true;
}
if (myEditor.ckeditor().editor.document.getBody().getText().length >= 2000) {
alert('You have reached the maximum char length');
return false;
}
});
});
</script>
Instead of myEditorID i tried 'editor', 'editor1', 'editor2' but still
doesn't work for me.
You need to look at the HTML of your page and see what the ID field is for your editor. It will be something like this
<textarea id="my_editor"></textarea>
That id attribute is what needs to go in here
CKEDITOR.instances.my_editor.insertHtml('<p>This is a new paragraph.</p>');
If you have a CKeditor like
<textarea id="user_body"></textarea>
To insert data, Please use the following line of Code
CKEDITOR.instances["user_body"].insertHtml('');
Hope it will work for you. Thanks
In your HTML
<textarea name="contenteditor" id="contenteditor" style="margin:0px 10px;">
</textarea>
In your JavaScript (JQuery)
$(function(){
CKEDITOR.replace('contenteditor');
//Your data
var yourData = '<p>This is a new paragraph.</p>';
//insert your data in the editor
$("#contenteditor").val(yourData);
})
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'); ?>
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
I am using gettext in my PHP code, but I have a big problem. All my JavaScript files are not affected by the translation, can somebody tell me an easy way to get the translations in the chosen language into JavaScript as well.
The easiest way is having a PHP file write the translations from gettext into JavaScript variables.
js_lang.php:
word_hello = "<?php echo gettext("hello"); ?>"
word_world = "<?php echo gettext("world"); ?>"
word_how_are_you = "<?php echo gettext("how_are_you"); ?>"
and then include it:
<script type="text/javascript" src="js_lang.php"></script>
I would also recommend this method in conjunction with the translation plugins S.Mark mentions (which are very interesting!).
You can define the dictionary in the current page's header, too, without including an external file, but that way, you would have to look up and send the data on every page load - quite unnecessary, as a dictionary tends to change very rarely.
I generally export the translations in a JavaScript structure:
var app = {};
var app.translations = {
en: {
hello: "Hello, World!",
bye: "Goodbye!"
},
nl: {
hello: "Hallo, Wereld!",
bye: "Tot ziens!"
}
};
The current language of the page texts can be defined using: <html xml:lang="en" lang="nl">
This can be read in JavaScript:
var currentLanguage = document.documentElement.lang || "en";
app.lang = app.translations[ currentLanguage ] || app.translations.en;
And then you can write code like this:
alert( app.lang.hello );
Optionally, a i18n() or gettext() function can bring some intelligence, to return the default text if the key does not exist). For example:
function gettext( key )
{
return app.lang[ key ] || app.translations.en[ key ] || "{translation key not found: " + key + "}";
}
Try, jQuery i18n or jQuery localisation
An example for jQuery i18n, and of course you need to generate JSON based dictionary from language file from php
var my_dictionary = {
"some text" : "a translation",
"some more text" : "another translation"
}
$.i18n.setDictionary(my_dictionary);
$('div#example').text($.i18n._('some text'));
JSGettext (archived link) is best implementation of GNU gettext spec.
First download JSGETTEXT package and include in your page
/js/Gettext.js
<?php
$locale = "ja_JP.utf8";
if(isSet($_GET["locale"]))$locale = $_GET["locale"];
?>
<html>
<head>
<link rel="gettext" type="application/x-po" href="/locale/<?php echo $locale ?>/LC_MESSAGES/messages.po" />
<script type="text/javascript" src="/js/Gettext.js"></script>
<script type="text/javascript" src="/js/test.js"></script>
</head>
<body>
Test!
</body>
</html>
javascript code for example
window.onload = function init(){
var gt = new Gettext({ 'domain' : 'messages' });
alert(gt.gettext('Hello world'));
}
For reference find below link. It's working fine without converting .js file to .php.
Click here
You can make your life much easier if you get rid of bad habit to use string literals in your code. That is, instead of
alert("Some message")
use
alert($("#some_message_id").text())
where "#some_message_id" is a hidden div or span generated on the server side.
As a further hint there's a perl script called po2json which will generate json from a .po file.
For JavaScript implementation of GNU gettext API these links can be also useful:
http://tnga.github.io/lib.ijs
http://tnga.github.io/lib.ijs/docs/iJS.Gettext.html
//set the locale in which the messages will be translated
iJS.i18n.setlocale("fr_FR.utf8") ;
//add domain where to find messages data. can also be in .json or .mo
iJS.i18n.bindtextdomain("domain_po", "./path_to_locale", "po") ;
//Always do this after a `setlocale` or a `bindtextdomain` call.
iJS.i18n.try_load_lang() ; //will load and parse messages data from the setting catalog.
//now print your messages
alert( iJS.i18n.gettext("messages to be translated") ) ;
//or use the common way to print your messages
alert( iJS._("another way to get translated messages") ) ;
This library seems the best implementation of getText in javascript:
http://messageformat.github.io/Jed/
https://github.com/messageformat/Jed
example from the documentation:
<script src="jed.js"></script>
<script>
var i18n = new Jed({
// Generally output by a .po file conversion
locale_data : {
"messages" : {
"" : {
"domain" : "messages",
"lang" : "en",
"plural_forms" : "nplurals=2; plural=(n != 1);"
},
"some key" : [ "some value"]
}
},
"domain" : "messages"
});
alert( i18n.gettext( "some key" ) ); // alerts "some value"
</script>