Better code for checking Duplicate in String Array - javascript

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');
});

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.

Use slice(); method to achieve an arithmetic operation

My aim is to use a single input to collect numbers and strings then use it to determine a math operation.
For example, I parse in values such as √64 intending to find the square root of 64. Knowing that this is no valid javascript, so I decided to get the first character with result[0]; which is "√" and then slice out the remaining values with result.slice(1); which is "64", then when the condition that result[0] == "√" is true then Math.sqrt(sliceVal) . This seems perfect and runs well in a mobile editor, but doesn't run in any web browser.
function actn() {
var input = document.getElementById("input").value;
var display = document.getElementById("display");
var result = input.toString();
var firstVal = result[0];
if (firstVal == "√") {
var sliceVal = result.slice(1);
display.innerHTML = Math.sqrt(sliceVal);
}
}
I do not know why It is not running at your end but It is working perfectly according to your requirement I tested above code :)
<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script>
function actn() {
var input = document.getElementById("test").value;
var result = input.toString();
var firstVal = result[0];
if (firstVal == "√") {
var sliceVal = result.slice(1);
alert(Math.sqrt(sliceVal));
}
alert("No match found");
}
</script>
</head>
<body>
<input type="text" id="test" />
<button type="button" onclick="actn()">Test</button>
</body>
</html>
Checking ASCII value instead of character comparison should work.
<html>
<body>
<input type="text" id="input" />
<button type="button" id="sqrRoot">Square Root</button>
<h1 id="display"></h1>
<script>
function actn() {
var input = document.getElementById("input").value;
var display = document.getElementById("display");
var result = input.toString();
var firstVal = result[0];
/* Ascii value for √ is 8730 */
if (firstVal.charCodeAt(0) === 8730) {
var sliceVal = result.slice(1);
display.innerHTML = Math.sqrt(sliceVal);
}
}
document.getElementById("sqrRoot").addEventListener("click", function () {
actn();
});
</script>
</body>
</html>

Iterating through tabs to search for string

I am working on a function for a Chrome extension, and I need some help debugging.
The function should get a user's String input from a popup.html text box, and look through all the tabs in the current window to see if the String input is present in any of the tabs. Finally, I give an alert telling the user which tab(s) (indices: 0, 1, ...) the string was found in.
background.js
//searches all tabs for the input string
function searchEverywhere(searchString) {
var indices = [];
chrome.tabs.query({}, function(tabs) {
var numOfTabs = tabs.length;
for(i = 0; i < numOfTabs; i++) {
chrome.tabs.update(tabs[i].id, updateProperties, function(tab) {
if(getText().indexOf(searchString) > -1) {
indices.push(i);
}
});
}
});
return indices;
}
function makeAlert(pagesFound) {
alert("Your input was found on tabs: " + pagesFound.toString());
}
function getText() {
return document.body.innerText;
}
popup_script.js
document.addEventListener("DOMContentLoaded", function() {
var backgroundPage = chrome.extension.getBackgroundPage();
document.querySelector('#btnSearch').addEventListener('click', function() {
var searchString = document.querySelector('#textToSearch');
var pagesFound = backgroundPage.searchEverywhere(String(searchString.value));
backgroundPage.makeAlert(pagesFound);
});
});
popup.html
<!DOCTYPE html>
<html>
<head>
<title>Work with tabs</title>
<script src="popup_script.js"></script>
</head>
<body><div class="searchEverywhere">
Search all tabs for word:<br>
<input type="text" name="textToSearch" id="textToSearch">
<br>
<input type="button" id="btnSearch" value="Search">
</div>
</body>
</html>
Using chrome.tabs.executeScript we can retrieve the innerText of the tab.
background.js
function searchEverywhere(searchPhrase, callback) {
chrome.tabs.query({
//query only tabs that you have enabled permissions for or you will get errors in console
}, tabs => {
let foundInTabIds = [];
for (let tab of tabs) {
chrome.tabs.executeScript(tab.id, {
code: `document.body.innerText`
}, (results => {
if (results && results.length > 0) {
let tabText = results[0];
if(tabText.indexOf(searchPhrase) > -1) {
foundInTabIds.push(tab.id);
}
}
}));
}
setTimeout(() => {
//your alert
callback(foundInTabIds);
}, 2000);
});
}
popup.js
...
var pagesFound = backgroundPage
.searchEverywhere(String(searchString.value), backgroundPage.makeAlert);
...
For simplicity, I use setTimeout, but that's not an optimal way to wait for all callbacks to complete. I suggest using promises.

Select word next to symbol

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>

Categories

Resources