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!
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.
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');
}
})
})
Related
I'm looking for some support with this math's project I'm doing. Basically I've created four boxes, and populated one with the correct answer. When I click on the correct answer, the if statement doesn't run; it always shows as wrong.
I include a snippet, if someone can see something glaringly wrong then I'd appreciate a response.
I'm only trying it with box 1 to see if it works, and the correct answer does populate in 1 of the 4 boxes, however it always says it's the wrong answer, even when correct answer is in box1.
document.getElementById("box1").onclick = function() {
if (playing == true) {
if (this.innerHTML == correctAnswer) {
score++;
document.getElementById("scorevalue").innerHTML = score;
hide("wrong");
show("correct");
setTimeout(function() {
hide("correct");
}, 1000);
} else {
hide("correct");
show("wrong");
setTimeout(function() {
hide("wrong");
}, 1000);
}
}
}
Instead of comparing two values with ==, try === in your if-statements.
Example: if (playing === true) {
This is most likely related to your HTML, and the way you have setup your tags. For example, if box1 is a div, then if your code looks like this:
<div id="box1">
answer
</div>
Then in some explorers, specifically Chrome and FireFox, it considers linebreak as empty space.
So, if var correctAnswer = "answer";
and you compare correctAnswer with box1.innerHTML like so:
if (correctAnswer == box1.innerHTML)
Then you will always get false returned.
In order to fix the issue, change your HTML like so:
<div id="box1">answer</div>
Basically remove the linebreaks.
Everything else seems to be fine.
I have a web page with a form on it. The "submit" button is supposed to remain deactivated until the user fills in all the necessary fields. When they fill in a field, a checkmark appears next to it. When all the checkmarks are there, we're good to go.
A checkmark might be set by code like this:
if (whatever) checkLocation.innerHTML = CHECKMARK;
Here's the code I'm using to do the final check. It just loops through all the locations where there may be checkmarks. If it finds a location without a mark, it disables the submit button and leaves. If it gets through them all, it activates the button and returns true.
function checkSubmitButton() {
var button = document.getElementById(SUBMIT_BUTTON);
for (var i=0; i<CHECK_LOCATIONS.length; i++) { // should be for-each, but JS support is wonky
var element = document.getElementById(CHECK_LOCATIONS[i]);
console.log(CHECK_LOCATIONS[i] +": " +element.innerHTML);
// if found unchecked box, deactivate & leave
if (element.innerHTML != CHECKMARK) {
button.disabled = true;
return false;
}
}
// all true--activate!
console.log("ACTIVATING BUTTON!");
button.disabled = false;
return true;
}
Here's the problem: this works so long as the const CHECKMARK contains something simple, like "X". But specs call for a special HTML character to be used: in this case ✓, or ✓. When I do the comparison (in the if line) it ends up comparing the string "✓" to the string "✓". Since these two are not equal, it doesn't recognize a valid checkmark and the button never activates. How can I compare the contents of the HTML element my constant? (And hopefully make the code work even if down the road somebody replaces the checkmark with something else.)
Thanks.
There is no problem with the check character and it behaves exactly like the X character. The problem is, that your html have the checkmark character stored as html entity in hex string. If you compare checkmark to checkmark it works just fine: https://jsfiddle.net/m7yoh026/
What you can do in your case is to make sure the CHECKMARK variable is the actuall checkmark character, not the html entity.
Other option is to decode the html entity: https://jsfiddle.net/m7yoh026/3/
var CHECKMARK = '✓'
var decoded_checkmark = $('<textarea />').html(CHECKMARK).text();
console.log($('div')[0].innerHTML)
if ($('div')[0].innerHTML == decoded_checkmark) {
$('body').append('checkmark recognized<br>')
}
You can convert a character to its HTML entity equivalent like so:
var encoded = raw.replace(/[\u00A0-\u9999<>\&]/gim, function(i) {
return '&#'+i.charCodeAt(0)+';';
});
Well, here's what I ended up doing: I made a function called encodeHtml() that takes a character or string, writes it to a brand new div, and then returns what's contained in that div:
function encodeHtml(character) {
var element = document.createElement("div");
element.innerHTML = character;
return element.innerHTML;
}
Then I can compare to what it returns, since it automatically changes "✓" to "✓", and will work with any unforeseen changes to that character. It's a bit of a kludge, but it works. (It's still not clear to me why JavaScript does this automatic conversion...but there are many design choices in which JavaScript mystifies me, so there you go.)
Thanks all for the help.
I am running this code:
if (div == '') {
console.log("hi"),
document.getElementById('divd').innerHTML = first,
$('draggablelamb').addClass('fade'),
$('droppable').addClass('bowl');
}
When the user presses a button (there are variables that I have left out and the elseif and else statements). However, when I run it in the browser it only goes past the first two lines of code (console.log("hi") and document.getElementById('divd').innerHTML = first) and then skips the rest and goes onto the next elseif. Why is it doing it? How can I stop it from doing this?
Update:
I now know that it goes past all the lines of code by using this:
console.log("Hi");
document.getElementById('divd').innerHTML = first;
console.log("Hello again");
$('draggablelamb').addClass('fade');
console.log("Bonjour");
$('droppable').addClass('bowl');
console.log("Guten Tag");
but just maybe doesn't carry it out?
Remove the , from the end of the first three statements.
Try,
if (div == '') {
console.log("hi");
document.getElementById('divd').innerHTML = first;
$('.draggablelamb').addClass('fade'); // add dot in the selector if it is a class
$('.droppable').addClass('bowl'); // add dot in the selector if it is a class
}
if (div == '') {
console.log("hi");
$('#divd').html(first);
$('.draggablelamb').addClass('fade');
$('.droppable').addClass('bowl');
}
1. You had commas , at the end of each line. It should be semi-colons ;.
2. You were selecting elements by class but missing the full-stop class selector .. So you had $('draggablelamb') when it should be $('.draggablelamb').
3. You've used jQuery for the selectors, so you can also use jQuery to write the innerHTML. Like this $('#divd).html(first);.
Your selectors are looking for the elements draggablelamb and droppable, but they won't find any, as there are no such elements in HTML.
Searching for something that isn't there will result in an empty jQuery object, and it will still accept calls that would change the elements in it, and simply do nothing.
If you are looking for elements with classes by those names, you need periods before the class names in the selectors:
$('.draggablelamb').addClass('fade');
$('.droppable').addClass('bowl');
Also, as Rajaprabhu Aravindasamy pointed out, commas aren't used between statements in Javascript. Although it would still work in this case, because there is a comma operator that can be used between expressions, it can cause problems in other cases.
I have a PHP form validation function that I developed in chrome and now will not work in firefox or Opera.
The function checks to see if a section of the form is blank and shows and error message. If there is no error then then the form submits through document.events.submit();
CODE:
function submit_events()
{
//Check to see if a number is entered if the corosponding textbox is checked
if (document.events.dj_card.checked == true && dj_amount.value==""){
//Error Control Method
//alert ('You didn\'t enetr an Amount for DJ\'s Card!');
var txt=document.getElementById("error")
txt.innerHTML="<p><font color=\"#FF0000\"> You didn\'t enetr an Amount for DJ\'s Card!</font></p>";
window.document.getElementById("dj_card_label").style.color = '#FF0000';
//Reset
window.document.getElementById("company_amount_label").style.color = '#000000';
window.document.getElementById("own_amount_label").style.color = '#000000';
}else{
document.events.submit();
}
The document.events.submit();does work across all my browsers however the check statements do not.
If the box is not ticked the form submits. If the box is ticked it does not matter whether there is data in the dj_amount.value or not. The form will not submit and no error messages are displayed.
Thanks guys.
Here are some things I noticed. Not sure if it will solve the problem, but you need to fix some of these; some of them are just observations.
dj_amount is not declared nor referenced; my guess is you mean documents.events.dj_amount
You should put a ; at the end of every statement in javascript, including the end of var txt = document.getElementById("error")
You don't need to escape the string in the txt.innerHTML line; you only need to escape like quotes, such as "\"" or '\'', not "'" or '"'
You don't need the window.document referenced; document will do in almost all cases
EDIT - As Guffa points out, FONT is an old and deprecated element in HTML. It's not the cause of your problems, but modern markup methods mean you don't need it. Consider omitting and applying the style to the paragraph tag instead.
See edits below.
function submit_events() {
//Check to see if a number is entered if the corosponding textbox is checked
if (document.events.dj_card.checked == true && document.events.dj_amount.value == "") {
//Error Control Method
//alert ('You didn't enetr an Amount for DJ\'s Card!');
var txt = document.getElementById("error");
txt.innerHTML = "<p style=\"color: #FF0000;\"> You didn't enter an Amount for DJ's Card!</p>";
document.getElementById("dj_card_label").style.color = '#FF0000';
//Reset
document.getElementById("company_amount_label").style.color = '#000000';
document.getElementById("own_amount_label").style.color = '#000000';
} else {
document.events.submit();
}
}
Consider Firebug so that you can see and log to console javascript errors and messages:
http://getfirebug.com
I believe one of the above answers would solve your problem. For future reference, although it might not be suitable for your project, please know that writing forms and javascript feedback is much easier and faster when you use a library like jQuery.
To have minimal changes in code, just add this line before the first if statement:
var dj_amount = document.forms["events"].elements["dj_amount"];
However your code need serious optimization let us know if you're interested.
Edit: here is the optimization. First the "small" things - instead of whatever you have now for "error" container, have only this instead:
<p id="error"></p>
Now add this CSS to your page:
<style type="text/css">
#error { color: #ff0000; }
</style>
This will take care of the red color, instead of hard coding this in the JS code you now control the color (and everything else) from within simple CSS. This is the correct approach.
Second, right now you are submitting the form as response to onclick event of ordinary button. Better approach (at least in my humble opinion) is having submit button then overriding the form onsubmit event, cancelling it if something is not valid. So, first you have to change the function name to be more proper then have proper code in the function. Cutting to the chase, here is the function:
function ValidateForm(oForm) {
//declare local variables:
var oCardCheckBox = oForm.elements["dj_card"];
var oAmoutTextBox = oForm.elements["dj_amount"];
//checkbox cheched?
if (oCardCheckBox.checked) {
//store value in local variable:
var strAmount = oAmoutTextBox.value;
//make sure not empty:
if (strAmount.length == 0) {
ErrorAndFocus("You didn't enter amount for DJ's Card!", oAmoutTextBox);
return false;
}
//make sure it's numeric and positive and not too big:
var nAmount = parseInt(strAmount, 10);
if (isNaN(nAmount) || nAmount < 1 || nAmount > 1000000) {
ErrorAndFocus("DJ's Card amount is invalid!", oAmoutTextBox);
return false;
}
}
//getting here means everything is fine and valid, continue submitting.
return true;
}
As you see, when something is wrong you return false otherwise you return true indicating the form can be submitted. To attach this to the form, have such form tag:
<form ... onsubmit="return ValidateForm(this);">
And instead of the current button have ordinary submit button:
<input type="submit" value="Send" />
The code will be called automatically.
Third, as you can see the function is now using "helper" function to show the error and focus the "misbehaving" element - this makes things much more simple when you want to validate other elements and show various messages. The function is:
function ErrorAndFocus(sMessage, element) {
var oErrorPanel = document.getElementById("error");
oErrorPanel.innerHTML = sMessage;
document.getElementById("dj_card_label").style.color = '#FF0000';
document.getElementById("company_amount_label").style.color = '#000000';
document.getElementById("own_amount_label").style.color = '#000000';
}
Last but not least, the "new" code also makes sure the amount is positive number in addition to check its existence - little addition that will prevent server side crash.
Everything else is pretty much self explanatory in the function: naming conventions, using local variables.... most important is have as little redundancy as possible and keep the code readable.
Hope at least some of this make sense, feel free to ask for clarifications. :)
You should bring up the error console so that you see what the error actually is.
Lacking that information, I can still make a guess. Try some less ancient HTML code; the parser can be picky about code you add to the page using innerHTML:
txt.innerHTML="<p style=\"color:#FF0000\"> You didn\'t enetr an Amount for DJ\'s Card!</p>";
I know this issue has been touched on here but I have not found a viable solution for my situation yet, so I'd like to but the brain trust back to work and see what can be done.
I have a textarea in a form that needs to detect when something is pasted into it, and clean out any hidden HTML & quotation marks. The content of this form is getting emailed to a 3rd party system which is particularly bitchy, so sometimes even encoding it to the html entity characters isn't going to be a safe bet.
I unfortunately cannot use something like FCKEditor, TinyMCE, etc, it's gotta stay a regular textarea in this instance. I have attempted to dissect FCKEditor's paste from word function but have not had luck tracking it down.
I am however able to use the jQuery library if need be, but haven't found a jQuery plugin for this just yet.
I am specifically looking for information geared towards cleaning the information pasted in, not how to monitor the element for change of content.
Any constructive help would be greatly appreciated.
I am looking at David Archer's answer and he pretty much answers it. I have used in the past a solution similar to his:
$("textarea").change( function() {
// convert any opening and closing braces to their HTML encoded equivalent.
var strClean = $(this).val().replace(/</gi, '<').replace(/>/gi, '>');
// Remove any double and single quotation marks.
strClean = strClean.replace(/"/gi, '').replace(/'/gi, '');
// put the data back in.
$(this).val(strClean);
});
If you are looking for a way to completely REMOVE HTML tags
$("textarea").change( function() {
// Completely strips tags. Taken from Prototype library.
var strClean = $(this).val().replace(/<\/?[^>]+>/gi, '');
// Remove any double and single quotation marks.
strClean = strClean.replace(/"/gi, '').replace(/'/gi, '');
// put the data back in.
$(this).val(strClean);
});
You could check out Word HTML Cleaner by Connor McKay. It is a pretty strong cleaner, in that it removes a lot of stuff that you might want to keep, but if that's not a problem it looks pretty decent.
What about something like this:
function cleanHTML(pastedString) {
var cleanString = "";
var insideTag = false;
for (var i = 0, var len = pastedString.length; i < len; i++) {
if (pastedString.charAt(i) == "<") insideTag = true;
if (pastedString.charAt(i) == ">") {
if (pastedString.charAt(i+1) != "<") {
insideTag = false;
i++;
}
}
if (!insideTag) cleanString += pastedString.charAt(i);
}
return cleanString;
}
Then just use the event listener to call this function and pass in the pasted string.
It might be useful to use the blur event which would be triggered less often:
$("textarea").blur(function() {
// check input ($(this).val()) for validity here
});
Edited from the jquery docs..
$("textarea").change( function() {
// check input ($(this).val()) for validity here
});
Thats for detecting the changes. The clean would probably be a regex of sorts
edited above to look for a textarea not a textbox