Issues in javascript mention script in textarea - javascript

im trying to implement mention using (#) on a textarea that feeds from MySQL database.
this is the code im using below
var start=/#/ig; // # Match
var word=/#(\w+)/ig; //#abc Match
$("#newstatus").live("keyup",function()
{
var content=$(this).val() //Content Box Data
var go= content.match(word); //Content Matching #
var name= content.match(word); //Content Matching #abc
var dataString = 'searchword='+ name;
//If # available
if(go.length>0)
{
$("#msgbox").slideDown('show');
$("#display").slideUp('show');
$("#msgbox").html("Type the name of someone or something...");
//if #abc avalable
if(name.length>0)
{
$.ajax({
type: "POST",
url: siteurl + "ajax/mention", // Database name search
data: dataString,
cache: false,
success: function(data)
{
$("#msgbox").hide();
$("#display").html(data).show();
}
});
}
}
return false;
});
The problem happens when i add more text it keeps showing suggested box, i want to stop searching whenever i start a new sentence after the #WORD im using e.g.
#blackberry is my favorite smartphone !
i may use more than one mention in that textarea !
i want your help how do i do that whenever i use # then i have suggested list whenever i choose i can continue writing and may use another mention

Solution is:
$("#newstatus").live("keyup",function()
{
var content=$(this).val() //Content Box Data
var index= content.lastIndexOf("#"); //Content Matching #
var name= content.substr(n+1);; //Content Matching abc, If you want to get #abc then remove +1.
var dataString = 'searchword='+ name;
Explanation:
I am searching last position of # in a given string (using lastIndexOf()) and from that I am getting the string till end using substr().
You no need to use reg exp for this. Regular Exp are very costly, it will consume more resources, According to my knowledge better to ignore regular exp for a small operations.

Related

Using document.getElementById() inside a function

I have this code:
<div id="com_22">
<a onclick="delete(22);">delete entry</a>
</div>
and the javascript code:
function delete(url){
var tupu = document.getElementById("#com_"+url+"");
alert(tupu);
}
the problem is I'm having a null alert
I want to get the id
document.getElementById("#com_22");
How I can solve it
update
this is my code:
function confirmDel(url){
$(document).ready(function(){
$.ajax({
type: 'POST',
url: '/files/assets/php/ajax/blog-stream.php?act=del',
data: 'url=' + url ,
success: function(h){
var status = h.status
if (status == "si" ) {
$("#com_"+url+"").fadeOut("slow");
}
}
});
});
}
the code excecutes so well except for the id didnt fade out
$("#com_"+url+"").fadeOut("slow"); <--- no working
See :: getElementById(), that should have been:
function delete_something(url){
var tupu = document.getElementById("com_"+url);
alert(tupu);
}
btw, try avoiding use of js pre-defined names as function name see:: delete
Don't include the hash when you're selecting by id. You're not using jQuery or querySelector.
var tupu = document.getElementById("com_"+url);
There is also no need to concatenate the empty string there at the end so I removed it.
Remove the '#' from within the bracket.
The function getElementById gets the element ID as a string, not a CSS-style selector. Change to:
var tupu = document.getElementById("com_"+url);
As can be extracted by javascript levels:
[{"file": ". m3u8" in this page: http: //ivm.antenaplay.ro/js/embed_aplay_fullshow.js? id = 6eI6sLVBfOL

How to pass javascript array variable through jquery $.window url to codeigniter controller?

I have a list of students with a corresponding check box each. The check box value contains students id that I need to pass to my controller function. I have a javascript code that detects the check box checked values and stored it to a javascript array variable. The javascript array variable will then be passed to the $.window url with a url address heading to my codeigniter controller function. This works fine when you choose the first student, it will show the student id via var_dump method, however, if the second or third and so on student is chosen, it says the uri you submitted has disallowed character. The same response when you checked all check boxes. The javascript array variable seems to passed only a single value to my codeigniter controller function taking just the first value of the student list. How I would be able to pass also the 2nd, 3rd and so on checked values or even to pass javascript array variable to codeigniter controller function through javascipt url with $.window. Images and codes are shown below. Thanks a lot.
Image choosing just the first student list
Controller output image after clicking send email button
Image choosing the second student
Controller output image after clicking send email button
Image choosing all student list
Controller output image after clicking send email button
Javascript:
<script type="text/javascript">
$("#send_email").click(function(){
var cboxes = document.getElementsByName('student_id[]');
var checked_val= [];
var unchecked_val=[];
var len = cboxes.length;
for (var i=0; i<len; i++) {
(cboxes[i].checked) ? checked_val[i]=cboxes[i].value:unchecked_val[i]=cboxes[i].value;
}
$.window({
title: "Coursebooking",
url: "<?php echo base_url() ?>student_controller/pop_val/"+checked_val,
});
});
</script>
Controller:
function pop_val(){
$stud_id = $this->uri->segment(3);
var_dump($stud_id);
}
try this,
var array_val = $('input[name="student_id[]"]:checked').map(function(){
return this.value;
}).get();
$.window({
title: "Coursebooking",
url: "<?php echo base_url() ?>ajax_student_controller/pop_val/" + array_val,
........
localhost/coursebooking/ajax_student_controller/pop_val/338,339 This kind of url causes the uri disallowed character error. A comma between the numbers 338 and 339. To solve this is just to add comma character in config.php file in $config['permitted_uri_chars'] = 'a-z 0-9~%.:_+-'; and then use explode function in your controller function to separate the comma separated values. Here are the output:
Image of a var_dump output after checking 3 check boxes and adding comma character in the config.php file $config['permitted_uri_chars'] = 'a-z 0-9~%.:_+-,';
Image of a var_dump output to separate comma separated values into array indexed values using explode function.
Controller Code:
function pop_val(){
$stud_id = $this->uri->segment(3);
$split_val = explode(',',$stud_id);
var_dump($split_val);
}
My revised javascript code. However, this changes only applies in getting the second value of the student list being checked, the same as getting the right value of the 3rd student list being checked. But checking all check boxes together returns a uri error saying "The URI you submitted has disallowed characters".
<script type="text/javascript">
$("#send_email").click(function(){
var cboxes = document.getElementsByName('student_id[]');
var checked_val= [];
var unchecked_val=[];
var array_val=new Array();
var len = cboxes.length;
for (var i=0; i<len; i++) {
if(cboxes[i].checked){
checked_val[i]=cboxes[i].value;
array_val.push(checked_val[i]);
}
}
$.window({
title: "Coursebooking",
url: "<?php echo base_url() ?>ajax_student_controller/pop_val/" + array_val,
});
});
</script>
Image choosing the second student on the list
Controller output returns the right value
Image choosing the 3rd student on the list
Controller output returns the right value
Image choosing the all student on the list
Still Controller output returns the uri error
url: "<?php echo base_url() ?>student_controller/pop_val/"+checked_val,
Try:
url: "/student_controller/pop_val/" + checked_val,

ckeditor inline save/submit

I can't work out how to grab the edited data from a CKEditor instance and post it to a url.
I'm looking at something this:
http://nightly.ckeditor.com/3995/samples/inlineall.html
and I can't work out how the changes can be saved. Can I post the newly edited data to be posted to a PHP along with the ID of the element being edited?
Similarly to this:
editor.on('configLoaded', function(){
// do some stuff
});
I was hoping I could do something like this:
editor.on('clickAway', function(e){
id = e.id();
// do some ajax stuff
});
But I can't seem to find anything, anywhere.
Has anyone worked out how to do this?
Thank you.
I'm sure there are many ways to pull this off, but here's my solution. I'm using the Smarty Template Engine, but this technique should work with vanilla HTML too.
First off, here's an example of some HTML stored in my template file named "dog_fleas.tpl":
<script type="text/javascript" src="/js/ckeditor/ckeditor.js"></script>
<script type="text/javascript" src="/js/admin/mycms.js"></script>
<div>
<div id="flea-blurb" tpl="/templates/dog_fleas.tpl" contenteditable="true">
<h1>My Dog Has Fleas</h1>
<p>This text is editable via the CMS!</p>
</div>
<p>This text is not editable</p>
</div>
The javascript (mycms.js) to handle the inline editing is:
$(document).ready(function() {
CKEDITOR.disableAutoInline = true;
$("div[contenteditable='true']" ).each(function( index ) {
var content_id = $(this).attr('id');
var tpl = $(this).attr('tpl');
CKEDITOR.inline( content_id, {
on: {
blur: function( event ) {
var data = event.editor.getData();
var request = jQuery.ajax({
url: "/admin/cms-pages/inline-update",
type: "POST",
data: {
content : data,
content_id : content_id,
tpl : tpl
},
dataType: "html"
});
}
}
} );
});
});
The above code does a few things:
It converts any div tag with the attribute contenteditable = "true" to inline-editable.
After content is edited (on blur), the editable element id, tpl filename, and edited content are sent to the server via an ajax call.
The tpl attribute is necessary in my situation to identify the file being edited. The element id specifies which element was modified.
Although my example only contains one editable region, this code supports multiple editable regions in a single file.
On the server-side, here's my PHP code. I'm using a framework, so my $this->_POST() functions might look a little unusual, but hopefully you get the idea:
// Get the posted parameters
$new_content = $this->_POST('content');
$content_id = $this->_POST('content_id');
$tpl_filename = $this->_POST('tpl');
// Get the contents of the .tpl file to edit
$file_contents = file_get_contents(APPPATH . 'views' . $tpl_filename);
// create revision as a backup in case of emergency
$revised_filename = str_replace('/', '.', $tpl_filename);
$revised_filename = ltrim ($revised_filename, '.');
file_put_contents(APPPATH . 'views/templates/revisions/' . $revised_filename . '.' . time(), $file_contents);
// Prepare to match the DIV tag
// Credit to: http://stackoverflow.com/questions/5355452/using-a-regular-expression-to-match-a-div-block-having-a-specific-id
$re = '% # Match a DIV element having id="content".
<div\b # Start of outer DIV start tag.
[^>]*? # Lazily match up to id attrib.
\bid\s*+=\s*+ # id attribute name and =
([\'"]?+) # $1: Optional quote delimiter.
\b' . $content_id . '\b # specific ID to be matched.
(?(1)\1) # If open quote, match same closing quote
[^>]*+> # remaining outer DIV start tag.
( # $2: DIV contents. (may be called recursively!)
(?: # Non-capture group for DIV contents alternatives.
# DIV contents option 1: All non-DIV, non-comment stuff...
[^<]++ # One or more non-tag, non-comment characters.
# DIV contents option 2: Start of a non-DIV tag...
| < # Match a "<", but only if it
(?! # is not the beginning of either
/?div\b # a DIV start or end tag,
| !-- # or an HTML comment.
) # Ok, that < was not a DIV or comment.
# DIV contents Option 3: an HTML comment.
| <!--.*?--> # A non-SGML compliant HTML comment.
# DIV contents Option 4: a nested DIV element!
| <div\b[^>]*+> # Inner DIV element start tag.
(?2) # Recurse group 2 as a nested subroutine.
</div\s*> # Inner DIV element end tag.
)*+ # Zero or more of these contents alternatives.
) # End 2$: DIV contents.
</div\s*> # Outer DIV end tag.
%isx';
if (preg_match($re, $file_contents, $matches))
{
$content_to_replace = $matches[0];
$replacement_content = $content_to_replace;
// Replace the inner content of $replacement_content with $new_content
$replacement_content = preg_replace('/(<div(?:.*?)>)(?:.*)(<\/div>)/msi',"$1" . $new_content . "$2", $replacement_content);
// Now replace the content_to_replace with $replacement content in the HTML
$new_file_contents = str_replace($content_to_replace, $replacement_content, $file_contents);
// write out the new .tpl file
file_put_contents(APPPATH . 'views' . $tpl_filename, $new_file_contents);
}
The PHP code above is basically loading the HTML, locating the div tag with the proper id, then replacing the contents of that div tag with the content sent down via the ajax call. The HTML is then re-saved to the server. I also include some code to store backup revisions just in case things go terribly wrong.
I realize that regular expressions aren't always the best solution. In my case, it was difficult to use the PHP Dom Object Model because my HTML content isn't valid HTML. You might look into using the Dom Object Model instead if your system is simpler than mine.
I hope this helps!
I've found the following solution: How do I save inline editor contents on the server?
I'm using the blur event
Using above answer of #clone45 and modified it. The data will be saved busing Save button and only after some changes carried out were old and new data is compared.
Overridden existing save button of inline editor and included below only alerted part of #clone45's answer.
<script>
CKEDITOR.disableAutoInline = true;
$("div[contenteditable='true']").each(function(index) {
var content_id = $(this).attr('id');
var tpl = $(this).attr('tpl');
var oldData = null;
CKEDITOR.inline(content_id, {
on: {
instanceReady: function(event) {
//get current data and save in variable
oldData = event.editor.getData();
// overwrite the default save function
event.editor.addCommand("save", {
modes: {
wysiwyg: 1,
source: 1
},
exec: function() {
var data = event.editor.getData();
//check if any changes has been carried out
if (oldData !== data) {
oldData = data;
$.ajax({
type: 'POST',
url: 'process.php',
data: {
content: data,
content_id: content_id,
tpl: tpl
}
})
.done(function(data) {
alert('saved');
})
.fail(function() {
alert('something went wrong');
});
} else
alert('looks like nothing has been changed');
}
});
}
}
});
});
</script>
Hope this helps!!

jQuery / javascript and nested if statements

I have a multi-lingual page where I want to display form validation error in the user's language. I use a hidden input to determine which language version the user is browsing like this: <input type="hidden" name="lang" id="lang" value="<?php echo $lang; ?>" />
The PHP side of the script works, but jQuery doesn't seem to realize which language is passed on. It displays the English error message no matter on which language site I am.
Here's the code (I removed the other form fields for length):
$(document).ready(function(){
$('#contact').submit(function() {
$(".form_message").hide();
var emailReg = /^([\w-\.]+#([\w-]+\.)+[\w-]{2,4})?$/;
var lang = $("#lang").val();
var name = $("#name").val();
var dataString = {
'lang': lang,
'name': name
}
if (name == '') {
if (lang == 'de') {
$("#posted").after('<div class="form_message"><p><span class="error">Fehler:</span> Bitte gib deinen Namen an!</p></div>');
} else {
$("#posted").after('<div class="form_message"><p><span class="error">Error:</span> Please enter your name!</p></div>');
}
$("#name").focus();
$("#name").addClass('req');
} else {
$("#loading").show();
$("#loading").fadeIn(400).html('<img src="/img/loading.gif" />Loading...');
$.ajax({
type: "POST",
url: "/contact-post.php",
data: dataString,
cache: false,
success: function(html){
$("#loading").hide();
$("#posted").after('<div class="form_message"><p>Thank you! Your contact request has been sent.</p></div>');
$("#contact input:submit").attr("disabled", "disabled").val("Success!");
}
});
}return false;
}); });
The problem seems to be somewhere in the nested if statement. Does jQuery / javascript even recognize nested ifs? And if yes, why is it not working?
Does jQuery / javascript even recnogize nested ifs?
Yes they do
One thing worth checking that would cause this behaviour is that you don't have any other elements on your page with id = lang. If there are, your $("#lang") selector will only find the first one, and if that's not your hidden input it won't work as you expect.
Javascript is case-sensitive, and perhaps the value of your #lang element is in a different case. You can force it to be lowered like this...
var lang = $("#lang").val().toLowerCase();
Why wouldn't it recognize nested if's?
Can you include the HTML for the page? There doesn't appear to be anything wrong with this javascript at all - so I have a feeling the issue is with the rest of the page.
Barring that, put an alert(lang) in right before your if statement to see what it is set to. My guess is that it will not be set to the value that you think it should be set to.
Check the value
alert("'" + lang + "' :" + lang.length);

Query String for pre-filling html form field

I manage a website for an organization that has separate chapter sites. There is a membership signup form that is on the main website that each chapter links to. On the form there is a dropdown box that allows a person to choose the chapter they want to join. What I would like to do is have each chapter website use a specific link to the form that will preselect their chapter from the dropdown box.
After searching the web, I found that I will probably need to use a Javascript function to utilize a Query String. With all my searching, I still can't figure out the exact code to use. The page is a basic HTML page...no php and it is hosted on a linux server.
Any help would be greatly appreciated.
If you format your url like this:
www.myorg.com?chapter=1
You could add this script to your html head:
function getparam(name) {
name = name.replace(/[\[]/, "\\\[").replace(/[\]]/, "\\\]");
var regexS = "[\\?&]" + name + "=([^&#]*)";
var regex = new RegExp(regexS);
var results = regex.exec(window.location.href);
if (results == null)
return "";
else
return results[1];
}
function loadform()
{
var list = document.getElementById("mychapterdropdown");
var chapter = getparam("chapter");
if (chapter>=0 && chapter < list.options.length)
{
list.selectedIndex = chapter;
}
}
The in your html body tag:
<body onload="loadform();" >
Could probably add more validation checks but that's the general idea.
It sounds like what you are looking for are GET or POST requests. For instance, if your user selects "Chapter A" from your form and hits select, you can allow redirects from another site (for instance http://www.yoursite.com/form.html?chapter=A) to allow Chapter A to be preselected. In Javascript this is done by
var chapter="";
var queryString = location.search.substring(1);
if ( queryString.length > 0 ) {
var getdata = queryString.split("&");
var keyvalues;
for(var i=0; i < getdata.length; i++){
keyvalues = getdata.split("=");
}
} else {
chapter = "Not Found";
}
document.getElementById( "ChapterID").value = keyvalues['chapter'];
This is untested, so don't hold me to it :).
maybe something using parse_url
$params = parse_url()
$query = $params['query'];
$query_pairs = explode('&',$query);
$key_val = array();
foreach($query_pairs as $key => $val){
$key_val[$key] = $val;
}
http://www.php.net/manual/en/function.parse-url.php
You would probably have to use an dynamic ajax content. Use the following javascript to read the querystring, then load the html file in that div using this javascript.

Categories