Compare variable against test strings - javascript

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");

Related

How to detect specific attribute with specific text inside

I want to be able to specify that IF data-path == "USB/sda1-usb-SanDisk_Cruzer_B" then do code etc data-path is my attribute.
Any idea how to do this with JS? document.getelementbyid i dont think has the extension for it but perhaps im wrong? I couldnt find anything anywhere for it.
I also know that you can use:
document.getElementById("db-1").hasAttribute("data-path");
But thats if it has it which it does but i want to check inside and match.
Thanks!
try the getAttribute method
var attrValue = document.getElementById("db-1").getAttribute("data-path");
if ( attrValue == "USB/sda1-usb-SanDisk_Cruzer_B" )
{
//your code here
}
This way ?
let path=document.getElementById("db-1").dataset.path;
if(path==="USB/sda1-usb-SanDisk_Cruzer_B"){
//do stuff
}
The HTMLElement.dataset property allows access, both in reading and writing mode, to all the custom data attributes (data-*) set on the element. It is a map of DOMString, one entry for each custom data attribute.
Code:
var el = document.getElementById('db-1');
if (el && el.dataset.path === 'USB/sda1-usb-SanDisk_Cruzer_B') {
// Your code...
}

Reassigning a value to a variable

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');
};

How do I find specific words in elements with specific classes with Javascript/jQuery?

I have a class for DIVs called .post and I'd like to find words inside that element and replace them with something else. That words must also not be inside elements with other classes (.tiptrig and .postheader).
I'd really like to achieve this but I don't know how... I am new to Javascript and especially jQuery.
Seems like an easy task.
$('.post').each(function() {
$(this).html(function(index, html) {
return html.replace(/THEWORD/g, 'something else');
});
});
This would iterate over all nodes which own the class .post and replace the word THEWORD with something else. Be aware of that his is dangerous too because you could also modify HTML tag names for instance. So this only makes sense if you want to add/modify HTML code aswell.
demo: http://www.jsfiddle.net/XGuGy/
Probably a better idea to access the text():
$('.post').each(function() {
var $this = $(this);
if( !$this.closest('.postheader').length && !$this.closest('.tiptrig ').length ) {
$this.text(function(index, text) {
return text.replace(/you/g, 'you fool');
});
}
});
demo: http://www.jsfiddle.net/XGuGy/1/

find text wrapped in brackets in jQuery

I have some text on a page and I want to located and remove any text found in brackets.
For example:
<td>here is [my text] that I want to look at</td>
So I want to grab that text (my text), save it in a variable and remove it from where it is.
If you're using jQuery you could use a regular expression like \[(.+)\] on $('body').text().
EDIT: Sorry, I might have jumped the gun a little bit giving you this answer. Going to think about it for a few more minutes and try to update this with a little more info.
You may find that this task is not all that simple. If you have control over the text before it is sent to the web browser you may want to put a <span class='bracket'>[my text]</span> around the text, then you could easily do something like this with jQuery:
$(".bracket").each(function() {
// store the data from $(this).text();
}).remove();
This can be done using regular expressions and jQuery, but there are problems that may creep up dealing with text inside of attributes like <input name='test[one][]' /> The "simple" regex would be to do something like this:
$("td").each(function() {
var $this = $(this);
var html = $this.html();
var bracketText = [];
// match all bracketed text in the html - replace with an empty string
// but push the text on to the array.
html = html.replace(/\[([^\]]+)\]/g, function() {
bracketText.push(arguments[1]);
return "";
});
// put the new html in away and save the data for later
$this.html(html).data("bracketText", bracketText);
});
There is not much danger in doing this if you're sure you wont have [] inside of tags other than in the text.
I ended up doing the following:
$('#formQuizAnswers td.question').each(function(){
var header = $(this).text().match(/-.*-/);
$(this).text($(this).text().replace(header,''));
});
I changed my text I search for to have dashes around it IE -My text-

JavaScript: Dynamic Field Names

HI All,
I have a piece of javaScript that removes commas from a provided string (in my case currency values)
It is:
function replaceCommaInCurrency(myField, val)
{
var re = /,/g;
document.net1003Form.myField.value=val.replace(re, '');
}
'MyField' was my attempt to dynamically have this work on any field that I pass in, but it doesn't work, I get errors saying 'MyField' is not valid. I sort of get my, but I thought this was valid.
I am calling by using: onBlur="replaceCommaInCurrency(this.name, this.value);return false;"
this.name and this.value are passing in the right values...field name and its value.
How do I do this dynamically?
-Jason
You can use eval to make your code snippet work:
eval("document.net1003Form." + myField + ".value=val.replace(re, '');");
As mentioned below, the square brackets work (and don't suck like eval), stupid me for forgetting about those:
document.net1003Form[myField].value=val.replace(re, '');
Alternatively, try something like this:
function replaceCommaInCurrency(field){
var re = /,/g;
field.value = field.value.replace(re, '');
}
Which gets called like so:
onBlur="replaceCommaInCurrency(this); return false";
You should consider using a javascript toolkit for things like this. You could set a class like "currency" on each input, then use this snippet of jQuery based Javascript to handle everything:
$(function(){
$("input.currency").bind('blur', function(){
this.value = $(this).val().replace(',', '');
})
});
This code would fire on document ready, attach an event handler to each input with currency as its class, and then do the replacements. Note that you don't need a regex for replacement as well.
If you code it right into the markup like that, e.g. onblur="replaceCommaInCurrency(this)", the control originating the event gets passed as the parameter. Then you should be able to do something like:
myField.value = myField.value.replace(re, '');
with jQuery:
var jqField = $(myField);
jqField.val(jqField.val().replace(re, ''));
In general, you should be using a framework that will handle low level functionality like this, but the specific answer to your question is to use bracket notation for the field name:
function replaceCommaInCurrency( myField, val)
{
var re = /,/g;
document.net1003Form[myField].value=val.replace(re, '');
}
function removeCommaInCurrency(myField)
{
var re = /,/g;
myField.value=myField.value.replace(re, '');
}
-- and then call it like this:
<input type="text" name="..." onchange="removeCommaInCurrency(this);">
flatline and roenving's solution with ‘this’ is the cleaner approach, it also avoids the problems of ‘document.formname.fieldname’.
(Use ‘document.forms.formname’ to access a form without possible clashing on forms having the same name as members of the document object, and ‘forms.elements.fieldname’ to do the same with fields. Like all JavaScript object, object[namevariable] can also be used. Or, better, add IDs and use the unambiguous document.getElementById method.)
By moving binding into the script you can also remove the inline JavaScript of the onclick attribute, making the markup cleaner still:
<input type="text" class="number" name="something" />
...
<script type="text/javascript"> // external script is best, linked after all forms
function numberfield_bind() {
var inputs= document.getElementsByTagName('input');
for (var inputi= inputs.length; inputi-->0;)
if (inputs[inputi].className=='number')
inputs[inputi].onchange= numberfield_change;
}
function numberfield_change() {
this.value= this.value.split(',').join('');
}
numberfield_bind();
</script>

Categories

Resources