Select word next to symbol - javascript

I have jquery code on keypress 35 which is # to dropdown div. I need to get the word that is standing next to # e.g.
<textarea></textarea> And I type #Michael I want to store #Michael in var name
After making an ajax request to check if Michael exists in the database and if it does, echo it inside dropdown div. After what I click on some from the list and replace it with name and # before name like if I got result:
Michael Parker and click on this one to replace this one with name value.
I need to select word that is typed with #
[Q] how to select the word that is standing next to #?

Try this:
function getName(){
var t = document.getElementsByTagName('textarea')[0].value;
var name = t.split(' ');
name.forEach(function(str){
if(str[0] === '#') {
return str;
}
});
}
I used this for test
<textarea>asjdaksdjans #hacj asdasd</textarea>
<button onclick="getName()">find</button>
I hope this is what you wanted.
EDIT
function getName(){
var t = document.getElementsByTagName('textarea')[0].value;
if(t[t.length-1]=== ' '){
var name = t.split(' ');
name.forEach(function(str){
if(str[0] === '#') {
console.log(str);
}
});
}
}
For test:
<textarea onkeyup="getName()">asjdaksdjans #hacj asdasd</textarea>
EDIT
jQuery(function($){
$('textarea').on('keyup', function(event){
var text = $(this).val();
if(text[text.length-1]=== ' ') {
var name = text.split(' ');
$.each(name, function(i, str) {
console.log(i, str);
if(str[0] === "#") {
alert('name is:' +str);
}
});
}
});
});

This is working example. Note that you cannot 'getvalue' from event handler. But you can call action from that handler.
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title></title>
<script src="https://ajax.aspnetcdn.com/ajax/jquery/jquery-2.1.4.min.js" type="text/javascript"></script>
<script type="text/javascript">
$(document).ready(function () {
var capName = '';
var capStart = false;
$('#txt').keypress(function (e) {
if (e.key == '#') {
capStart = true;
capName = '';
}
if (capStart && /[a-z0-9_#-]/i.test(e.key)) {
capName += e.key;
}
if (capStart && !/[a-z0-9_#-]/i.test(e.key)) {
capStart = false;
doSomething(capName);
}
});
function doSomething(text) {
$('#result').html(capName);
}
});
</script>
</head>
<body>
<textarea id="txt"></textarea><br />
<div id="result"></div>
</body>
</html>

Related

My JS to retrieve querystring params isn't working, any ideas why?

I'm trying to get a simple example of using js to retrieve querystring params working and it's not (even though I said simple).
Here's my code:
I've tried putting alert statements in and debugging the old fashioned way but to be honest I'm used to using VS2017 for c# not js
Here's the code I'm using.
I have 2 html pages, the first just has a link:
try me
The second has the code:
this is some text <br />
<script> getparams2();</script>
this is some more text <br />
<script>
function getUrlParam(parameter, defaultvalue) {
var urlparameter = defaultvalue;
if (window.location.href.indexOf(parameter) > -1) {
urlparameter = getUrlVars()[parameter];
}
return urlparameter;
}
</script>
<script>
function getUrlVars() {
var vars = {};
var parts = window.location.href.replace(/[?&]+([^=&]+)=([^&]*)/gi, function (m, key, value) {
alert(value);
vars[key] = value;
});
return vars;
}
</script>
<script>
function getparams2()
{
var mytext = getUrlVars()["type"];
}
</script>
The result I'm trying to acheive is that the h1.html page can display the type parameter from the url.
Thanks in advance,
Paul.
Your code works. You just need to execute it when the document is ready also you need to return something or update your page to see the results.
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js">
</script>
</head>
<body>
<div id="params"> Printing The URL Params here</div>
<script type="text/javascript">
$( document ).ready(function() {
getparams2();
function getUrlParam(parameter, defaultvalue) {
var urlparameter = defaultvalue;
if (window.location.href.indexOf(parameter) > -1) {
urlparameter = getUrlVars()[parameter];
}
return urlparameter;
}
function getUrlVars() {
var vars = {};
var parts = window.location.href.replace(/[?&]+([^=&]+)=([^&]*)/gi, function
(m, key, value) {
alert(value);
vars[key] = value;
});
return vars;
}
function getparams2()
{
var mytext = getUrlVars()["type"];
//console.log(mytext);
$('#params').text(mytext);
}
});
</script>
</body>
</html>
I would do it the following way:
URL-Param function
function getUrlParam(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]; }
};
Call from your getParams2
function getParams2(){
return getUrlParam('type');
};
getParams2 will return the value of the param if it is in the URL.

both jQuery and $ is not a function

I already imported
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
under the head section. But still I got,
RelatedObjectLookups.js:142 Uncaught TypeError: $ is not a function
at RelatedObjectLookups.js:142
at RelatedObjectLookups.js:175
(anonymous) # RelatedObjectLookups.js:142
(anonymous) # RelatedObjectLookups.js:175
(index):177 Uncaught TypeError: $ is not a function
at (index):177
Relavant html looks like,
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script crossorigin="anonymous" integrity="sha384-ApNbgh9B+Y1QKtv3Rn7W3mgPxhU9K/ScQsAP7hUibX39j7fakFPskvXusvfa0b4Q" src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.12.9/umd/popper.min.js"></script>
<script crossorigin="anonymous" integrity="sha384-JZR6Spejh4U02d8jOt6vLEHfe/JQGiRRSQQxSfFWpi1MquVdAyjUar5+76PVCmYl" src="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/js/bootstrap.min.js"></script>
<link crossorigin="anonymous" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css" integrity="sha384-Gn5384xqQ1aoWXA+058RXPxPg6fy4IWvTNh0E263XmFcJlSAwiGgFAW/dAiS6JXm" rel="stylesheet">
</head>
<body>
<script type="text/javascript" src="/admin/jsi18n/"></script>
<script type="text/javascript" src="/static/admin/js/core.js"></script>
<script type="text/javascript" src="/static/admin/js/admin/RelatedObjectLookups.js"> </script>
<script type="text/javascript" src="/static/admin/js/jquery.init.js"></script>
<script type="text/javascript" src="/static/admin/js/actions.min.js"></script>
<script type="text/javascript" src="/static/admin/js/calendar.js"></script>
<script type="text/javascript" src="/static/admin/js/admin/DateTimeShortcuts.js"></script>
{{form.media}}
<div class="row">
<div class="col-6">
<form method="post" id="extendTrialForm" class="form">
{% csrf_token %}
{% bootstrap_field form.user %}
{% bootstrap_field form.core_instance %}
{% bootstrap_field form.expiry_datetime %}
{% buttons %}
<button type="submit" class="btn btn-primary">Submit</button>
{% endbuttons %}
</form>
</div>
</div>
<script>
$( document ).ready(function() { // line no 177
Removing the script tags above {{form.media}} won't throw any error related to jquery but it misses the widget functionality. I need that script tags but I don't want Jquery to return $ is not a function. I have tried adding $.noconflict, jQuery(document).ready but nothing works.
RelatedObjectsLookups.js
/*global SelectBox, interpolate*/
// Handles related-objects functionality: lookup link for raw_id_fields
// and Add Another links.
(function($) {
'use strict';
// IE doesn't accept periods or dashes in the window name, but the element IDs
// we use to generate popup window names may contain them, therefore we map them
// to allowed characters in a reversible way so that we can locate the correct
// element when the popup window is dismissed.
function id_to_windowname(text) {
text = text.replace(/\./g, '__dot__');
text = text.replace(/\-/g, '__dash__');
return text;
}
function windowname_to_id(text) {
text = text.replace(/__dot__/g, '.');
text = text.replace(/__dash__/g, '-');
return text;
}
function showAdminPopup(triggeringLink, name_regexp, add_popup) {
var name = triggeringLink.id.replace(name_regexp, '');
name = id_to_windowname(name);
var href = triggeringLink.href;
if (add_popup) {
if (href.indexOf('?') === -1) {
href += '?_popup=1';
} else {
href += '&_popup=1';
}
}
var win = window.open(href, name, 'height=500,width=800,resizable=yes,scrollbars=yes');
win.focus();
return false;
}
function showRelatedObjectLookupPopup(triggeringLink) {
return showAdminPopup(triggeringLink, /^lookup_/, true);
}
function dismissRelatedLookupPopup(win, chosenId) {
var name = windowname_to_id(win.name);
var elem = document.getElementById(name);
if (elem.className.indexOf('vManyToManyRawIdAdminField') !== -1 && elem.value) {
elem.value += ',' + chosenId;
} else {
document.getElementById(name).value = chosenId;
}
win.close();
}
function showRelatedObjectPopup(triggeringLink) {
return showAdminPopup(triggeringLink, /^(change|add|delete)_/, false);
}
function updateRelatedObjectLinks(triggeringLink) {
var $this = $(triggeringLink);
var siblings = $this.nextAll('.change-related, .delete-related');
if (!siblings.length) {
return;
}
var value = $this.val();
if (value) {
siblings.each(function() {
var elm = $(this);
elm.attr('href', elm.attr('data-href-template').replace('__fk__', value));
});
} else {
siblings.removeAttr('href');
}
}
function dismissAddRelatedObjectPopup(win, newId, newRepr) {
var name = windowname_to_id(win.name);
var elem = document.getElementById(name);
if (elem) {
var elemName = elem.nodeName.toUpperCase();
if (elemName === 'SELECT') {
elem.options[elem.options.length] = new Option(newRepr, newId, true, true);
} else if (elemName === 'INPUT') {
if (elem.className.indexOf('vManyToManyRawIdAdminField') !== -1 && elem.value) {
elem.value += ',' + newId;
} else {
elem.value = newId;
}
}
// Trigger a change event to update related links if required.
$(elem).trigger('change');
} else {
var toId = name + "_to";
var o = new Option(newRepr, newId);
SelectBox.add_to_cache(toId, o);
SelectBox.redisplay(toId);
}
win.close();
}
function dismissChangeRelatedObjectPopup(win, objId, newRepr, newId) {
var id = windowname_to_id(win.name).replace(/^edit_/, '');
var selectsSelector = interpolate('#%s, #%s_from, #%s_to', [id, id, id]);
var selects = $(selectsSelector);
selects.find('option').each(function() {
if (this.value === objId) {
this.textContent = newRepr;
this.value = newId;
}
});
win.close();
}
function dismissDeleteRelatedObjectPopup(win, objId) {
var id = windowname_to_id(win.name).replace(/^delete_/, '');
var selectsSelector = interpolate('#%s, #%s_from, #%s_to', [id, id, id]);
var selects = $(selectsSelector);
selects.find('option').each(function() {
if (this.value === objId) {
$(this).remove();
}
}).trigger('change');
win.close();
}
// Global for testing purposes
window.id_to_windowname = id_to_windowname;
window.windowname_to_id = windowname_to_id;
window.showRelatedObjectLookupPopup = showRelatedObjectLookupPopup;
window.dismissRelatedLookupPopup = dismissRelatedLookupPopup;
window.showRelatedObjectPopup = showRelatedObjectPopup;
window.updateRelatedObjectLinks = updateRelatedObjectLinks;
window.dismissAddRelatedObjectPopup = dismissAddRelatedObjectPopup;
window.dismissChangeRelatedObjectPopup = dismissChangeRelatedObjectPopup;
window.dismissDeleteRelatedObjectPopup = dismissDeleteRelatedObjectPopup;
// Kept for backward compatibility
window.showAddAnotherPopup = showRelatedObjectPopup;
window.dismissAddAnotherPopup = dismissAddRelatedObjectPopup;
$(document).ready(function() {
$("a[data-popup-opener]").click(function(event) {
event.preventDefault();
opener.dismissRelatedLookupPopup(window, $(this).data("popup-opener"));
});
$('body').on('click', '.related-widget-wrapper-link', function(e) {
e.preventDefault();
if (this.href) {
var event = $.Event('django:show-related', {href: this.href});
$(this).trigger(event);
if (!event.isDefaultPrevented()) {
showRelatedObjectPopup(this);
}
}
});
$('body').on('change', '.related-widget-wrapper select', function(e) {
var event = $.Event('django:update-related');
$(this).trigger(event);
if (!event.isDefaultPrevented()) {
updateRelatedObjectLinks(this);
}
});
$('.related-widget-wrapper select').trigger('change');
$('body').on('click', '.related-lookup', function(e) {
e.preventDefault();
var event = $.Event('django:lookup-related');
$(this).trigger(event);
if (!event.isDefaultPrevented()) {
showRelatedObjectLookupPopup(this);
}
});
});
})(django.jQuery);
I’m pretty sure your whole problem is that the very end of your RelatedObjectsLookups.js JS file says django.jQuery, which doesn’t exist (or at least, the googleapis jQuery file you’re loading in isn’t going to define that). Change it to window.jQuery and things should work for you.
EDIT based on your reply
Since you can’t change the line that says django.jQuery, then let’s define that.
Right after you include your jQuery file, add the following tag.
<script>
django = django || {};
django.jQuery = django.jQuery || jQuery;
</script>
This will set django.jQuery to jQuery (which is included by your googleapis file), if it’s not been set yet. Now it will exist for your later scripts to use.

How to return contents of php using javascript $.get

I have a PHP script hosted in the root of a working LAMP server which provides me with the output of a MySQL query. The typical output of values.php:
2017-01-12 22:02:17/12/2017-01-12 22:03:18/12/2017-01-12
22:04:18/12/2017-01-12 22:05:18/12/2017-01-12 22:06:18/12/2017-01-12
22:07:19/12/2017-01-12 22:08:19/12/2017-01-12 22:09:19/12/2017-01-12
22:10:20/12/2017-01-12 22:11:20/12/2017-01-12 22:12:20/12/2017-01-12
22:13:21/12/2017-01-12 22:14:21/12/2017-01-12 22:15:21/12/2017-01-12
22:16:21/12/2017-01-12 22:17:22/12/2017-01-12 22:18:22/11/2017-01-12
22:19:22/11/2017-01-12 22:20:23/12/2017-01-12 22:21:23/11/2017-01-12
22:22:23/11/2017-01-12 22:23:24/11/2017-01-12 22:24:24/11/2017-01-12
22:25:24/11/2017-01-12 22:26:25/11/2017-01-12 22:27:25/11/2017-01-12
22:28:25/11
I am trying to use $.get to break it up and list it on a page. My code is as follows but it won't work:
<!DOCTYPE html>
<html>
<body>
<script>
function() {
var switch1 = true;
$.get('values.php', function(data) {
data = data.split('/');
for (var i in data)
{
if (switch1 == true)
{
document.write(data[i] + " Temp: ");
switch1 = false;
}
else
{
document.writeln(data[i]);
switch1 = true;
}
}
});
};
</script>
</body>
</html>
Any ideas where I am going wrong?
I should have added the code <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.2.4/jque‌​ry.min.js"></script> in the html. Final code is as follows and works fine:
<!DOCTYPE html>
<html>
<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js" type="text/javascript"></script>
</head>
<body>
<script>
var switch1 = true;
$.get('values.php', function(data) {
data = data.split('/');
for (var i in data)
{
if (switch1 == true)
{
document.write(data[i] + " Temp: ");
switch1 = false;
}
else
{
document.write(data[i] + "<br>");
switch1 = true;
}
}
});
</script>
</body>
</html>
Thanks to all.
I don't know what your PHP script actually returns but if I store manually to data it seems to work the way you expected. Can you explain what exactly does not work?
I would shorten code bit though:
var switch1 = true;
var data = "2017-01-12 22:02:17/12/2017-01-12 22:03:18/12/2017-01-12 22:04:18/12/2017-01-12 22:05:18/12/2017-01-12 22:06:18/12/2017-01-12 22:07:19/12/2017-01-12 22:08:19/12/2017-01-12 22:09:19/12/2017-01-12 22:10:20/12/2017-01-12 22:11:20/12/2017-01-12 22:12:20/12/2017-01-12 22:13:21/12/2017-01-12 22:14:21/12/2017-01-12 22:15:21/12/2017-01-12 22:16:21/12/2017-01-12 22:17:22/12/2017-01-12 22:18:22/11/2017-01-12 22:19:22/11/2017-01-12 22:20:23/12/2017-01-12 22:21:23/11/2017-01-12 22:22:23/11/2017-01-12 22:23:24/11/2017-01-12 22:24:24/11/2017-01-12 22:25:24/11/2017-01-12 22:26:25/11/2017-01-12 22:27:25/11/2017-01-12 22:28:25/11"
data = data.split('/').map(function(i){
document.write(i + (switch1 ? " Temp: " : ""));
switch1 = !switch1;
});
Give this a try, should do what you are looking for...
var content = "2017-01-12 22:02:17/12/2017-01-12 22:03:18/12/2017-01-12 22:04:18/12/2017-01-12 22:05:18/12/2017-01-12 22:06:18/12/2017-01-12 22:07:19/12/2017-01-12 22:08:19/12/2017-01-12 22:09:19/12/2017-01-12 22:10:20/12/2017-01-12 22:11:20/12/2017-01-12 22:12:20/12/2017-01-12 22:13:21/12/2017-01-12 22:14:21/12/2017-01-12 22:15:21/12/2017-01-12 22:16:21/12/2017-01-12 22:17:22/12/2017-01-12 22:18:22/11/2017-01-12 22:19:22/11/2017-01-12 22:20:23/12/2017-01-12 22:21:23/11/2017-01-12 22:22:23/11/2017-01-12 22:23:24/11/2017-01-12 22:24:24/11/2017-01-12 22:25:24/11/2017-01-12 22:26:25/11/2017-01-12 22:27:25/11/2017-01-12 22:28:25/11";
var regexp = /(\d{4}-\d{2}-\d{2}\s+\d{2}:\d{2}:\d{2})\/(\d{2})/g;
var matches;
while ( matches = regexp.exec( content ) ) {
document.write( matches[1] + " Temp: " + matches[2] + "<br/>");
}
Hope this helps!

Better code for checking Duplicate in String Array

I have following code for checking whether there is duplicate in an array. The code works fine. But it uses a new array named newUniqueArray. Is there a better code for this purpose without using a new array? Is there any optimization possible on this code?
Note: I have used inArray and in keywords from jQuery
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title></title>
<script type="text/javascript" src="http://ajax.aspnetcdn.com/ajax/jquery/jquery-1.4.1.js"></script>
<script type="text/javascript">
$(document).ready(function () {
$('#btnSave').click(function (e) {
var reportRecipients = "A, a , b,";
reportRecipients = reportRecipients.toLowerCase();
checkDuplicate(reportRecipients);
});
function checkDuplicate(reportRecipients) {
if (reportRecipients.length > 1) {
var recipientsArray = reportRecipients.split(',');
var newUniqueArray = [];
for (a in recipientsArray) {
var email = $.trim(recipientsArray[a]);
if ($.inArray(email, newUniqueArray) == -1) {
newUniqueArray.push(email);
}
}
if (newUniqueArray.length < recipientsArray.length) {
alert('Duplicate Exists');
}
return false;
}
}
});
</script>
</head>
<body>
<input name="txtName" type="text" id="txtName" />
<input type="submit" name="btnSave" value="Save" id="btnSave" />
</body>
</html>
If you just want to test on string arrays, you can use a JavaScript object's property to test. It used a hash-table to look up properties, which is faster than array iteration.
example: http://jsfiddle.net/jmDEZ/8/
function checkDuplicate(reportRecipients) {
var recipientsArray = reportRecipients.split(','),
textHash = {};
for(var i=0; i<recipientsArray.length;i++){
var key = $.trim(recipientsArray[i].toLowerCase());
console.log("lower:" + key);
if(textHash[key]){
alert("duplicated:" + key);
return true;
}else{
textHash[key] = true;
}
}
alert("no duplicate");
return false;
}​
I can't see any reason to use jQuery for this purpose:
checkDuplicate = function (reportRecipients) {
if (reportRecipients.length > 1) {
var recipientsArray = reportRecipients.split(',');
for (a in recipientsArray) {
if(reportRecipients.indexOf(a) != reportRecipients.lastIndexOf(a)){
return true;
}
}
}
return false;
}
$('#btnSave').click(function (e) {
var reportRecipients = "A, a , b,";
reportRecipients = reportRecipients.toLowerCase();
if(checkDuplicate(reportRecipients)) alert('Duplicate Exists');
});

How do I control the font weight of any text within a paragraph (<p> tag) within braces or curly brackets { } using JavaScript

I would like to be able to control the font-weight of text if bracketed inside a p tag using JavaScript.
For instance:
The cow jumped over the {moon}. font-weight within {} would be increased.
This so the end user can type this into a text area and on submit the would print to page altering the font-weight within the braces or curly brackets.
Any help on this would be great.
Here is how you can do this:
var ps = document.getElementsByTagName('p');
foreach = Array.prototype.forEach;
foreach.call(ps, function (p) {
var content = p.innerHTML;
p.innerHTML = content.replace(/\{(.*?)\}|\((.*?)\)/g, function (m) {
return '<span style="font-weight: bold;">' + m + '</span>';
});
});
​
And of course a fiddle.
For the example you need just pure JavaScript, no additional libraries.
Edit:
If you don't want to see the brackets in the result you can use:
var ps = document.getElementsByTagName('p');
foreach = Array.prototype.forEach;
foreach.call(ps, function (p) {
var content = p.innerHTML;
p.innerHTML = content.replace(/\((.*?)\)|\{(.*?)\}/g, function (m) {
return '<span style="font-weight: bold;">' + m.replace(/[\(\)\{\}]/g, '') + '</span>';
});
});
Fiddle: http://jsfiddle.net/ma47D/4/
​
Best regards!
You can do it with mootools like this:
window.addEvent('domready', function()
{
$$('P').each(function(p)
{
p.set('html', p.get('text').replace(/{([^\}]*)*}/g,"<b>$1</b>"));
});
});​
domready is important because it must be done after page is completely loaded. converting to jquery would not be so hard.
http://jsfiddle.net/Smw7Q/1/
Locally you can handle it like this:
<!DOCTYPE html>
<html>
<head>
<script>
function transfer(){
document.getElementById("result").innerHTML=document.getElementById("demo").value.replace(/{/g,'<strong>').replace(/}/g,'</strong>');
}
</script>
</head>
<body>
Input: <input type="text" name="input" id="demo"><br>
<input type="button" value="Submit" onclick="transfer();">
<p id="result"></p>
</body>
</html>
If you submit the text to server, the magic can be done similarly at server side.
My suggestion
<!DOCTYPE html>
<html>
<head>
<style>
p span {
font-size:1.5em;
}
</style>
<script>
function regex(){
document.getElementById("output").innerHTML=
document.getElementById("input").value.replace(/{(.*?)}/g, "<span>$1</span>");
};
</script>
</head>
<body>
<p id="output"></p>
<textarea id="input" rows="30" cols="80"></textarea>
<input type="button" value="Input" onclick="regex();"/>
</body>
<html>
Of course, prior to submitting, you need to sanitize your data.
If tried something, but I'm sure there are more elegant solutions.
http://jsfiddle.net/xT7Fg/
$(document).ready(function(){
$(tb).blur(function(){
var str = '';
var nextFont = 0;
$.each($(tb).val(),function(i,char){
if(nextFont == 0){
if(char == '{'){
if($(tb).val().indexOf(i,'}')){
str += '<font size="15">';
nextFont = $(tb).val().indexOf('}', i);
} else {
str += char;
}
} else {
str += char;
}
} else if (nextFont === i) {
str += '</font>';
nextFont = 0;
} else {
str += char;
}
});
$("#txt").html(str);
});
});

Categories

Resources