This is my first time doing much with anything but perl and vb so please bear with me.
I am able to compare two fields which need to match, and if they don't, then I need to hide HTML links completely. How would this be written?
This grabs the first userid
($("#trid").val());
($("#pxuserid").text());
var test = $("#pxuserid").text().indexOf("-");
var username = $("#pxuserid").text().substring(test + 1);
(username);
This grabs the second userid and changes it from all uppercase to lowercase.
($("[name=vsvadm]").val());
var str = $("[name=vsvadm]").text("checked", true).val().toLowerCase();
(str);
These are what I need to show/hide
<div class="pxcontent" id="sarea">
<div class="pxvtab" id="pxform">
<div class="pxvtablinks">
Directories
Accounting
Advanced
Security
I'm trying to get the script to say "If userid1 does not equal userid2, then hide Page 5, 6, and 7, but show only page 2, otherwise keep going"
Hopefully I didn't confuse anyone and someone could help out!
Give all the <a> tags a class:
Directories
Accounting
Advanced
Security
And then check for the condition and hide it:
if (userid1 != userid2)
$(".nav-links").hide();
Note: This should be really handled on the server side than the client side. Experienced users (and almost everyone now) can access the hidden elements by using the Dev Tools.
Assuming str and username are what you want to compare..
if(str !== username) $("a").hide();
This hides ALL links, as your question stated, but should not be used to prevent users from viewing them. If your links need to be secure then auth should be done on server side.
Also you can get rid of all the free-standing statements that you wrapped in perens. Those don't serve any purpose.
You need to compare the strings and then loop over the links
var username1 = 'username1'
var username2 = 'username2'
// Do compare
if (username1 !== username2) {
// Loop over the links
$.each($('.pxvtablinks a'), function() {
// If it doesn't have a rel attribute equal to '#page2'...
if ($(this).attr('rel') !== '#page2') {
// hide it.
$(this).hide()
}
})
}
Example: https://codepen.io/mark_c/pen/mAQwpE
Related
I need to retrieve all elements who's ID ends with "_inputError" from within a specific element! AND also , I need to retrieve only the inputError that has class 'b-block' set.. How would I do this using javascript/jquery ?
I know I can get my form node with: var formNode = $("#frm1");
I know I can get ALL elements with ID ending, but this will get them all, which isn't quite what I need: var inputErrors = $("[id$=_inputError]");.
How do I mix'em all together as to retrieve only the input errors with 'd-block' class from within a specified form node ?
Cheers!
UPDATE: This seems to work for me:
var inputErrors = $("[id$=_inputError].d-block");
console.warn(inputErrors[0]);
It'll retrieve all inputError with class .d-block. However, I've yet to find how to do this check ONLY from a selected form element id, instead of the hole page. (I can have multiple forms on a single page!)
To help others if it can, here's the final solution and why I needed this:
Essentially, I get a response back from an ajax post like so:
{
type: 2,
formid: 'frmProfile',
fields: {
username: "Invalid username!",
email: "Invalid email!"
}
}
I loop my response.fields to show the individual errors under each failed inputs.
I then needed to find a way set focus on the first failed input! Because my fields are NOT 0-indexed based, I could not simply set the focus on the first field in the array! They are 'randomly' looped through!
Therefor, I decided to get all input errors that we're showing (id=*_inputError and with class d-block). The first one in the returned array is in fact the first input error! So, I use its ID to determine the corresponding input name and set focus to it:
var inputErrors = $("#" + response.formid + " [id$=_inputError].d-block");
var firstInputError = inputErrors[0].id.replace(/_inputError$/, ''); // get just the name of the failed input! Its name/id should be the same as <name>_inputError!
document.getElementById(firstInputError).focus();
This seems to do the trick for me ;) Hopefully, this can serve ideas to others.
Thanks for your help folks!
P
I have an Array with one or more entries. Each one is a string (List of urls in open Tabs via Firefox SDK). I want to check if a specific url is already opened in some of the tabs (nothing special till now).
My problem is, that the url in tab list can have four diffrent fourms. For example:
Url I want to find in the tablist:
https://cmsr-author.de/cf#/content/test/de.html
But the url can also look like this:
https://cmsr-author.de/content/test/de.html
https://cmsr-author.de/test/de.html
https://cmsr-author.de/cf#/test/de.html
Of course the last part of the url (after /test/...) is always something diffrent. If I wasn't able to find one of the four urls in the tablist i want to call some other action.
My Solution till now is to build some if-chain:
if (res !== url1) {
if (res !== url2) {
if ...
But i thought there must be some more elegant way. Maybe via RegEx? I already have a capture to catch the first part (which stays the same https://cmsr-author.ws...) with it four forms. But i dont know how to implent this probably.
var urls = ["https://cmsr-author.de/content/test/de.html","https://cmsr-author.de/test/de.html","https://cmsr-author.de/cf#/test/de.html"]
var filtered = urls.filter(function(url)
{
return url.indexOf("cf#") > -1 && url.endsWith("/test/de.html")
})
var contains = filtered.length > 0
console.log(contains)
If you want to use regex you can do this by using groups for the middle part, which is explained in detail here: http://www.regular-expressions.info/refcapture.html
Practically, your regex would look something like that:
https:\/\/cmsr-author\.de\/(content|...|...)\/de\.html
Where ... must be replaced by the middle parts of the url which differ.
Note that | is "or" used to provide multiple possibilities within the group. The character / and . must be escaped since they have special roles in regex.
I hope that helps!
My English is not good,Do not fully understand what you mean,According to my idea,You should need a regular expression,Only to match the first.If I am wrong,
please # me.
I hope that helps!
var reg = /^https:\/\/cmsr\-author\.de\/cf#\/(?:\w+\/)+test\/de\.html$/gi;
var str1 = "https://cmsr-author.de/cf#/content/test/de.html";
var str2 = "https://cmsr-author.de/content/test/de.html";
var str3 = "https://cmsr-author.de/test/de.html";
var str4 = "https://cmsr-author.de/cf#/test/de.html";
console.log(reg.test(str1));
console.log(reg.test(str2));
console.log(reg.test(str3));
console.log(reg.test(str4));
Need help! I've been looking for a solution for this seemingly simple task but can't find an exact one. Anyway, I'm trying to add custom #id to the tag based on the page's URL. The script I'm using works ok when the URLs are like these below.
- http://localhost.com/index.html
- http://localhost.com/page1.html
- http://localhost.com/page2.html
-> on this level, <body> gets ids like #index, #page1, #page2, etc...
My question is, how can I make the body #id still as #page1 or #page2 even when viewing subpages like this?
- http://localhost.com/page1/subpage1
- http://localhost.com/page2/subpage2
Here's the JS code I'm using (found online)
$(document).ready(function() {
var pathname = window.location.pathname;
var getLast = pathname.match(/.*\/(.*)$/)[1];
var truePath = getLast.replace(".html","");
if(truePath === "") {
$("body").attr("id","index");
}
else {
$("body").attr("id",truePath);
}
});
Thanks in advance!
edit: Thanks for all the replies! Basically I just want to put custom background images on every pages based on their body#id. >> js noob here.
http://localhost.com/page2/subpage2 - > my only problem is how to make the id as #page2 and not #subpage2 on this link.
Using the javascript split function might be of help here. For example (untested, but the general idea):
var url = window.location.href.replace(/http[s]?:\/\//, '').replace('.html', '');
var segments = url.split('/');
$('body').id = segments[0];
Also, you might want to consider using classes instead of ID's. This way you could assign every segment as a class...
var url = window.location.href.replace(/http[s]?:\/\//, '').replace('.html', '');
var segments = url.split('/');
for (var i = 0; i < segments.length; i++) {
$('body').addClass(segments[i]);
}
EDIT:
Glad it worked. Couple of notes if you're planning on using this for-real: If you ever have an extension besides .html that will get picked up in the class name. You can account for this by changing that replace to a regex...
var url = window.location.href.replace(/http[s]?:\/\//, '');
// Trim extension
url = url.replace(/\.(htm[l]?|asp[x]?|php|jsp)$/,'');
If there will ever be querystrings on the URL you'll want to filter those out too (this is the one regex I'm not 100% on)...
url = url.replace(/\?.+$/,'');
Also, it's a bit inefficient to have the $('body') in every for loop "around" as this causes jQuery to have to re-find the body tag. A more performant way to do this, especially if the sub folders end up 2 or 3 deep would be to find it once, then "cache" it to a variable like so..
var $body = $('body');
for ( ... ) {
$body.addClass( ...
}
Your regex is only going to select the last part of the url.
var getLast = pathname.match(/./(.)$/)[1];
You're matching anything (.*), followed by a slash, followed by anything (this time, capturing this value) and then pulling out the first match, which is the only match.
If you really want to do this (and I have my doubts, this seems like a bad idea) then you could just use window.location.pathname, since that already has the fullpath in there.
edit: You really shouldn't need to do this because the URL for the page is already a unique identifier. I can't really think of any situation where you'd need to have a unique id attribute for the body element on a page. Anytime where you're dealing with that content (either from client side javascript, or from a scraper) you should already have a unique identifier - the URL.
What are you actually trying to do?
Try the following. Basically, it sets the id to whatever folder or filename appears after the domain, but won't include a file extension.
$(document).ready(function() {
$("body").attr("id",window.location.pathname.split("/")[1].split(".")[0]);
}
You want to get the first part of the path instead of the last:
var getFirst = pathname.match(/^\/([^\/]*)/)[1];
If your pages all have a common name as in your example ("page"), you could modify your script including changing your match pattern to include that part:
var getLast = pathname.match(/\/(page\d+)\//)[1];
The above would match "page" followed by a number of digits (omitting the 'html' ending too).
Ok, I'm a bit of a n00b when it comes to JS (I'm not the greatest programmer) so please be gentle - specially if my questions been asked already somewhere and I'm too stupid to find the right answer. Self deprecation out of the way, let's get to the question.
Problem
There is a site me and a large group of friends frequently use which doesn't display all the information we may like to know - in this case an airline bookings site and the class of travel.
While the information is buried in the code of the page, it isn't displayed anywhere to the user.
Using a Greasemonkey script, I'd like to liberate this piece of information and display it in a suitable format.
Here's the psuedocode of what I'm looking to do.
Search dom for specified element
define variables
Find a string of text
If found
Set result to a variable
Write contents to page at a specific location (before a specified div)
If not found
Do nothing
I think I've achieved most of it so far, except for the key bits of:
Searching for the string: The page needs to search for the following piece of text in the page HEAD:
mileageRequest += "&CLASSES=S,S-S,S-S";
The Content I need to extract and store is between the second equals (=) sign and the last comma ("). The contents of this area can be any letter between A-Z.
I'm not fussed about splitting it up into an array so I could use the elements individually at this stage.
Writing the result to a location: Taking that found piece of text and writing it to another location.
Code so far
This is what I've come up so far, with bits missing highlighted.
buttons = document.getElementById('buttons');
''Search goes here
var flightClasses = document.createElement("div");
flightClasses.innerHTML = '<div id="flightClasses"> ' +
'<h2>Travel classes</h2>' +
'For the above segments, your flight classes are as follows:' +
'write result here' +
'</div>';
main.parentNode.insertBefore(flightClasses, buttons);
If anyone could help me, or point me in the right direction to finish this off I'd appreciate it.
The Content I need to extract and store is between the second equals (=) sign and the last comma (").
Do you mean "is between the second equals (=) sign and the last quote (")"?
And I assume that this:
mileageRequest += "&CLASSES=S,S-S,S-S";
is in a script tag?
If so then it looks like there will be a JS variable on the page called mileageRequest which you can access from Greasemonkey with unsafeWindow.mileageRequest and assuming that you can access the data you want with something like:
// check that the mileageRequest variable exists
if(unsafeWindow.mileageRequest){
// it exists
var myString = unsafeWindow.mileageRequest.match(/&CLASSES=([^&=]*)/i);
if(myString){
// my string exists
myString = myString[1];
}
else{
// my sting does not exist
}
}
else {
// it does not exist
}
or you can try:
var myString = document.getElementsByTagName('head')[0].innerHTML.match(/mileageRequest\s*\+=\s*"&CLASSES=([^"]*)";/i);
if(myString){
// my string exists
myString = myString[1];
}
else{
// my string does not exist
}
I'm writing a bookmarklet, i.e. a bookmark that contains javascript instead of a URL, and I have some trouble. In fact, I cannot remember how I can get the content of the page as a string, so I can apply a regular expression to find what I want. Can you please help me on this?
Before anyone suggests it, I cannot use getElementBy(Id/Name/Tag), because the data I'm looking for is HTML-commented and inside markups, so I don't think that would work.
Thanks.
You can access it through:
document.body.innerHTML
so I can apply a regular expression to find what I want
Do. Not. Use. Regex. To. Parse. HTML.
Especially when the browser has already parsed it for you! Come ON!
the data I'm looking for is HTML-commented
You can perfectly well grab comment content out of the DOM. eg.
<div id="mything"><!-- la la la I'm a big comment --></div>
alert(document.getElementById('mything').firstChild.data);
And if you need to search the DOM for comment elements:
// Get comment descendents
//
function dom_getComments(parent, recurse) {
var results= [];
for (var childi= 0; childi<parent.childNodes.length; childi++) {
var child= parent.childNodes[childi];
if (child.nodeType==8) // Node.COMMENT_NODE
results.push(child);
else if (recurse && child.nodeType==1) // Node.ELEMENT_NODE
results= results.concat(dom_getComments(child));
}
return results;
}