Reassigning a value to a variable - javascript

I feel like I must be missing something really obvious here. I'm grabbing the text from within a div and using an if statement to reassign the value of the variable to "javascript" if it's "HTML", but this doesn't seem to be working at all.
Could somebody help me with this?
var currentChoice = $('#contentSelector').text();
var newChoice = currentChoice;
if (currentChoice == 'HTML') {
currentChoice = 'Javascript';
};
alert(currentChoice);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div id="contentSelector"> HTML </div>
Thanks

There are spaces around 'HTML' so it's likely not matching. " HTML " is different than "HTML".
Do this and it works $.trim($('#contentSelector').text());

You have spaces either side of the HTML text value of the element. You can use trim() to remove these before testing the value in the if statement:
var currentChoice = $('#contentSelector').text().trim();

If you already use jquery, why not:
var $currentChoice = $('#contentSelector')
if ($currentChoice.text().toString() == "HTML"){
$currentChoice.text('Javascript');
};

Related

Compare variable against test strings

Here is my JQuery Code and I would like to compare the text in the text variable "text" to the possible CR Status (e.g. Approved Implemented), but I don't know how to do it.
_spBodyOnLoadFunctionNames.push("colouring");
function colouring(){
var $th = $("div[Name='CR_x0020_Status']").parent().css("background-color","#66CD00");
var $index = $th.index();
$th.parent().parent().children(".ms-itmhover").each(function(index, elem) {
var $div = $($(this).children("td").get($index));
var text = $div.text();
$("text:contains('Approved')").css("background-color","#66CD00");
})
}
I tried different options, but I still don't know how to do it!
Best regards and thank you in advance
Matthias
You can't put variables in jQuery selectors. $("text:contains(Approved)") means an element with tag text that contains Approved. You could write:
if (text.indexOf('Approved') > -1)
But you don't need the .each() loop at all, you can do it all with jQuery selectors:
$th.parent().parent().find(".ms-itmhover > td:contains(Approved)").css("background-color", "#66CD00");
Hard to tell exactly what you need, but possibly:
if(text == "Approved Implemented"){
...do more stuff here...
}
Possibly, you just need to duplicate the existing line and modify it for another colour:
$("text:contains('Approved')").css("background-color","#66CD00");
$("text:contains('Approved Implemented')").css("background-color","#0066CD");

Replace Word Within Word - Javascript

I need to get a id from a html element and replace a part of the word. For example:
HTML
<input type="checkbox" id="facebookCheckbox"></div>
JavaScript
var x = document.getElementById("facebookCheckbox");
var name = x.id;
name.replace("Checkbox","");
This obviously does not work because the replacing word has to be standalone for it to be replaced. Is there a different way of doing this?
I'm looking for purely javascript no jQuery
Thank you!
name.replace("Checkbox","");
This obviously does not work because the replacing word has to be standalone for it to be replaced.
No, it does work and there's no need to be "standalone" - any part of the string can be matched. Only you did nothing with the result of the operation:
console.log(name.replace("Checkbox",""));
// or
name = name.replace("Checkbox","");
// or assign back to x.id maybe?
You are creating a copy of string when replacing, so you must assign the result of .replace() back to x.id.
var x = document.getElementById("facebookCheckbox");
x.id = x.id.replace("Checkbox","");
this is not going to work in this way. However you can have a marker kind of character by which you can break the name into array and implement the logic. For example:
var x = document.getElementById("facebook_Checkbox");
//Note I have added underscore in the Id
var name = x.id;
var arr=name.split("_");
//Now you have Checkbox and Facebook as string objects (part of array) and you can use them
name=arr[0]
I hope it will solve the purpose.

Quotes in Javascript

I have been trying for hours to fix this code, I can't see what's wrong:
document.getElementById('detail'+num).innerHTML='<a class="dobpicker" href="javascript:NewCal('+s_d+','+ddmmyy+')">'
The problem is in href="javascript ..."
s_d is a javascript variable defined as
var num = 2;
var s_d = "sname"+num;
var ddmmyy = "ddmmyy";
Basically I need to call a javascript function with different parameter each time.
Use a backslash like \'.
document.getElementById('detail'+num).innerHTML=
'<a class="dobpicker" href="javascript:NewCal(\''+s_d+'\',\''+ddmmyy+'\')">'
Since this is the value of a href attribute, HTML encode them:
document.getElementById('detail'+num).innerHTML='<a class="dobpicker" href="javascript:NewCal("'+s_d+'","'+ddmmyy+'")">'
Or better yet don't use the javascript: protocol:
[0,1,2,3,4,5].forEach(function(num) {
var s_r = "sname"+num;
var ddmmyy = "ddmmyy";
var aEl = document.createElement("a");
aEl.className = "dobpicker";
aEl.onclick = function() {
NewCal(s_d, ddmmyy);
}
document.getElementById('detail'+num).appendChild(aEl);
});
Your .innerHTML setting is using s_d, but your variable declaration has s_r.
EDIT: That was the first thing that jumped out at me. Having looked a bit closer and realised the values are strings, I think fixing the variable name together with adding some escaped quotation marks as in Daniel A. White's answer will do the trick.

What is wrong with this code in jquery

I am trying to get plain text out of value stored in variable like this
var lb = $(this).attr("htmllabel");
var text = $(this).html(lb);
alert(text);
When the alert popup it give result as object[Object] but I was expecting the actual string after application of the function.
Can anyone help me in this? Thanks.
$(this).html(lb)
This line is setting the html of whatever this is to whatever is stored in lb. It then returns the jquery object for chaining purposes.
If you want the html of this then you just call $(this).html() with no parameter.
Your code on the second line is setting something not getting something ...
Can you include your HTML and the actual data you want in the alert box and this might help shape the answer
Take a look at the documentation for the html method:
http://api.jquery.com/html/#html2
As you can see from the documentation your code is setting the html for this and then returning a jQuery object. What is it that you want to display exactly?
If you're simply looking to get the value of your custom attribute "htmllabel", you can do the following:
var val = $(this).attr("htmllabel");
alter(val);
As a side note; I would suggest naming custom attributes with data-*according to the HTML5 spec like this:
<div data-htmllable></div>
Your can then access the value of the attribute in two ways (jQuery 1.4.3+):
var val1 = $(this).attr('data-htmllabel');
var val2 = $(this).data('htmllabel');
// Outputs same value //
alert(val1);
alert(val2);
I hope this helps!

Finding commas in strings using JS

I'm trying to learn JS, so forgive me if you code makes the world explode.
Anyway, I am trying to make a tagging system interface similar to SOs. Where the user types in words and SO separates them on the comma (or on spacebar but I don't want that).
I am using jQuery to access the DOM (because it is so much easier), and I know there are various plugins that could do this and feed the homeless, but as I said I want to learn.
Here's what I have so far:
<input type="textbox" name="somebox" id"someid">
$(document).ready(function() {
var startPos = 0;
$("#someid").keyup(function() {
var inputText = $(this).val();
var commaPosition = inputText.indexOf(",", startPos);
var foundWords = [];
alert('Hello'); // even this doesn't work... why???
if (commaSearch !== '-1') {
// take the word:
foundWords.push(inputText.slice(startPos,commaPosition));
startPos = commaPosition + 1;
}
});
});
It can also be found here. Nothing seems to work, not even the alert. Any help would be grateful.
Problems:
Invalid HTML - you're missing an = in between id and "someid". This will make the alert() work.
Use String.split(',') rather than String.indexOf(','). To split and get rid of extra spaces: inputText.split(/\s*,\s*/g)
I also get Uncaught ReferenceError: commaSearch is not defined. – Felix Kling
Demo with fixes: http://jsfiddle.net/mattball/2sE8b/
Is this what you want?
DEMO
$(document).ready(function() {
$("#someid").keyup(function() {
var inputText = $(this).val();
var foundWords = inputText.split(","); // or as posted elsewhere split(/\s*,\s*/g)
if (foundWords.length>1) $("#tags").html(foundWords.join(";"))
});
});
You're going to laugh, but you didn't have the = infront of the id=someid :D http://jsfiddle.net/SuperPhil/9KVs4/2/
Is this what you want?
As Matt Ball pointed out, you're missing the = sign after id in your HTML. Next, you use commaPosition then commaSearch. Next, you use the not-identity operator with a number and a string, which will always return false.

Categories

Resources