When I create a new link for my textarea it creates a new line like
[enter link description here][1] and [enter link description here][2]
[1]: http://
[2]: http://
As you can see above there is a gap between the bottom two links I don't want the gap there
It should look like
[enter link description here][1] and [enter link description here][2]
[1]: http://
[2]: http://
Question how to make it so when create new link that there are no gaps
for the bottom links.
Here is a codepen demo has been updated with working code
<script type="text/javascript">
$('#myLink').on('shown.bs.modal', function() {
var textarea = document.getElementById("message");
var len = textarea.value.length;
var start = textarea.selectionStart;
var end = textarea.selectionEnd;
var selectedText = textarea.value.substring(start, end);
$('#title').val(selectedText);
$('#url').val('http://');
});
$('#save').on('click', function(e) {
var textarea = document.getElementById("message");
var len = textarea.value.length;
var start = textarea.selectionStart;
var end = textarea.selectionEnd;
var selectedText = textarea.value.substring(start, end);
var counter = findAvailableNumber(textarea);
if ($.trim($('#title').val()).length == 0){
var replace_word = '[enter link description here]' + '[' + counter + ']';
} else {
var replace_word = '[' + $(this).val() + ']' + '[' + counter + ']';
}
var add_link = '\n\n' + ' [' + counter + ']: ' + $('#url').val();
textarea.value = textarea.value.substring(0, start) + replace_word + textarea.value.substring(end,len) + add_link;
});
function findAvailableNumber(textarea){
var number = 1;
var a = textarea.value;
if(a.indexOf('[1]') > -1){
//Find lines with links
var matches = a.match(/(^|\n)\s*\[\d+\]:/g);
//Find corresponding numbers
var usedNumbers = matches.map(function(match){
return parseInt(match.match(/\d+/)[0]); }
);
//Find first unused number
var number = 1;
while(true){
if(usedNumbers.indexOf(number) === -1){
//Found unused number
return number;
}
number++;
}
}
return number;
}
</script>
I think your code at:
var add_link = '\n\n' + ' [' + counter + ']: ' + $('#url').val();
should instead be
if (counter == 1)
var add_link = '\n\n' + ' [' + counter + ']: ' + $('#url').val();
else
var add_link = '\n' + ' [' + counter + ']: ' + $('#url').val();
so that there is no gap between links, except between the text and link. Since the links should be next to each other (see assumption below), only the first link should have a gap
ASSUMPTION: I'm assuming there shouldn't be any text after the links.
Related
I am working on a web application in Visual Studio using visual basic and master pages. I have 10 textbox fields on a child page where I would like to emulate the iPhone password entry (ie. show the character entered for a short period of time then change that character to a bullet). This is the definition of one of the text box controls:
<asp:TextBox ID="txtMID01" runat="server" Width="200" MaxLength="9"></asp:TextBox>
At the bottom of the page where the above control is defined, I have the following:
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
<script type="text/javascript" src="lib/jQuery.dPassword.js"></script>
<script type="text/javascript">
$(function () {
var textbox01 = $("[id$=txtMID01]");
alert(textbox01.attr("id"));
$("[id$=txtMID01]").dPassword()
});
</script>
When the page loads, the alert displays MainContent_txtMID01 which is the ID of the control preceeded with the name of the content place holder.
The following is the contents of lib/jQuery.dPassword.js (which I found on the internet):
(function ($) {
$.fn.dPassword = function (options) {
var defaults = {
interval: 200,
duration: 3000,
replacement: '%u25CF',
// prefix: 'password_',
prefix: 'MainContent_',
debug: false
}
var opts = $.extend(defaults, options);
var checker = new Array();
var timer = new Array();
$(this).each(function () {
if (opts.debug) console.log('init [' + $(this).attr('id') + ']');
// get original password tag values
var name = $(this).attr('name');
var id = $(this).attr('id');
var cssclass = $(this).attr('class');
var style = $(this).attr('style');
var size = $(this).attr('size');
var maxlength = $(this).attr('maxlength');
var disabled = $(this).attr('disabled');
var tabindex = $(this).attr('tabindex');
var accesskey = $(this).attr('accesskey');
var value = $(this).attr('value');
// set timers
checker.push(id);
timer.push(id);
// hide field
$(this).hide();
// add debug span
if (opts.debug) {
$(this).after('<span id="debug_' + opts.prefix + name + '" style="color: #f00;"></span>');
}
// add new text field
$(this).after(' <input name="' + (opts.prefix + name) + '" ' +
'id="' + (opts.prefix + id) + '" ' +
'type="text" ' +
'value="' + value + '" ' +
(cssclass != '' ? 'class="' + cssclass + '"' : '') +
(style != '' ? 'style="' + style + '"' : '') +
(size != '' ? 'size="' + size + '"' : '') +
(maxlength != -1 ? 'maxlength="' + maxlength + '"' : '') +
// (disabled != '' ? 'disabled="' + disabled + '"' : '') +
(tabindex != '' ? 'tabindex="' + tabindex + '"' : '') +
(accesskey != undefined ? 'accesskey="' + accesskey + '"' : '') +
'autocomplete="off" />');
// change label
$('label[for=' + id + ']').attr('for', opts.prefix + id);
// disable tabindex
$(this).attr('tabindex', '');
// disable accesskey
$(this).attr('accesskey', '');
// bind event
$('#' + opts.prefix + id).bind('focus', function (event) {
if (opts.debug) console.log('event: focus [' + getId($(this).attr('id')) + ']');
clearTimeout(checker[getId($(this).attr('id'))]);
checker[getId($(this).attr('id'))] = setTimeout("check('" + getId($(this).attr('id')) + "', '')", opts.interval);
});
$('#' + opts.prefix + id).bind('blur', function (event) {
if (opts.debug) console.log('event: blur [' + getId($(this).attr('id')) + ']');
clearTimeout(checker[getId($(this).attr('id'))]);
});
setTimeout("check('" + id + "', '', true);", opts.interval);
});
getId = function (id) {
var pattern = opts.prefix + '(.*)';
var regex = new RegExp(pattern);
regex.exec(id);
id = RegExp.$1;
return id;
}
setPassword = function (id, str) {
if (opts.debug) console.log('setPassword: [' + id + ']');
var tmp = '';
for (i = 0; i < str.length; i++) {
if (str.charAt(i) == unescape(opts.replacement)) {
tmp = tmp + $('#' + id).val().charAt(i);
}
else {
tmp = tmp + str.charAt(i);
}
}
$('#' + id).val(tmp);
}
check = function (id, oldValue, initialCall) {
if (opts.debug) console.log('check: [' + id + ']');
var bullets = $('#' + opts.prefix + id).val();
if (oldValue != bullets) {
setPassword(id, bullets);
if (bullets.length > 1) {
var tmp = '';
for (i = 0; i < bullets.length - 1; i++) {
tmp = tmp + unescape(opts.replacement);
}
tmp = tmp + bullets.charAt(bullets.length - 1);
$('#' + opts.prefix + id).val(tmp);
}
else {
}
clearTimeout(timer[id]);
timer[id] = setTimeout("convertLastChar('" + id + "')", opts.duration);
}
if (opts.debug) {
$('#debug_' + opts.prefix + id).text($('#' + id).val());
}
if (!initialCall) {
checker[id] = setTimeout("check('" + id + "', '" + $('#' + opts.prefix + id).val() + "', false)", opts.interval);
}
}
convertLastChar = function (id) {
if ($('#' + opts.prefix + id).val() != '') {
var tmp = '';
for (i = 0; i < $('#' + opts.prefix + id).val().length; i++) {
tmp = tmp + unescape(opts.replacement);
}
$('#' + opts.prefix + id).val(tmp);
}
}
};
})(jQuery);
When I execute my code, the code behind populates the value of the textbox with "123456789" and when the page gets rendered, all the characters have been changed to bullets, which is correct. The problem I am having is that the textbox has been disabled so I can not edit the data in the textbox.
I removed (by commenting out) the references to the disabled attribute but the control still gets rendered as disabled.
As a side note, the code that I found on the internet was originally designed to work with a textbox with a type of password but when I set the TextMode to password, not only does the control get rendered as disabled, but the field gets rendered with no value so I left the TextMode as SingleLine.
Any suggestions or assistance is greatly appreciated.
Thanks!
As far as I know, it is not possible to have it so that while you type a password, the last letter is visible for a second and then turns into a bullet or star.
However what you can do is as the user types in password, with a delay of lets say 500ms store the string the user has typed in so far into some variable and replace the content of the password field or the text field with stars or black bullets. This will give you what you are looking for.
I am trying to be able to use highlight.js when my preview is enabled
Unable to get the highlightjs to work with my preview using showdown.js
Question: How to get the highlight.js to work with showdown.js
Codepen Demo Note all the .js files and css files are loaded in the codepen settings
I have tried using
$(document).ready(function() {
$('pre code').each(function(i, block) {
hljs.highlightBlock(block);
});
});
$("#message").on('keyup paste cut', function() {
var text = document.getElementById('message').value,
target = document.getElementById('showdown'),
converter = new showdown.Converter({
parseImgDimensions: true
}),
html = converter.makeHtml(text);
target.innerHTML = html;
});
Full Script
$(document).ready(function() {
$('pre code').each(function(i, block) {
hljs.highlightBlock(block);
});
})
$('#button-link').on('click', function() {
$('#myLink').modal('show');
});
$('#button-image').on('click', function() {
$('#myImage').modal('show');
});
$('#button-smile').on('click', function() {
$('#mySmile').modal('show');
});
$('#myLink').on('shown.bs.modal', function() {
var textarea = document.getElementById("message");
var len = textarea.value.length;
var start = textarea.selectionStart;
var end = textarea.selectionEnd;
var selectedText = textarea.value.substring(start, end);
$('#link_title').val(selectedText);
$('#link_url').val('http://');
});
$('#myImage').on('shown.bs.modal', function() {
$("#image_url").attr("placeholder", "http://www.example.com/image.png");
});
$("#save-image").on('click', function(e) {
var textarea = document.getElementById("message");
var len = textarea.value.length;
var start = textarea.selectionStart;
var end = textarea.selectionEnd;
var selectedText = textarea.value.substring(start, end);
var counter = findAvailableNumber(textarea);
var replace_word = '![enter image description here]' + '[' + counter + ']';
if (counter == 1) {
if ($('input#image_width').val().length > 0) {
var add_link = '\n\n' + ' [' + counter + ']: ' + $('#image_url').val() + ' =' + $('input#image_width').val() + 'x' + $('input#image_height').val();
} else {
var add_link = '\n\n' + ' [' + counter + ']: ' + $('#image_url').val();
}
} else {
var add_link = '\n' + ' [' + counter + ']: ' + $('#image_url').val();
}
textarea.value = textarea.value.substring(0, start) + replace_word + textarea.value.substring(end, len) + add_link;
$("#message").trigger('change');
});
$("#save-link").on('click', function(e) {
var textarea = document.getElementById("message");
var len = textarea.value.length;
var start = textarea.selectionStart;
var end = textarea.selectionEnd;
var selectedText = textarea.value.substring(start, end);
var counter = findAvailableNumber(textarea);
if ($('#link_title').val().length > 0) {
var replace_word = '[' + $('#link_title').val() + ']' + '[' + counter + ']';
} else {
var replace_word = '[enter link description here]' + '[' + counter + ']';
}
if (counter == 1) {
var add_link = '\n\n' + ' [' + counter + ']: ' + $('#link_url').val();
} else {
var add_link = '\n' + ' [' + counter + ']: ' + $('#link_url').val();
}
textarea.value = textarea.value.substring(0, start) + replace_word + textarea.value.substring(end, len) + add_link;
$("#message").trigger('change');
});
// Editor Buttons
$('#bold').on('click', function(e) {
text_wrap("message", "**", "**", 'strong text');
});
$('#italic').on('click', function(e) {
text_wrap("message", "*", "*", 'emphasized text');
});
$('#quote').on('click', function(e) {
text_wrap("message", "> ", "", 'Blockquote');
});
$('#code').on('click', function(e) {
code_wrap("message", "", "", 'enter code here');
});
function text_wrap(elementID, openTag, closeTag, message) {
var textArea = $('#' + elementID);
var len = textArea.val().length;
var start = textArea[0].selectionStart;
var end = textArea[0].selectionEnd;
var selectedText = textArea.val().substring(start, end);
if (selectedText.length > 0) {
replacement = openTag + selectedText + closeTag;
} else {
replacement = openTag + message + closeTag;
}
textArea.val(textArea.val().substring(0, start) + replacement + textArea.val().substring(end, len));
}
function code_wrap(elementID, openTag, closeTag, message) {
var textArea = $('#' + elementID);
var len = textArea.val().length;
var start = textArea[0].selectionStart;
var end = textArea[0].selectionEnd;
var selectedText = textArea.val().substring(start, end);
var multiLineReplace = '\n' + openTag;
if (selectedText.length > 0) {
//using regex to replace all instances of `\n` with `\n` + your indent spaces.
replacement = ' ' + openTag + selectedText.replace(/\n/g, multiLineReplace) + closeTag;
} else {
replacement = ' ' + openTag + message + closeTag;
}
textArea.val(textArea.val().substring(0, start) + replacement + textArea.val().substring(end, len));
}
function findAvailableNumber(textarea) {
var number = 1;
var a = textarea.value;
if (a.indexOf('[1]') > -1) {
//Find lines with links
var matches = a.match(/(^|\n)\s*\[\d+\]:/g);
//Find corresponding numbers
var usedNumbers = matches.map(function(match) {
return parseInt(match.match(/\d+/)[0]);
});
//Find first unused number
var number = 1;
while (true) {
if (usedNumbers.indexOf(number) === -1) {
//Found unused number
return number;
}
number++;
}
}
return number;
}
$("#message").on('keyup paste cut', function() {
var text = document.getElementById('message').value,
target = document.getElementById('showdown'),
converter = new showdown.Converter({
parseImgDimensions: true
}),
html = converter.makeHtml(text);
target.innerHTML = html;
});
$(function() {
$('[data-toggle="tooltip"]').tooltip()
});
I have made a script that allows the user to send a weekly newsletter powered by php. My php code is fine and working 100%. However, i made a script to count how many newsletters have been send out to check if all the newsletters have been send.
The code i made is the following:
function sendMail(test) {
var onderwerp = document.getElementById('getOnderwerp').value;
var pin = document.getElementById('secretPIN').value;
var e = document.getElementById('selectBrief');
var brief = e[e.selectedIndex].value;
var checkbox = [];
$('input[type="checkbox"][name="check_list[]"]').each(function(_, ele) {
if ($(ele).prop('checked')) {
checkbox.push($(ele).attr('value'));
}
});
loadgif2();
var breakx = false;
var temp = '';
var text = '';
var h = 0;
var regExp = /\(([^)]+)\)/;
var xhr = [];
for(var j = 0; j < checkbox.length; j++) {
if (breakx == true) {
removegif();
break;
}
var provincie = checkbox[j].replace(/\(([^)]+)\)/, '');
var aantal = checkbox[j].match(regExp)[1];
h = 0;
xhr = [];
temp = '';
temp = provincie + ' word verstuurd';
text += temp + '<br>';
for (i = 0; i < aantal; i++) {
if (breakx == true) {
break;
}
(function (i) {
xhr[i] = new XMLHttpRequest();
url = "/modules/pages/ajax/nieuwsbrief/send-mail.php?provincie=" + provincie +
"&test=" + test + "&brief=" + brief + "&onderwerp=" + onderwerp + "&pin=" + pin + "&offset=" + i;
xhr[i].open("POST", url, true);
xhr[i].onreadystatechange = function () {
if (xhr[i].readyState == 4 && xhr[i].status == 200) {
document.getElementById("spancontent").innerHTML = 'Even geduld, nieuwsbrief word verzonden<br><br>' + text;
document.getElementById("spancontent").innerHTML = 'Even geduld, nieuwsbrief word verzonden<br><br>' + text + '<br>' +
h + ' e-mails van de ' + aantal + ' verzonden in provincie ' + provincie;
h++;
if (h == aantal) {
text = text.replace(temp, provincie + ' is verzonden<br>');
document.getElementById("spancontent").innerHTML = 'Even geduld, nieuwsbrief word verzonden<br><br>' + text;
} else {
document.getElementById("spancontent").innerHTML = 'Even geduld, nieuwsbrief word verzonden<br><br>' + text + '<br>' +
h + ' e-mails van de ' + aantal + ' verzonden in provincie ' + provincie;
}
console.log(xhr[i].responseText);
if (xhr[i].responseText == '<br> Ongeldige PIN') {
breakx = true;
}
}
};
xhr[i].send();
})(i);
}
}
}
The code above is working but the only problem i'm facing is that as soon as i have a checkbox array length > 1 it'll not work properly. My guess is that the loop is going too fast and the xhr request just takes a little more time to get the php file stuff. My question is here how am i going to fix this? I was thinking myself to pause the script until the xhr requrest was done and resume it after.
Edit
I have edited my code to be like this:
function sendMail(FormElements, test) {
var onderwerp = document.getElementById('getOnderwerp').value;
var pin = document.getElementById('secretPIN').value;
var e = document.getElementById('selectBrief');
var brief = e[e.selectedIndex].value;
var checkbox = [];
$('input[type="checkbox"][name="check_list[]"]').each(function(_, ele) {
if ($(ele).prop('checked')) {
checkbox.push($(ele).attr('value'));
}
});
loadgif2();
sendmail2(0, test,brief,onderwerp,pin,checkbox, '');
}
function sendmail2(checkboxcount, test,brief,onderwerp,pin,checkbox,text) {
var breakx = false;
var temp = '';
var h = 0;
var regExp = /\(([^)]+)\)/;
var xhr = [];
var provincie = checkbox[checkboxcount].replace(/\(([^)]+)\)/, '');
var aantal = checkbox[checkboxcount].match(regExp)[1];
temp = provincie + ' word verstuurd';
text += temp + '<br>';
for (i = 0; i < aantal; i++) {
if (breakx == true) {
break;
}
(function (i) {
xhr[i] = new XMLHttpRequest();
url = "/modules/pages/ajax/nieuwsbrief/send-mail.php?provincie=" + provincie +
"&test=" + test + "&brief=" + brief + "&onderwerp=" + onderwerp + "&pin=" + pin + "&offset=" + i;
xhr[i].open("POST", url, true);
xhr[i].onreadystatechange = function () {
if (xhr[i].readyState == 4 && xhr[i].status == 200) {
document.getElementById("spancontent").innerHTML = 'Even geduld, nieuwsbrief word verzonden<br><br>' + text;
document.getElementById("spancontent").innerHTML = 'Even geduld, nieuwsbrief word verzonden<br><br>' + text + '<br>' +
h + ' e-mails van de ' + aantal + ' verzonden in provincie ' + provincie;
h++;
if (h == aantal) {
text = text.replace(temp, provincie + ' is verzonden<br>');
document.getElementById("spancontent").innerHTML = 'Even geduld, nieuwsbrief word verzonden<br><br>' + text;
if (checkboxcount + 1 == checkbox.length) {
} else {
sendmail2(checkboxcount + 1, test, brief, onderwerp, pin, checkbox,text);
}
} else {
document.getElementById("spancontent").innerHTML = 'Even geduld, nieuwsbrief word verzonden<br><br>' + text + '<br>' +
h + ' e-mails van de ' + aantal + ' verzonden in provincie ' + provincie;
}
console.log(xhr[i].responseText);
if (xhr[i].responseText == '<br> Ongeldige PIN') {
breakx = true;
}
}
};
xhr[i].send();
})(i);
}
}
This code acutally works the way i want to, but now i'm gettting some random 500 internal errors, but they seem to be completely random? sometimes they appear and sometimes they don't and i'm not changing anything. any solutions to this?
At your code:
xhr[i].open("POST", url, true);
Change it to:
xhr[i].open("POST", url, false);
It is a deprecated and bad workaround for your problem, you should find an other way.
( https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest/Synchronous_and_Asynchronous_Requests )
i am making a client for my node.js irc bot and want to implement tab complete but the regex in the following code returns null for no reason. i have included what's logged as comments next to the console.log statement.
what is tab complete: i type "mic" and press tab, it the automatically completes it to "michael" because he is a user in the channel.
tabStart = false;
$("#textbox").keydown(function (e) {
if (!$(this).val().length) return;
if (e.keyCode === 9) {
e.preventDefault();
var text = $(this).val();
console.log('text: ' + text);// mic
var index = text.lastIndexOf(" ");
console.log('index: ' + index);// -1
if (!tabStart) {
tabStart = index > -1 ? text.substr(index + 1) : text;
var current = '';
} else {
var current = index > -1 ? text.substr(index + 1) : text;
}
console.log('tabStart: ' + tabStart);// mic
console.log('current: ' + current);//
var active = $("#tabs").tabs("option", "active");
var channel = $("#tabs ul>li a").eq(active).attr("href");
console.log('channel: ' + channel);// #debug
var users = $(channel + " .user-list li");
var regex = new RegExp("^" + tabStart + ".*", "i");
console.log('regex: ' + regex);// /^mic.*/i
for (var i = 0; i < users.length; ++i) {
var user = $(users[i]).text();
console.log('user: ' + user);// michael
var match = user.match(regex);
console.log('match: ' + match);// null
if (match) {
var newText = (index > -1 ? text.substr(0, index + 1) : "") + user;
console.log('newText: ' + newText);
$(this).val(newText);
break;
}
}
} else {
tabStart = false;
}
});
as i said, i can't seem to find an explanation for this because i tried the following in the javascript console and it works
var regex = new RegExp("^mic.*", "i");"michael".match(regex);
It looks like you have an issue with getting the correct text from users. Since I don't know your actual HTML, I created a CodePen and commented out some of the channel lines and added users as a typical array. Doing that, your regex works fine.
Here is the codePen in action.
figured out the problem. user was wrapped in .
I will be printing two fields using for fields using for loop in javascript. First field is the name and second field is the link to download that file. This table will be generated dynamically. I want to keep a counter saying how many times a particular file is downloaded on the generated table.
for (i=0; i<resp.items.length; i++) {
var titulo = resp.items[i].title;
var fechaUpd = resp.items[i].modifiedDate;
var userUpd = resp.items[i].lastModifyingUserName;
var userEmbed = resp.items[i].embedLink;
var userAltLink = resp.items[i].alternateLink;
var download = resp.items[i].webContentLink;
var hold="Download";
var flag=0;
<!-- var fileInfo = document.createElement('li');
<!-- fileInfo.appendChild(document.createTextNode('TITLE: ' + titulo + ' - LAST MODIF: ' + fechaUpd + ' - BY: ' + userUpd +' url: ' + hold.link(download)));
<!-- document.getElementById('content').appendChild(fileInfo);
document.write(titulo + " ");
document.write(hold.link(download) + "<br>");
<!--flag=1;
}
<!--if(flag!=1){
<!--document.write("not found!");
<!--}
});