What am I doing wrong here? I even tried it with case instead of if and it does not work
function updateResultPage(the_resp,r) {
var to_alert="s";
if(the_resp=="11"){
to_alert="Thank you!!";
}
else if(the_resp=="22"){
to_alert="Error:.";
}
else if(the_resp=="33"){
to_alert="ERROR 234dfR,.";
}
alert("c "+to_alert+the_resp);
}
I get an alert that displays C s22
Why is it skipping past all the if() statements?
EDIT:
Ok, I added this code to see the exact value of resp: alert("d "+to_alert+" *"+the_resp+"*");
and the second * is coming on the next line, so it looks like i have a trimming problem...
Add
the_resp = the_resp.replace(/^\s*|\s*$/g,""); // will trim it.
at the beginning of your function.
Remove this
alert("c "+to_alert+the_resp);
or add an else
else{
alert("c "+to_alert+the_resp);
}
Might be worth checking to make sure you are passing in an actual string or string object (as opposed to say an int). May also be worth making sure there isn't any non-printing whitespace in your input by trimming appropriately..
Related
I have two variables, totalGuess and condensedAnswer. I am creating a jQuery click event and if totalGuess doesn't equal condensedAnswer then the click event will not occur and a div called message will display the message "Sorry, but your answer is incorrect. Please try again."
The problem is, totalGuess in the if statement is never equal to condensedAnswer. I've tried seeing typeof and they are both strings. I've tried console.log(totalGuess+"\n"+condensedAnswer); and they both return the same value. I've tried hardcoding the condensedAnswer, and totalGuess was able to be equal to the hardcoded answer. But when I tried comparing condensedAnswer with the hardcoded answer, it's not equal, even though the console.log value for condensedAnswer is the same. I'm not what's wrong.
Here's the code snippet:
$('.submitGuess').click(function(e){
var totalGuess = "";
var condensedAnswer = answer.replace(new RegExp(" ","g"), "");
$('.crypto-input').each(function(){
totalGuess += $(this).val();
});
// if incorrect guess
if(totalGuess !== condensedAnswer) {
$('.message').text("Sorry, but your answer is incorrect. Please try again.");
e.preventDefault();
}
// if user wins, congratulate them and submit the form
else {
return true;
}
});
If it helps, here's the page, just a random test cryptogram plugin for Wordpress:
http://playfuldevotions.com/archives/140
The problem has nothing to do with the check. The problem is the fact your value you are checking against has hidden characters. However you are getting that string has the issue.
Simple debugging shows the problem
> escape(totalGuess)
"God%27sMasterpieceMatthew15%3A99Psalms129%3A158"
> escape(condensedAnswer)
"God%27sMasterpieceMatthew15%3A99Psalms129%3A158%00"
It has a null character at the end.
Now looking at how you fill in the answer you have an array with numbers
"071,111,100,039,...49,053,056,"
Look at the end we have a trailing comma
when you do a split that means the last index of your array is going to be "" and hence why you get a null.
Remove the trailing comma and it will magically work.
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.
Hello there everyone,
I've been trying to figure out how to create a function that takes any input and adds spaces to it before returning it. For example. The function would change "hello" into "h e l l o"
When I perform the task -not- as a function, it seems to work okay. I previously had some good feedback about using the split() and join() functions and that seems to get the desired effect.
It just doesn't seem to be working as a function. Here is the code that I have come up with so far:
function sStr(aString)
{
var mySplitResult = aString.split("").join(" ");
return mySplitResult;
}
window.alert(sStr(test));
I would really appreciate any help with this as I'm racking my brains trying to learn this stuff. I can see that I still have a long way to go.
Put quotes around test like :
alert(sStr("test"));
In your code, test is not a string, but a variable. Strings need to be inserted in quotes or double quotes.
function sStr(aString)
{
return aString.split("").join(" ");
}
window.alert(sStr('test'));
Check this fiddle.
It works, just add quotes around test:
function sStr(aString)
{
var mySplitResult = aString.split("").join(" ");
return mySplitResult;
}
window.alert(sStr("test"));
It looks your function works beautifully. In this line:
window.alert(sStr(test));
Is test a variable, or did you mean to provide a string:
window.alert(sStr('test'));
While we're at it, you may want to make your function handle the cases where the (1) parameter is undefined or null and (2) the parameter is not a string (e.g.: numbers):
function sStr(aString)
{
if(!aString)
{
return "";
}
var mySplitResult = aString.toString().split("").join(" ");
return mySplitResult;
}
So I am trying to make a string out of a string and a passed variable(which is a number).
How do I do that?
I have something like this:
function AddBorder(id){
document.getElementById('horseThumb_'+id).className='hand positionLeft'
}
So how do I get that 'horseThumb' and an id into one string?
I tried all the various options, I also googled and besides learning that I can insert a variable in string like this getElementById("horseThumb_{$id}") <-- (didn't work for me, I don't know why) I found nothing useful. So any help would be very appreciated.
Your code is correct. Perhaps your problem is that you are not passing an ID to the AddBorder function, or that an element with that ID does not exist. Or you might be running your function before the element in question is accessible through the browser's DOM.
Since ECMAScript 2015, you can also use template literals (aka template strings):
document.getElementById(`horseThumb_${id}`).className = "hand positionLeft";
To identify the first case or determine the cause of the second case, add these as the first lines inside the function:
alert('ID number: ' + id);
alert('Return value of gEBI: ' + document.getElementById('horseThumb_' + id));
That will open pop-up windows each time the function is called, with the value of id and the return value of document.getElementById. If you get undefined for the ID number pop-up, you are not passing an argument to the function. If the ID does not exist, you would get your (incorrect?) ID number in the first pop-up but get null in the second.
The third case would happen if your web page looks like this, trying to run AddBorder while the page is still loading:
<head>
<title>My Web Page</title>
<script>
function AddBorder(id) {
...
}
AddBorder(42); // Won't work; the page hasn't completely loaded yet!
</script>
</head>
To fix this, put all the code that uses AddBorder inside an onload event handler:
// Can only have one of these per page
window.onload = function() {
...
AddBorder(42);
...
}
// Or can have any number of these on a page
function doWhatever() {
...
AddBorder(42);
...
}
if(window.addEventListener) window.addEventListener('load', doWhatever, false);
else window.attachEvent('onload', doWhatever);
In javascript the "+" operator is used to add numbers or to concatenate strings.
if one of the operands is a string "+" concatenates, and if it is only numbers it adds them.
example:
1+2+3 == 6
"1"+2+3 == "123"
This can happen because java script allows white spaces sometimes if a string is concatenated with a number. try removing the spaces and create a string and then pass it into getElementById.
example:
var str = 'horseThumb_'+id;
str = str.replace(/^\s+|\s+$/g,"");
function AddBorder(id){
document.getElementById(str).className='hand positionLeft'
}
It's just like you did. And I'll give you a small tip for these kind of silly things: just use the browser url box to try js syntax. for example, write this: javascript:alert("test"+5) and you have your answer.
The problem in your code is probably that this element does not exist in your document... maybe it's inside a form or something. You can test this too by writing in the url: javascript:alert(document.horseThumb_5) to check where your mistake is.
Another way to do it simpler using jquery.
sample:
function add(product_id){
// the code to add the product
//updating the div, here I just change the text inside the div.
//You can do anything with jquery, like change style, border etc.
$("#added_"+product_id).html('the product was added to list');
}
Where product_id is the javascript var and$("#added_"+product_id) is a div id concatenated with product_id, the var from function add.
Best Regards!
var tagMatch;
if (tagMatch = window.location.href.match(/\/questions\/ask\?tags=([^&]+)/)) {
$(function() {
if (!$('#tagnames').val().length) {
$('#tagnames').val(unescape(match[1].replace(/\+/g, ' '));
}
});
}
Hi all, this JS code is supposed to match the latter-part of a URL of the form /questions/ask?tags=some-tag, and then plug the text contained in the part of the URL after tags= into a textbox with the id #tagnames. What am I doing wrong? How can I fix this?
I'm still learning so if you would want to show me how to fix my regex or anything else, please do!
I think the error is with this line
if (!$('#tagnames').val().length)
length will return a number and check that against number.
Something like
if ($('#tagnames').val().length > 0)
I don't think there is a need to place document ready inside the if statement. Isn't this better.
$(function() {
var tagMatch;
if (tagMatch = window.location.href.match(/\/questions\/ask\?tags=([^&]+)/))
{
if ($('#tagnames').val().length > 0)
{
$('#tagnames').val(unescape(match[1].replace(/\+/g, ' '));
}
}
});
Without looking too much into how the string matching works...
You seem to be defining and setting a variable called tagMatch, but then you're using a variable called match to set the value.
Is that the problem?
Update: Apologies - your regex is correct - I misread the intention :)