jquery text() not comparing to string - javascript

I am using javascript to hide some list Items based on the user role.
I am getting the role from a list item's text(). When I am comparing the $("#activeUser").text() value against a string, it is not working.
HTML Block that I am using in my javascript to get the text() value of a list item.
<ul class="pull-right breadcrumb">
<li>Home <span class="divider">/</span> </li>
<li id="activeUser" class="active"> <?php echo ucfirst($_SESSION['sewafs_user_role']); ?> </li>
</ul>
Javascript
$(document).ready(function () {
var testRole = $("#activeUser").text();
//This block of code works
role = 'Guest';
if (role == 'Guest') {
alert("Inside if");
$("#request_history_li").hide();
$("#assign_role_li").hide();
$("#volunteer_li").hide();
$("#profile_li").show();
$("#change_password_li").show();
}
//This doesn't work why?
if (testRole == 'Guest') {
alert("Inside if");
$("#request_history_li").hide();
$("#assign_role_li").hide();
$("#volunteer_li").hide();
$("#profile_li").show();
$("#change_password_li").show();
}
});
But if I see the value of the var testRole using alert it prints Guest.
I tried converting the testRole value into string using testRole.toString() / string(testRole) method, but nothing helped.
Please let me know, where I am going wrong. Thanks.

The problem seems to be extra white-spaces in the value that you receive from $("#activeUser").text()
Solution:
You must trim the value and then use it for comparison as:
var testRole = $("#activeUser").text().trim();
OR
var testRole = $.trim($("#activeUser").text());
OR
var testRole = $("#activeUser").text();
testRole = $.trim(testRole);
Any of the above will work.
More info on jQuery trim at this link.
Whitespace test:
If you want to test if you are getting extra white spaces, then try below javascript code:
alert("-" + $("#activeUser").text() + "-");
If you get "" then you dont have whitespaces in your received value.
But if you get spaces after < or before >, then these are white spaces, that are spoiling your party.

Try trimming the string, with $.trim($("#activeUser").text());
There seem to be whitespaces in your element.

You need to trim white spaces at start and end of the string:
var testRole = $("#activeUser").text().replace(/^\s+|\s+$/g,'');
You can see why here: http://jsfiddle.net/AfUZR/1/

Demo
$(document).ready(function () {
var testRole = $("#activeUser").text().trim();
//This doesn't work why?
if (testRole == "Guest") {
alert("Inside if");
$("#request_history_li").hide();
$("#assign_role_li").hide();
$("#volunteer_li").hide();
$("#profile_li").show();
$("#change_password_li").show();
}
});

Man, first what do you must do it, it's write correct selector.
$("#request_history_li").hide();
$("#assign_role_li").hide();
you can write
$("#request_history_li, #assign_role_li").hide();
or you can add the same classes of these Elements, that is correct
<ul>
<li class="same_class 1"></li>
<li class="same_class 2"></li>
</ul>
and
$(".same_class").hide();
ok? next:
As concerns your problem, js loaded earlier than you determine the role of, use
$(document).ready(function(){
......
});

Related

Remove dashes and wrap with <li> with javascript/jquery

I have a "list" that looks like this:
-1+ years of experience in End User Support<br>
-Experience re-imaging laptops<br>
-Great customer service experience
And I want to turn it into an unordered list.
I wrapped the block in a <ul></ul> and then I used this code to remove the <br> and wrap with <li></li>:
$('.entry-content ul').each(function() {
var $this = $(this);
$this.html($this.html().replace(/[^\r\n]+/g, '<li>$&</li>'));
});
This outputs an unordered list like this:
-1+ years of experience in End User Support
-Experience re-imaging laptops
-Great customer service experience
But I don't know how to remove the dashes, too. I tried doing a second replace function after the first one, like this: $this.html($this.html().replace((/-/g, ' ')); , but that didn't work.
How can I achieve this?
var str = str = "-Experience re-imaging laptops";
console.log(str.replace(/^-/, ''));
Your posted code doesn't actually remove the <br> tags, you just don't see them in the results. I'd replace those, and any "-" after a newline or at the beginning of the text, with newlines, then replace as above.
$('.entry-content ul').each(function() {
var $this = $(this);
$this.html(
$this
.html()
.trim()
.replace(/^-|[\r\n]+-|<br>/g, "\n")
.replace(/[^\r\n]+/g, '<li>$&</li>')
);
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class=entry-content>
<ul>
-1+ years of experience in End User Support<br>
-Experience re-imaging laptops<br>
-Great customer service experience
</ul>
</div>

jquery if input contains phrase from array-child friendly global chat

I have found some code for a chat system. I am going to be using it as a child-friendly (so I can't be blamed for anything) global chat. The way the code works is by checking the input to see if it contains any word from an array, if it does then the program will display something to a <ol> tag, for me to see if it works. Otherwise is does nothing.
JQUERY
var banned_words = {
'songs': ['hello', 'sorry', 'blame'],
'music': ['tempo', 'blues', 'rhythm']
};
function contains(words) {
return function(word) {
return (words.indexOf(word) > -1);
};
};
function getTags(input, banned_words) {
var words = input.match(/\w+/g);
return Object.keys(banned_words).reduce(function(tags, classification) {
var keywords = banned_words[classification];
if (words.some(contains(keywords)))
tags.push(classification);
return tags;
}, []);
};
// watch textarea for release of key press
$('#sendie').keyup(function(e) {
$('#tags').empty();
var tags = getTags($(this).val().toLowerCase(), banned_words);
var children = tags.forEach(function(tag) {
$('#tags').append($('<li>').text(tag));
});
if (e.keyCode == 13) {
var text = $(this).val();
var maxLength = $(this).attr("maxlength");
var length = text.length;
// send
if (length <= maxLength + 1) {
chat.send(text, name);
$(this).val("");
} else {
$(this).val(text.substring(0, maxLength));
}
}
});
HTML
<form id="send-message-area">
<p style="text-align:center">Your message: </p>
<input id="sendie" maxlength = '100' />
</form>
<ol id="tags">
</ol>
But, what I'm also wanting to do is check if the input value contains phrases from the array so I can ban phrases that are too sensitive for children. How can I add this in, or is there another more efficient way to check the input?
UPDATE
I have already tried to place the phrase directly into the banned_words (I changed them as this post would get flagged for inappropriate language) and using the hexadecimal character for the space-bar. None of these worked.
You can try either of the following since the space is also a known charachter:
test 1:
Just put your phrase between quotes such as 'cry baby','red apple' etc.
sometimes it does not work, you can try
test 2:
replace the space with the hexidecimal character \x20 such as 'cry\x20baby','red\x20apple'
I hope one or both of these works for you.
I have done some more research and have found a cool plugin for JQuery. It's called jQuery.profanityFilter. It uses a json file filled with sensative words.
Link to github download: https://github.com/ChaseFlorell/jQuery.ProfanityFilter

Set a form value as that of a UL

I am using a jQuery plugin called 'tagit'.
I know you can't post a UL, but how can I get around that?
Lets say that I have:
<ul name="addtags" id="addtags" class="addtags" placeholder="Tags">
<li>Add your tags here</li>
</ul>
<input type="hidden" name="addtagsReal" />
When the form is submitted, I do validation with javascript. So I was thinking that, in my validation, I could simply set the hidden 'addtagsReal' input to that of the ul.
How can I do this with jQuery?
Thanks!
You essentially need a way to "serialize" the list, an older jquery plugin to do this is here:
jQuery serialize list
You can do something like this:
var separator = ",";
var str = $('#addtags').children('li').map(function(i,el){
return($(el).text());
}).get().join(separator);
$('input[name="addtagsReal"]').val(str);
And then you send your LIs separated by ´separator´, and explode them with PHP.
You can make comma separated 'data' strings with simple concatenation and some jQuery tomfoolery. There are certainly better ways to do it.
$(document).ready(function(){
var sampleTags = ['c++', 'java', 'php'],
eventTags = $('#eventTags');
eventTags.tagit({
availableTags: sampleTags,
afterTagAdded: function(evt, ui) {
updateTagInput();
},
afterTagRemoved: function(evt, ui) {
updateTagInput();
}
});
});
function updateTagInput() {
var $hidden = $('input[name=addtagsReal]'),
values = "";
$('#eventTags').find('.tagit-label').each(function(i, item){
values += $(item).text() + ', ';
});
// update the input and trim the final ', '
$hidden.val(values.substr(0, values.length - 2 ));
}
edit: oops! Deleted the plunk, thought I was deleting a version of it! Sorry, not going to recreate it but it used the html from the Events portion of this page http://aehlke.github.io/tag-it/examples.html

JS/JQuery loop chekboxes and call function by name

I have many inputs with class filter:
<ul>
<li>
<a><input class="filter" name="filter[manufacturer][]" type="checkbox"> Other (18)</a>
</li>
<li>
<a><input class="filter" name="filter[manufacturer][JOBY]" type="checkbox"> JOBY (2)</a>
</li>
<li>
<a><input class="filter" name="filter[manufacturer][Beurer]" type="checkbox"> Beurer (1)</a>
</li>
<li><a>
<input class="filter" name="filter[manufacturer][Obreey Products]" type="checkbox"> Obreey Products (1)</a>
</li>
</ul>
And i need to loop every input with JavaScript or JQuery and call cl.facetFilter(name, name2) function if input checkbox is checked:
For example if checkbox name is filter[manufacturer][JOBY] and input is checked, i need to call:
cl.facetFilter('manufacturer', 'JOBY');
If checkbox name filter[manufacturer][] and input is checked, i need to call:
cl.facetFilter('manufacturer', '');
Thanks for help
You can do:
$(".filter:checked").each(function() {
var name = $(".filter").attr("name");
name = name.split("[");
name[1] = name[1].substring(0, name[1].length - 1);
name[2] = name[2].substring(0, name[2].length - 1);
cl.facetFilter(name[1], name[2]);
});
Demo: http://jsfiddle.net/tymeJV/MfAsA/ -- I logged the results rather than call a func in the demo.
At its simplest I'd suggest, albeit untested:
$('.filter').each(function () {
var self = this;
if (self.checked && self.name) {
var names = self.name.match(/\[(.+)\]/)[1].split('][');
c1.facetFilter(names[0],names[1]);
}
});
JS Fiddle demo.
Note, in the demo I'm, obviously, using a different function-name and also setting the checkboxes to be checked (for the purposes of demonstration).
References:
each().
JavaScript Regular Expressions.
String.match().
String.split().
This jQuery should do what you need:
$('.filter:checked').each(function(index, elem) {
elem = $(elem);
var result = elem.attr('name').match(/\[[a-zA-Z0-9 ]*\]/g);
if (result.length == 2) { // Sanity check
cl.facetFilter(result[0], result[1]);
}
});
The :checked portion of the selector should filter out any unchecked input boxes, and the regex match should pick out the values in the two sets of brackets. If that notation isn't necessary, though, I would advise a simpler formatting (e.g. filter|manufacturer|JOBY) so you could do a simple .split() on the separator character.
Some icky string manipulation, but this will call the function with the correct parameters when you check the relevant box:
$('.filter').click(function(e){
if($(this).is(':checked')){
$name = $(this).attr('name');
$names = $name.split('[');
$attr1 = $names[1].replace(']', '');
$attr2 = $names[2].replace(']', '');
console.log('cl.facetFilter(\''+$attr1+'\', \'' +$attr2+'\')');
}
});
If you're loading the document with some boxes already checked, then the $('.filter:checked').each(function() {... syntax will get you there.
JSFiddle link
$("input.filter:checked").each(function() {
var parts = /\[(.*)\]\[(.*)\]/g.exec(this.name);
cl.facetFilter(parts[1], parts[2]);
});

Looping through array and display results using JavaScript?

I've got a simple array that I want to loop through and search for whatever a user has typed into a text box. Here is what I have got. Bare in mind I am very new to JavaScript:
function recipeInfo(name, ingredients, url) {
this.name = name;
this.ingredients = ingredients;
this.url = url;
}
var vIngredients = new Array();
vIngredients[0] = new recipeInfo("Ackee Pasta", "ackee", "ackpast.html");
vIngredients[1] = new recipeInfo("Ackee and Saltfish", "ackee saltfish", "acksalt.html");
vIngredients[2] = new recipeInfo("Jerk Chicken", "jerk", "jerkchick.html");
// do the lookup
function getData(form) {
// make a copy of the text box contents
var inputText = form.Input.value
// loop through all entries of vIngredients array
for (var i = 0; i < vIngredients.length; i++) {
var list = $("#search-results");
// compare results
if (inputText == vIngredients[i].ingredients) {
console.log(vIngredients[i].name);
//add to the list the search result plus list item tags
list.append (
$("<li class='arrow'><a href='#' >" + vIngredients[i].name + "</a></li>" )
);
}
else {
// advise user
var list = $("#search-results");
// empty list then tell user nothing is found
list.empty();
list.append (
$("<li>No matches found for '" + inputText + "'</li>")
);
}
}
}
</script>
<form name="search" id="search" action="">
<ul class="rounded">
<li><input type="search" name="Input" placeholder="Search..." onkeydown="if (event.keyCode == 13) getData(this.form)"></li>
</ul>
<ul class="edgetoedge" id="results">
<li class="sep">Results</li>
</ul>
<ul class="edgetoedge" id="search-results">
</ul>
</form>
Here are the problems I'm having:
My search only looks for exact matches. In my example, the "ingredients" property will have more than 1 word in it, so I want to be able to search for any of those words instead of exactly what is in the array
If someone searches, the list just keeps appending to the existing list. How can I erase the contents of the before every search?
Lastly, my feedback for the user if no match is found always is shown instead of results, regardless if there are results or not. Commenting that section out makes the search work as normal but alas without the feedback if there is no match.
Thanks!
For #1, you want to see if the text in array slot contains the typed word as a substring. Do it like this:
// compare results
if (vIngredients[i].ingredients.indexOf(inputText) != -1) {
For #2, list.empty() should do it. You have that in your "else" block for the case when no results were found.
For #3 how do you know that results are actually being found? Does "inputText == vIngredients[i].ingredients" ever evaluate to "true"? Does console.log(vIngredients[i].name); log as you'd expect it to?
If you're new to javascript, you may not know about breakpoint debuggers in various browser developer tools. These are invaluable .

Categories

Resources