Reputation: 85
Using a WYSIWYG type web page creator that links up to various databases to pull in information from the clients servers.
One variable is for frequency and has three possible outputs, MO, YR or it is blank.
This is my HTML for one place (this can appear multiple times, just switching out the 1 with the next number)
<span style="font-size:24px;"><strong>$@@1_Price</strong></span><span style="font-size:18px;" class="rateFrequency">@@1_rateFrequency</span>
I am looking to use javascript to replace the MO or YR with /month and /year and doing nothing when it fills in blank.
Not much knowledge in javascript, so not sure where to begin. Was thinking somthing along the lines of this, but not sure if I am going in the right direction or where to move forward from here
<script>
window.onload=function change() {
var frequency = document.getElementsByClassName("rateFrequency");
if (condition1) {
block of code to be executed if condition1 is true
} else if (condition2) {
block of code to be executed if the condition1 is false and condition2 is true
} else {
block of code to be executed if the condition1 is false and condition2 is false
}
}
change();
</script>
Anything to help me move forward would be great. Thanks!
Upvotes: 0
Views: 93
Reputation: 2766
Assuming I have understood your requirements correctly, the following code should do the trick, no matter how many "rateFrequency" spans are in the HTML document.
window.onload = function(e) {
function changeFreq() {
var els = document.getElementsByClassName("rateFrequency"),
len = els.length;
while (len--){
els.item(len).innerText = els.item(len).innerText.replace('MO', '/month').replace('YR', '/year');
}
}
changeFreq();
};
No if
is required here. If the text contained in the span is 'MO', the first replace
will replace it with '/month' and the second replace won't do anything. If the text contained in the span is 'YR', the first replace
won't do anything, and the second replace
will replace it with '/year'. If the text in the span is anything other than 'MO' or 'YR', neither replace
will do anything, and the text in the span will remain unchanged.
Upvotes: 2
Reputation: 539
I have made codepen for you to take a look at. It uses jquery, which I suggest you use because it is awesome!
Let me know if you have question: Example
$(document).ready(function(){
$.each($('.rateFrequency'),function(){
frq = $(this).text();
if (frq=='MO'){
console.log('REPLACE MONTH');
$(this).text('/month');
}else if(frq=='YR'){
console.log('REPLACE YEAR');
$(this).text('/year');
}
})
})
Upvotes: -1