Capitalize select option using Javascript - javascript

I have a dropdown menu.
I've been trying to capitalize the text inside my select option, but I couldn't make it work.
JS
$.each(responseData.assignments, function(i, v) {
var chapterNum = v.contentLabel;
var assessmentType = v.assessmentType.toLowerCase().replace(/_/g, " ");
var sameAssignmentType = $('#assignment-type-dd option').filter(function(){
return $(this).text() == assessmentType;
})
if(!sameAssignmentType.length){
$('#assignment-type-dd').append('<option value="' + assessmentType + '">' +
assessmentType + '</option>');
}
});
I've tried chaining this code to my assessmentType :
.charAt(0).toUpperCase() + this.slice(1)
But as soon as I do that it give error :
Uncaught TypeError: this.slice is not a function
Can someone please give me a little hint here ? Thanks.

This should work (CSS approach)
#assignment-type-dd option {
text-transform: capitalize;
}
If you need the entire options text to be uppercase use this.
#assignment-type-dd option {
text-transform: uppercase;
}
And if you really hate CSS or you need the Capitalized text to be passed to server or do some other manipulation, use the below JavaScript code
var capitalizeMe = "";
$("#assignment-type-dd option").each(function() {
capitalizeMe = $(this).text();
$(this).text(capitalizeMe.charAt(0).toUpperCase() + capitalizeMe.substring(1));
});
Play it here

Instead of using this.slice(1), try using assessmentType.slice(1).

you need to format it as
string.charAt(0).toUpperCase() + string.slice(1)

One solution could be to use a CSS rule:
select option {
text-transform:capitalize;
}

We can manipulate font setting by CSS alternation also. Try this
<style>
select option {
text-transform:capitalize;
}
</style>

This seems like a problem CSS is best-suited for.
.select {
text-transform: uppercase;
}

You don't need jQuery for this, unless you are trying to capitalize the first letter of each word. In which case a pure JavaScript solution (assuming you are targeting h2 elements) would be:
var a = document.getElementsByTagName('h2');
for (i = 0; i < a.length; i++) {
var words = a[i].innerHTML.split(" ");
for (j = 0; j < words.length; j++) {
if (words[j][0] != "&") {
words[j] = "<span class='first-letter'>" + words[j][0] + "</span>" + words[j].substring(1);
}
}
a[i].innerHTML = words.join(" ");
}
http://jsfiddle.net/ryanpcmcquen/2uLLqy8r/
Otherwise pure css will work: text-transform: capitalize;
https://developer.mozilla.org/en-US/docs/Web/CSS/text-transform

If it is about just showing it then the css text-transform should work.
If you want to do it programatically in Javascript, I suggest creating a function and calling it as needed:
function stringCapitalize(str){
if (str){
str = str.charAt(0).toUpperCase() + str.slice(1);
return str;
}
}
stringCapitalize("moemen"); // returns "Moemen"
If you think that you will use it regularly during this application, then add it to the built-in String.prototype:
String.prototype.stringCapitalize = function () {
if (this){
str = this;
str = str.charAt(0).toUpperCase() + str.slice(1);
return str;
}
}
"moemen".stringCapitalize() // returns "Moemen"

var name = prompt("what is your name");
var firstchar = name.slice(0, 1);
var firstcharuppercase = firstchar.toUpperCase();
var restofName = name.slice(1,name.length);
var capitlisedName = firstcharuppercase + restofName;
alert(" Hello " + capitlisedName);

Related

Format color while typing in textarea or pre

I'm trying to create a comments section that lets users #someone. When the user types #random and then space, I want it to be highlighted. So I've created something that searches and replaces the string, but I then when the html is replaced, it places the cursor at the beginning. Any way to solve this? Any other way of doing something like this?
$('#textarea').keyup(function() {
txt = this.innerText.split(" ")
new_txt = this.innerText
for (var i = txt.length - 1; i >= 0; i--) {
if (txt[i].startsWith('#') == false) {
delete txt[i]
}
}
txt = txt.sort().join(" ").trim().split(" ")
console.log(txt)
if (txt.length > 0 && txt[0] != "") {
for (var i = 0; i < txt.length; i++) {
new_txt = new_txt.replace(txt[i], '<mark>' + txt[i] + '</mark>')
}
$('#my_console_log').text(new_txt)
this.innerHTML = new_txt
}
});
pre {
border: solid black 1px;
}
mark {
background: blue;
color: red;
}
<script src="https://code.jquery.com/jquery-1.10.2.js"></script>
<title>Test page</title>
<form>
<pre id='textarea' contentEditable='true'></pre>
<div id="my_console_log"></div>
</form>
Here is a simple plugin available which can be useful to you,
Download the plugin and edit the file jquery.hashtags.js and remove the condition for #. You can also change the style as per your requirement.
(function($) {
$.fn.hashtags = function() {
$(this).wrap('<div class="jqueryHashtags"><div class="highlighter"></div></div>').unwrap().before('<div class="highlighter"></div>').wrap('<div class="typehead"></div></div>');
$(this).addClass("theSelector");
autosize($(this));
$(this).on("keyup", function() {
var str = $(this).val();
$(this).parent().parent().find(".highlighter").css("width",$(this).css("width"));
str = str.replace(/\n/g, '<br>');
if(!str.match(/(http|ftp|https):\/\/[\w-]+(\.[\w-]+)+([\w.,#?^=%&:\/~+#-]*[\w#?^=%&\/~+#-])?#([a-zA-Z0-9]+)/g) && !str.match(/(http|ftp|https):\/\/[\w-]+(\.[\w-]+)+([\w.,#?^=%&:\/~+#-]*[\w#?^=%&\/~+#-])?#([a-zA-Z0-9]+)/g) && !str.match(/(http|ftp|https):\/\/[\w-]+(\.[\w-]+)+([\w.,#?^=%&:\/~+#-]*[\w#?^=%&\/~+#-])?#([\u0600-\u06FF]+)/g) && !str.match(/(http|ftp|https):\/\/[\w-]+(\.[\w-]+)+([\w.,#?^=%&:\/~+#-]*[\w#?^=%&\/~+#-])?#([\u0600-\u06FF]+)/g)) {
// Remove below condition for hashtag.
if(!str.match(/#(([_a-zA-Z0-9]+)|([\u0600-\u06FF]+)|([ㄱ-ㅎㅏ-ㅣ가-힣]+)|([ぁ-んァ-ン]+)|([一-龯]+))#/g)) { //arabic support, CJK support
str = str.replace(/#(([_a-zA-Z0-9]+)|([\u0600-\u06FF]+)|([ㄱ-ㅎㅏ-ㅣ가-힣]+)|([ぁ-んァ-ン]+)|([一-龯]+))/g,'<span class="hashtag">#$1</span>');
}else{
str = str.replace(/#(([_a-zA-Z0-9]+)|([\u0600-\u06FF]+)|([ㄱ-ㅎㅏ-ㅣ가-힣]+)|([ぁ-んァ-ン]+)|([一-龯]+))#(([_a-zA-Z0-9]+)|([\u0600-\u06FF]+)|([ㄱ-ㅎㅏ-ㅣ가-힣]+)|([ぁ-んァ-ン]+)|([一-龯]+))/g,'<span class="hashtag">#$1</span>');
}
// Keep this condition.
if(!str.match(/#(([a-zA-Z0-9]+)|([\u0600-\u06FF]+)|([ㄱ-ㅎㅏ-ㅣ가-힣]+)|([ぁ-んァ-ン]+)|([一-龯]+))#/g)) {
str = str.replace(/#(([a-zA-Z0-9]+)|([\u0600-\u06FF]+)|([ㄱ-ㅎㅏ-ㅣ가-힣]+)|([ぁ-んァ-ン]+)|([一-龯]+))/g,'<span class="hashtag">#$1</span>');
}else{
str = str.replace(/#(([a-zA-Z0-9]+)|([\u0600-\u06FF]+)|([ㄱ-ㅎㅏ-ㅣ가-힣]+)|([ぁ-んァ-ン]+)|([一-龯]+))#(([a-zA-Z0-9]+)|([\u0600-\u06FF]+)|([ㄱ-ㅎㅏ-ㅣ가-힣]+)|([ぁ-んァ-ン]+)|([一-龯]+))/g,'<span class="hashtag">#$1</span>');
}
}
$(this).parent().parent().find(".highlighter").html(str);
});
$(this).parent().prev().on('click', function() {
$(this).parent().find(".theSelector").focus();
});
};
})(jQuery);
Instead of replacing the html just append a class with the color that you want

Checking a div for duplicates before appending to the list using jQuery

This should be trivial but I'm having issues...
Basically what I am trying to do is append a new "div" to "selected-courses" when a user clicks on a "course". This should happen if and only if the current course is not already in the "selected-courses" box.
The problem I'm running into is that nothing is appended to the "selected-courses" section when this is executed. I have used alert statements to make sure the code is in fact being run. Is there something wrong with my understanding of the way .on and .each work ? can I use them this way.
Here is a fiddle http://jsfiddle.net/jq9dth4j/
$(document).on("click", "div.course", function() {
var title = $( this ).find("span").text();
var match_found = 0;
//if length 0 nothing in list, no need to check for a match
if ($(".selected-course").length > 0) {
match_found = match(title);
}
if (matched == 0) {
var out = '<div class="selected-course">' + '' + title + ''+'</div>';
$("#selected-box").append(out);
}
});
//checks to see if clicked course is already in list before adding.
function match(str) {
$(".selected-course").each(function() {
var retval = 0;
if(str == this.text()) {
//course already in selected-course section
retval = 1;
return false;
}
});
return retval;
}
There was a couple of little issues in your fiddle.
See fixed fiddle: http://jsfiddle.net/jq9dth4j/1/
function match(str) {
var retval = 0;
$(".selected-course").each(function() {
if(str == $(this).text()) {
retval = 1;
return false;
}
});
return retval;
}
You hadn't wrapped your this in a jquery object. So it threw an exception saying this had no method text().
Second your retval was declared inside the each so it wasn't available to return outside the each, wrong scope.
Lastly the if in the block:
if (matched== 0) {
var out = '';
out += '<div class="selected-course">' + '' + title + ''+'</div>';
$("#selected-box").append(out);
}
was looking at the wrong variable it was looking at matched which didn't exist causing an exception.
Relying on checking what text elements contain is not the best approach to solve this kind of question. It is prone to errors (as you have found out), it can be slow, it gives you long code and it is sensitive to small changes in the HTML. I would recommend using custom data-* attributes instead.
So you would get HTML like this:
<div class="course" data-course="Kite Flying 101">
<a href="#">
<span>Kite Flying 101</span>
</a>
</div>
Then the JS would be simple like this:
$(document).on('click', 'div.course', function() {
// Get the name of the course that was clicked from the attribute.
var title = $(this).attr('data-course');
// Create a selector that selects everything with class selected-course and the right data-course attribute.
var selector = '.selected-course[data-course="' + title + '"]';
if($(selector).length == 0) {
// If the selector didn't return anything, append the div.
// Do note that we need to add the data-course attribute here.
var out = '<div class="selected-course" data-course="' + title + '">' + title + '</div>';
$('#selected-box').append(out);
}
});
Beware of case sensitivity in course names, though!
Here is a working fiddle.
Try this code, read comment for where the changes are :
$(document).on("click", "div.course", function () {
var title = $(this).find("span").text().trim(); // use trim to remove first and end whitespace
var match_found = 0;
if ($(".selected-course").length > 0) {
match_found = match(title);
}
if (match_found == 0) { // should change into match_found
var out = '';
out += '<div class="selected-course">' + '' + title + '' + '</div>';
$("#selected-box").append(out);
}
});
function match(str) {
var retval = 0; // this variable should place in here
$(".selected-course").each(function () {
if (str == $(this).find('a').text().trim()) { // find a tag to catch values, and use $(this) instead of this
retval = 1;
return false;
}
});
return retval; // now can return variable, before will return undefined
}
Updated DEMO
Your Issues are :
1.this.text() is not valid. you have to use $(this).text().
2.you defined var retval = 0; inside each statement and trying to return it outside each statement. so move this line out of the each statement.
3.matched is not defined . it should be match_found in line if (matched == 0) {.
4. use trim() to get and set text, because text may contain leading and trailing spaces.
Your updated JS is
$(document).on("click", "div.course", function () {
var title = $(this).find("span").text();
var match_found = 0;
if ($(".selected-course").length > 0) {
match_found = match(title);
}
if (match_found == 0) {
var out = '<div class="selected-course">' + '' + title + '' + '</div>';
$("#selected-box").append(out);
}
});
function match(str) {
var retval = 0;
$(".selected-course").each(function () {
if (str.trim() == $(this).text().trim()) {
retval = 1;
return false;
}
});
return retval;
}
Updated you Fiddle

Why html-element text doesn't replace?

I use javascript (jQuery) to toggle text of html-element (span):
function TextToogle(element, text) {
if (element.html() == '-' + text) {
element.html(text.replace(element.html(), '+' + text));
}
else {
element.html(text.replace(element.html(), '-' + text));
}
}
I give two arguments for my function:
1) element - html Object
2) text - default text of span
My goal is toggle the span text from "+text" to "-text" and vice versa.
But script doesn't work correctly. When function toggle text to "+text", as result I see "text". The toggle to "-text" works correctly.
I would just replace inside a callback, seems so much simpler
element.text(function(_, txt) {
return txt.replace(/[+-]/g, function(x) {
return x == '+' ? '-' : '+';
});
});
FIDDLE
Based on you is comparison (element.html() == '-' + text) your function can be simpler. You don't need text.replace(element.html(), '+' + text) part:
function TextToogle(element, text) {
if (element.text() == '-' + text) {
element.text('+' + text);
}
else {
element.text('-' + text);
}
}
However relying on text comparison is not ideal. I would use CSS which is not text dependent:
$('.text-toggle').click(function() {
$(this).toggleClass('active');
});
CSS
.text-toggle:before {
content: '+';
}
.text-toggle.active:before {
content: '-';
}
There is obvious advantage here is that you can style your +/- easily, you can set a background image, chage font-size, etc. While you would'n be able this with your original approach.
Demo: http://jsfiddle.net/dfsq/mvj5c/
function toggleText(text) {
return {'-':'+', '+':'-'}[text[0]]+text.slice(1);
}
element.html(toggleText(element.html()));
See simple example.
You've text -abc. Now it's fail on both of the checks.
Why not do this
function TextToogle(element, text) {
var check = text.splice(0, 1);
if (check === "-") {
element.html("+" + text.substring(1, text.length));
}
else {
element.html("-" + text.substring(1, text.length));
}
}
try this code
$('span').click(function(){
var
$this = $(this),
thisText = $this.text();
$this.text($this.text() === "-" + thisText ? ("+" + thisText) : ("-" + thisText));
});

Generating a random color not working

I was working on a simple project, to have the background of a webpage change every time you click on it. I succeeded in such, tested it a few times, save, tested again, and then left.
I go home and load it.. And it no longer works. I am using the same browser, I have no idea how anything could have changed.. I must have messed up a few ways almost impossible it feels like.. But alas, I'm sitting here dumb-founded..
Could anyone take a look at my simple program and tell me what is wrong? (Again, the program purpose is to change the webpage's background color to a random color whenever you click on the page.)
Here is the code:
<!DOCTYPE HTML PUBLIC>
<html>
<head>
<title>Random Colors</title>
<script language="javascript">
function randomColor() {
var h0 = Math.floor(Math.random()*99);
var h1 = Math.floor(Math.random()*99);
var h2 = Math.floor(Math.random()*99);
var h3 = Math.floor(Math.random()*99);
var h4 = Math.floor(Math.random()*99);
var h5 = Math.floor(Math.random()*99);
return '#'.toString(16)+h0.toString(16)+h1.toString(16)+h2.toString(16);+h3.toString(16)+h4.toString(16)+h5.toString(16);
}
</script>
</head>
<body onclick="document.bgColor=randomColor();">
</body>
</html>
Thanks in advance if anyone can help.
Having '#'.toString(16) makes no sense, the string '#' can't be converted to a string in hexadecimal form...
You have an extra semicolon after h2.toString(16).
return '#'+h0.toString(16)+h1.toString(16)+h2.toString(16)+h3.toString(16)+h4.toString(16)+h5.toString(16);
I think that you want to keep each digit in the range 0-15 instead of 0-98:
var h0 = Math.floor(Math.random()*16);
Try this out. Built off of what #Guffa did
function randomColor() {
var h0 = Math.floor(Math.random()*16);
var h1 = Math.floor(Math.random()*16);
var h2 = Math.floor(Math.random()*16);
var h3 = Math.floor(Math.random()*16);
var h4 = Math.floor(Math.random()*16);
var h5 = Math.floor(Math.random()*16);
return '#' + h0.toString(16) + h1.toString(16) + h2.toString(16) + h3.toString(16) + h4.toString(16) + h5.toString(16);
}
Here's the fiddle --> http://jsfiddle.net/Jh5ms/1/
Is there a reason you're using Math.random so many times?
function pad6(s) {
s = '' + s;
return '000000'.slice(s.length) + s;
}
function randomColor() {
var rand = Math.floor(Math.random() * 0x1000000);
return '#' + pad6(rand.toString(16)).toUpperCase();
}
randomColor(); // "#7EE83D"
randomColor(); // "#19E771"
As pointed out by Guffa, your first error was attempting to convert '#' to a hexadecimal representation.
This should do the trick:
function randomColor() {
var ret = Math.floor(Math.random() * (0xFFFFFF + 1)).toString(16);
return ('#' + new Array((6 - ret.length) + 1).join('0') + ret);
}
window.onload = function() {
document.querySelector('button').onclick = function() {
document.querySelector('body').style.backgroundColor = randomColor();
};
};
Here is a demonstration.
Here is another demonstration showing how you could implement it into your current page. I also took the liberty of changing your event handler to be unobtrusive.
Adding to Guffa fixing the Math.random()*99 problem, I would put all this in a loop like this:
var theColor = "#";
for (var i = 0; i < 6; i++) {
theColor += Math.floor(Math.random() * 16).toString(16);
}
return theColor;
Here's a jsFiddle
another answer in your format - pass this to whatever you want to change backgroundcolor
http://jsfiddle.net/FpLKW/2/
<div onclick="test(this);">
</div>
function test (ele) {
var h0 = Math.floor(Math.random()*10);
var h1 = Math.floor(Math.random()*10);
var h2 = Math.floor(Math.random()*10);
var h3 = Math.floor(Math.random()*10);
var h4 = Math.floor(Math.random()*10);
var h5 = Math.floor(Math.random()*10);
var x = '#' + h0.toString(16) + h1.toString(16) + h2.toString(16) + h3.toString(16) + h4.toString(16) + h5.toString(16);
ele.style.backgroundColor=x;
}

Javascript - Get Meta Keywords and If Non Don't Break Bookmarklet

I have a bookmarklet that gets the meta keywords on a page. However if the there are no meta keywords the bookmarklet breaks.
Here is my current javascript
function docoument_keywords(){
var keywords;
var metas = document.getElementsByTagName('meta');
for (var x=0,y=metas.length; x<y; x++) {
if (metas[x].name.toLowerCase() == "keywords") {
keywords = metas[x];
}
}
return keywords.content;
}
k = document_keywords();
$('body').append("<p>" + k + "</p><p>Content</p>");
The bookmarklet works fine when there are actually keywords in the meta keywords. However its break when there are none. You guys have any solutions?
Much appreciated!
function document_keywords(){
var keywords = '';
var metas = document.getElementsByTagName('meta');
if (metas) {
for (var x=0,y=metas.length; x<y; x++) {
if (metas[x].name.toLowerCase() == "keywords") {
keywords += metas[x].content;
}
}
}
return keywords != '' ? keywords : false;
}
k = document_keywords();
if (k) {
$('body').append("<p>"+k+"</p>");
}
Working example: JS Fiddle
Though Michael answered your question, I just wanted to point out that since you appear to already be using jQuery, this can be accomplished much, much more simply. Your script can be summarized thusly in its entirety:
$('body').append(
"<p>" +
$.map($('meta[name="keywords"]'), function(metaEl) { return metaEl.content; }) +
"</p>"
);
// Or, on one line:
$('body').append("<p>" + $.map($('meta[name="keywords"]'), function(metaEl) { return metaEl.content; }) + "</p>");
Hope it's helpful!

Categories