check if a string in the address bar matches an li id - javascript

I need to check if my address has any words that matches word in my li id:
<ul>
<li id="filter-myId" class="noSelected">Text</li>
</ul>
url address example to check:
http://www_link.com/D=.myId
But on the window address bar it'd only display "myId" without "filter-", so I guess I need to check if whatever is after "filter-" matches a string which appears on the windows address. If so, the li would get a class "selected"
Help?

I'd suggest, though currently untested, something along the lines of:
var string = document.location.href.split('=')[1];
if ($('li[id*="' + string + '"]').length){
$('li[id*="' + string + '"]').addClass('selected');
}
To restrict the search to those li elements that have the filter- prefix:
var string = document.location.href.split('=')[1];
if ($('li[id^="filter-"][id*="' + string + '"]').length){
$('li[id^="filter-"][id*="' + string + '"]').addClass('selected');
}
References:
Attribute-contains ([attribute*="value"]) selector.
Attribute-starts-with ([attribute^="value"]) selector.

You'll need to parse the URL somehow. I'm leaving that part out, but assuming it is placed in an object called url.
Javascript
if (elem = document.getElementById('filter-' + url['D'])) {
// exists
elem.className += ' selected';
}
jQuery
elem = $('#filter-' + url['D']);
if (elem.length) {
// exists
elem.addClass('selected');
}

Related

Regular expression to convert html class to attribute

Is there any way to use regular expression alone or with help of javascript to do the following
from
<div class="type-c red blue">
to
<div type="c" class="red blue">
This isn't the solution. Just offers some insights on text parsing this problem without regex. As the OP did mention a possible non-regex solution. Also this answer was posted during a very long comment session, and as such requirements changed.
This solution (in like fashion of #DakotaMethvin's) also attempts to solve it without regex, and as well, resides on a more exact pattern match with class="type-. As such the following code will indeed break (logically) if that's not the match.
However in light of FanCheung's more recent comment [type-x] not always the first class entry, I'm only posting this answer because I already started on posting it.
function replaceIt( s, sentinel ) {
// sentinel: e.g. class="type-
if (sentinel) {
}
else sentinel = 'class="type-';
return s.replaceAll(sentinel , function( match, offset ) {
// get the position of the whitespace after "type-c"
nextSpace = s.indexOf(" ", offset);
// extract the "type" up until and excluding the "next space"
typeVar = s.substring( offset + sentinel.length, nextSpace);
// get the position of the 2nd double quote char
nextDoubleQuote = s.indexOf("\"", nextSpace);
// extract the new "class" names e.g. red blue
newClass = s.substring( nextSpace + 1, nextDoubleQuote);
// create the replacement string. Also something must be done with the leftover chars; prepend them with 'data-source'.
replacement = 'type="' + typeVar + '" class="' + newClass +'" data-source="';
// debugging code
console.log( match + ": " + offset + ": " + typeVar + ": " + newClass);
return replacement;
});
}
console.log( replaceIt( '<div class="type-c red blue">') );
But as noted on recent developments on what I noted on The entire before "class" string will have to be tokenized. So this solution only works if "type-" is the 1st class.
You don't even need regular expressions.
(Okay, you do, but only to find the x value in type-x. Proof here.)
You can use a mix of attribute selectors, the data-* attribute standard, and the Element.setAttribute() method.
Here's an example.
function doChange() {
// Find all divs with a 'type-x' class
let myDivs = document.querySelectorAll('div[class*="type-"]');
myDivs.forEach(curDiv => {
// Get the specific 'x' for the type
let curType = /(?<=type-)[A-Za-z\-]+/.exec(curDiv.classList.toString())[0];
// Set the 'data-type' attribute
curDiv.setAttribute('data-type', curType);
// Remove the 'type-x' class
curDiv.classList.toggle('type-' + curType);
// Write the 'classList' and 'data-type' attributes for show
curDiv.innerText = 'classList: ' + curDiv.classList
+ '; data-type: ' + curDiv.getAttribute('data-type') + ';';
});
}
<div class="type-a red blue">classList: type-a red blue; data-type: undefined;</div>
<div class="red type-b blue">classList: red type-b blue; data-type: undefined;</div>
<div class="red blue type-c">classList: red blue type-c; data-type: undefined;</div>
<button onclick="doChange()">Click Me</button>
This regular expression will match what you describe, regardless of the position of "type-xxx" in class attribute
/class="([^"]*)type-(\w+)([^"]*)"/g
Combining with a string replace
let value = '<div class="type-a b">test</div><div class="a type-b">test 2</div>';
value.replace(/class="([^"]*)type-(\w+)([^"]*)"/g, 'type="$2" class="$1$3"');
this will yield the result
<div type="a" class="b">test</div><div type="b" class="a">test 2</div>

Having difficulty building a form summary with JS

Sorry for the noobish question but, I am trying to build a form summary that will populate a div (immediately) with all of the fields being used. Here is a small sample of the field: Fiddle
For some reason the JS is not working as I would expect it to, can anyone point out what I am doing wrong?
For example, I would like it to output: "AND name: john EXCEPT number 222".
I would also like to be able click on a result to remove it, and clear the field. Thank you
$(".allS").change(function () {
if ($(this).next('.textArea').not(':empty'))
// varible to hold string
var str = "";
$("select option:selected").each(function () {
str += $(this).text() + " ";
});
$("#text_here").text(str);
}).change();
$('.textArea').change(function(){
var $inputs = $('form#form :input[type="text"]'),
result = "";
$inputs.each(function(){
// access the individual input as jQuery object via $(this)
result += $(this).val()+"<br>";
});
// store result in some div
$('div#text_here').text(result);
}).change();
There were many mistakes in your code. I simplified it to a very short code that only does what's needed to get the output you requested. Here's the working fiddle.
$(".allS, .textArea").change(function () {
var str = '';
if ($('#name').val().length > 0 && $('#number').val().length > 0)
var str = $('#nameMod>option:selected').text() + ' name:' + $('#name').val() + ' ' + $('#numberMod>option:selected').text() + ' number ' + $('#number').val();
$("#text_here").html(str);
});
Basically, what this does is attach a change event handler to both classes (.alls, .textArea), and when the event is triggered, both input fields are tested for any content. If this test passes, a string is composed out of all the relevant values, and the div content is set. If the test failed (no content), the str variable contains an empty string and the div is cleared.
Just glancing at the code, the selector 'form#form :input[type="text"]' looks wrong. For starters, input is not a pseudoclass. Also, attribute matching shouldn't have the quotes.
This may or may not be what you want (I think it is, from looking at your html):
'form#form input[type=text]'
Also your <br>'s are not working because you called text(). call html() instead.

Assign html <a> tag to a textarea value

I need to assign an <a> tag to a textarea value, separated with a comma. I'm trying to insert email IDs I get from a response of an ajax request. How do I achieve this using JS?
I tried using:
$('reminder_email').value += "<a href='#' id='+id'>+email+</a>";
Assuming that 'reminder_email' is the id of the relevant textarea, and that the response is an array of emails:
var emailAddressesArray = ['emailAddress#host.tld', 'emailAddress2#otherHost.tld'];
$('#reminder_email').val(emailAddressesArray.join(', '));
JS Fiddle demo.
If, on the other hand, you're trying to create the HTML of an a element with a mailto protocol (for copying/pasting elsewhere):
var email = 'emailAddress#host.tld';
$('#reminder_email').val('' + email + '');
JS Fiddle demo.
Note that you can't create clickable links within a textarea, as they can't contain HTML (just text).
If, though, you have an object from which to create your value:
var email = [{
'address': 'emailAddress#host.tld',
'id': 'emailOne',
'text': 'UserNameOne'
}, {
'address': 'anotherAddress#host2.tld',
'id': 'emailTwo',
'text': 'UserNameTwo'
}];
$('#reminder_email').val(function(_, v){
for (var i = 0, len = email.length; i < len; i++){
v += '' + email[i].text + ', ';
}
return v.slice(0, v.length - 2);
});
JS Fiddle demo.
The reason your code:
$('reminder_email').value += '<a href='#' id='+id'>+email+</a>;
didn't work is twofold:
$('reminder_email') is a selector looking for reminder_email tags (which don't exist); assuming that it's an id you're looking for you'll need to use: $('#reminder_email') instead,
A jQuery object/collection has no .value property, instead use the val() method (without arguments to get the current value, or with an argument to set a new value).
hoping you have jquery imported, try this:
$('reminder_email').val("<a href='#' id='"+id+"'>" + email + "</a>");
are you appending it? why do you use += ?

Get attr(id) with a known href variable

I want to get the id name thanks to a href value that is set in a variable.
To do this, I want to:
get the attr('href') of a clicked element (that works).
put it in a variable (OK).
search this href in a every class called ".link" (not in #prev-ajax, #next-ajax id) (problem)
Get the parent id.
I tried this :
$('#prev-ajax,#next-ajax').click(function(e) {
e.preventDefault();
var href = $(this).attr('href');
$(".link[href*= href ]:not('#prev-ajax,#next-ajax')");
var ajax = $(this).parents('.element').attr('id');
alert(ajax);
});
As you're using a JavaScript variable, you need to escape the quotes. Also, don't wrap items in the :not selector in quotes.
Try this:
$(".link[href*= '" + href + "']:not(#prev-ajax, #next-ajax)");
Edit: Looking at your fiddle, you're also not doing anything with that selector. See this:
$(".link[href*= '" + href + "']:not(#prev-ajax, #next-ajax)");
var ajax = $(this).parents('.element').attr('id');
It should be:
var link = $(".link[href*= '" + href + "']:not(#prev-ajax, #next-ajax)");
var ajax = link.parents('.element').attr('id');
Demo: http://fiddle.jshell.net/UKyT4/1/

How to include javascript generated text into html link?

I have a javascript that displays a generated text into a div:
document.getElementById('phrase').innerHTML = phrase;
PHRASE_TEXT_GETS_SHOWN_HERE
Basically I'm trying to set up a link that will take the text and post it to twitter with a link:
Clicky for tweety
How can I include the generated text in the link?
Do you mean like:
function setPhrase(phrase) {
var url = 'http://twitter.com/home?status=' + encode(phrase);
$('#phrase').html('' + phrase + '');
}
...?
Un-jQuerying it should be straightforward enough, if that's how you roll.
This is un-jQueried:
function setPhrase(phrase) {
var url = 'http://twitter.com/home?status=' + encodeURI(phrase);
document.getElementById('phrase').innerHTML = '' + phrase + '';
}
If you didn't see my failbraining encode for encodeURI as an error you should use Firebug. It may also fail if you have more than one element with the id phrase or if you have no elements with the id phrase.

Categories

Resources