Javascript function skips statements - javascript

I have a simple function as follows:
function FUNCTION1() {
document.getElementById('Preview1').innerHTML = ''){
if (document.UserData.input1.value.length !== 0;
var input1 = document.UserData.input1.value;
document.getElementById('Preview1').innerHTML = '<div>Hello ' + input1 + '</div>';}
}
I run the above script and everything is just fine.
Then I run another function to clear the div which has the form "UserData".
document.getElementById('UserDataDiv').innerHTML = '';
And then I run the FUNCTION1 again, It brings up old value This value should not be there as div was cleared.
Is there a way to avoid this behaviour or am i doing something wrong?

I think you should just check that the string is empty instead of the length of the value: document.UserData.input1.value.length:
if (document.UserData.input1.value == '')
Oh, as someone else has pointed out, it also looks like there's an extra semi-colon at the end of your first line.

Related

jQuery Math - No calculation with empty fields

I have a simple parse to get the sum of a collection of textareas. It works fine, but if there's no value placed in the field, then the calculation just doesn't run.
How can I make the default value 0 without having the contents actually have to be 0? Like, I don't want the fields to load up with a 0 already waiting in the box - I just want the formula to not worry about empty fields.
Here's the jQuery:
jQuery(document).ready(function(){
jQuery(".button1").click(function(){
var set1 = function() {
var calc1 = 0;
$('.calc1').each( function(index,item) {
calc1 += parseInt(jQuery(item).val());
});
$('.result1').html(calc1);
}
set1();
});
});
The codepen can be seen here if you'd like to get a better idea: https://codepen.io/JTBennett/pen/NENMdP
I appreciate any help with this! I know it's probably a stupid mistake, but I've tried a few different things and not gotten anywhere yet.
Try parseInt(jQuery(item).val() || 0). The || operator will return the second value if the first is falsey. Therefore if the value is empty, it will try to parse '0' which it will successfully.
Just make an if statement that looks for an empty field and then replace it with 0.
$('.calc1').each( function(index,item) {
var itemValue = jQuery(item).val();
if (itemValue === "") {itemValue = 0;}
calc1 += parseInt(itemValue);
});
You can just replace your line with this:
calc1 += parseInt(jQuery(item).val() || 0);

how to remove HTML tags from a string in JavaScript without using regexp?

I am new to programming and I was solving this exercise.
I have tried 3 loops with string.slice() but for some reason it prints an empty string.
Would you please explain what happens inside my code and why it prints the wrong output and how I can correct, rather than giving me your version of the correct answer, so that I can learn from my mistakes.
the test input is
<p><strong><em>PHP Exercises</em></strong></p>
and output should be PHP Exercises
p.s this is not a PHP exercise, I'm not confused
here is my code :
function remove(answer){
var sen = answer.split("");
var arr = [];
for (var i = 0; i<answer.length; i++){
if (answer[i] == "<"){
for (var j = i; j<answer.length; j++){
if (answer[j] == ">"){
for (var k = j; k<answer.length; k++){
if (answer[k] == "<"){
return answer.slice(j+1, k);
}
}
}
}
}
}
}
Try this:
function stripTags(data)
{
var tmpElement = document.createElement("div");
tmpElement.innerHTML = data;
return tmpElement.textContent || tmpElement.innerText || "";
}
var something = '<p><strong><em>PHP Exercises</em></strong></p>';
alert(stripTags(something));
or You can use string.js (string.js link):
var S = window.S;
var something = '<p><strong><em>PHP Exercises</em></strong></p>';
something = S(something).stripTags().s;
alert(something);
<script src="https://raw.githubusercontent.com/jprichardson/string.js/master/dist/string.min.js"></script>
if You're trying nodejs so:
var S = require('string');
var something = '<p><strong><em>PHP Exercises</em></strong></p>';
something = S(something).stripTags().s;
console.log(something);
As to why the provided code isn't working, the code returns when j = 2 and k = 3. I discovered this by writing console.log(j, k); immediately before the return. This insight made it clear that the code is identifying the first set of open tags, when actually you seem to want to identify the open and closed "em" tags. The answers provided by others are more robust, but a quick fix to your code is:
change
if (answer[i] == "<"){
to
if (answer.slice(i, i+3) == "<em"){
Hope this helps!
Your code does not account for ... nothing. It simply stops at the first encounter of what's between ">" and "<", which is, in the first case, is nothing! You should check if a character is present, and move on if not.
Honestly, this is one of those useless exercises that text books use to try to get you to think outside the box. But you will never want to loop through a string to find text between tags. There are so many methods built in to JavaScript, it's literally reinventing the wheel to do this... that is if a wheel were really a for-loop.
If you really want to avoid Regex and other built in functions so that you can learn to problem solve the long way, well try slicing by brackets first!

Radio Button Validation: I could validate it but I cant figure out the reason

I was stuck trying to validate if a radiobutton was selected or not and, in consequence, show alerts. Well, I found the mistake (I was putting the conditional statement inside the loop).
Even I solved the problem, I can’t figure out yet why my code works correctly outside the loop but doesn’t work inside it. Now I'm stuck with this.
I appreciate if anyone can tell me what’s the reason.
Below you'll see both JS codes, but here you have the fiddles examples:
JSFiddle that doesn't work
JSFiddle that works
This is the JS code that doesn’t work:
var getForm = document.getElementById('formX');
var putForm = getForm.onsubmit = showIt;
function showIt(){
var getNames = document.getElementsByName('season');
var result = false;
for(var i = 0; i < getNames.length; i++){
if(getNames[i].checked){
result = true;
break;
}
if(result === false){
alert('Please, choose an option');
return false;
}else{
alert('You\'ve choosen ' + getNames[i].value)
}
}//Loop ends here.
}
And this is the JS code that works without problems:
var getForm = document.getElementById('formX');
var putForm = getForm.onsubmit = showIt;
function showIt(){
var getNames = document.getElementsByName('season');
var result = false;
for(var i = 0; i < getNames.length; i++){
if(getNames[i].checked){
result = true;
break;
}
}//Loop ends here.
if(result === false){
alert('Please, choose an option');
return false;
}else{
alert('You\'ve choosen ' + getNames[i].value)
}
}
Maybe the for loop in JS code that doesn’t work has a wrong logic, it means that if the first radiobutton checked, the for loop stops; if the first radiobutton does not checked, it will alert 'Please, choose an option' and stops the for loop. The logic only validates the first radiobutton. Maybe thats the problem.
It's because of your break; line.
When it's inside the loop you're breaking it out on true before it has a chance to hit the following code: if(result === false)
break is breaking out of the entire loop which means it never hit's your if(result===false)
Hope that helps!
Wrong logic inside the loop, try this:
var getForm = document.getElementById('formX');
var putForm = getForm.onsubmit = showIt;
function showIt(){
var getNames = document.getElementsByName('season');
var result = false;
for(var i = 0; i < getNames.length; i++){
if(getNames[i].checked){
alert('You\'ve chosen ' + getNames[i].value)
result = true
}
if (i == getNames.length - 1 && !result)
{
alert('Please, choose an option')
}
}
}
If your question is how do I make it work, there are several good suggestions in the answers.
If you want to know: "Why didn't it work using the first method?" The best answer is that the break; line was causing your loop to terminate immediately, and therefore preventing the alert("You've chosen...") from having the opportunity to trigger.

jquery each loop only looping once and if using else code stops

I've got two problems with the following javascript and jquery code.
The jquery each loop only iterates once, it gets the first element with the right ID does what it needs to do and stops.
The second problems is that when I use the else in the code the one inside the each function, it doesn't even tries the next if, it just exits there.
I'm probably doing something fundamental wrong, but from the jquery each function and what I'd expect from an else, I don't see it.
Javascript code:
var $checkVal;
var $checkFailed;
$("#compliance").live("keypress", function (e) {
if (e.which == 10 || e.which == 13) {
var checkID = $(this).parents('td').next().attr('id');
var checkVal = $(this).val();
$('#' + checkID).each(function () {
var cellVal = $(this).text();
if (checkVal == cellVal) {
$(this).removeClass("compFail").addClass("compOk");
} else {
$(this).removeClass("compOk").addClass("compFail");
var checkFailed = True;
}
});
if (checkFailed == 'True') {
(this).addClass("compFail");
} else {
(this).addClass("compOk");
}
}
});
How could I get the each loop to iterate through all instances of each element with the id assigned to the variable checkID, and get the code to continue after the else, so it can do the last if?
An id should appear on a page only once. If you want to have multiple elements with same id, then use a class, not an id.
Your each loop iter only once because you are selecting by id thus you are selecting only one element in the page. If you change you elements to a class it should work like you expect.
This is to illustrate what I'm talking about in my comment, so that you do not remove the wrong var:
var checkVal;
var checkFailed;
$("#compliance").live("keypress", function (e) {
if (e.which == 10 || e.which == 13) {
var checkID = $(this).parents('td').next().attr('id');
//HERE is the first edit
checkVal = $(this).val();
$('#' + checkID).each(function () {
var cellVal = $(this).text();
if (checkVal == cellVal) {
$(this).removeClass("compFail").addClass("compOk");
} else {
$(this).removeClass("compOk").addClass("compFail");
//HERE is the second
checkFailed = True;
}
});
if (checkFailed == 'True') {
(this).addClass("compFail");
} else {
(this).addClass("compOk");
}
}
});
Normally, the way you have it would cause a compile-time error (in a typed language like C#) for redeclaring a variable. Here, it's not clear to me if it will be used as a local variable (ignoring your global variable) or if javascript will combine them and consider them the same. Either way, you should use it as I have shown so that your intent is more clear.
EDIT: I have removed the $ from your variables (var $checkVal) as on jsFiddle it was causing issues. SO if you do not need those $'s, then remove them. Also, note that testing on jsFiddle indicates that you do not need to change your code (other than possibly removing the $ from your declaration) as javascript appears to consider them the same variable, despite the redeclaration, which I find a bit suprising tbh.
The jquery each loop only iterates once, it gets the first element
with the right ID does what it needs to do and stops.
Yes, this is absolutely right for the code you're using:
$('#' + checkID).each(function(){};)
ID attributes are unique. There must be only one element with a given ID in the DOM. Your selector can match only one element. You are iterating over a collection containing just 1 item.

Javascript - making form inputs appear needed through key input

I have a form that has five text inputs, a through e. I set it though so only the first two are visible through the css:display, and I set the last three to display:none initially.
I have my javascript so that it sets the last input to 'b', and the next input to 'c', and depending on whether the other texts are empty or not changes the last and next variables.
option-a, option-b, etc. is the id of the text box in the form
answer_answera, answer_answerb, etc. is the class of the form input
<script>
var last = 'b';
var next = 'c';
if (document.getElementById('option-c').value != null) {
last = 'c';
next = 'd';
}
if (document.getElementById('option-d').value != null) {
last = 'd';
next = 'e';
}
if (document.getElementById('option-e').value != null) {
last = '';
next = '';
}
$('#answer_answer'+last).keyup(function() {
console.log('beg');
var elem = document.getElementById('option-'+next);
elem.style.display="block";
console.log('hit this');
})
</script>
This works for the first input. When I type in form input b, form input c appears. However, how do I get this to continually, I suppose, refresh itself, as form input d does not appear when I type in form input c. I thought about putting a while loop around the entire last block/keyup function, but it made the entire app slow and wouldn't load properly.
Thanks for any thoughts! :)
Before we go into solving this problem, let's quickly review some Javascript concepts. When your document first loads, everything inside the <script></script> tags will execute once. This means that the following statements will all be evaluated:
var last = 'b';
var next = 'c';
if (document.getElementById('option-c').value != null) {
last = 'c';
next = 'd';
}
if (document.getElementById('option-d').value != null) {
last = 'd';
next = 'e';
}
if (document.getElementById('option-e').value != null) {
last = '';
next = '';
}
Once they are evaluated, they will never be run again until you refresh the page. Thus, when the page is done loading last = 'b' and next = 'c' and the three if statements all evaluate to false and are not executed (I assume the text fields are empty on initial load). The following code will also be executed once:
$('#answer_answer'+last).keyup(function() {
console.log('beg');
var elem = document.getElementById('option-'+next);
elem.style.display="block";
console.log('hit this');
})
However, this code binds a 'handler' (a future promise) to execute some code given a user action.
The action is a keyup event on the '#answer_answer'+last element.
Because we know that last = 'b' when this promise is made, this
really means '#answer_answerb'
The promise is to execute the following code:
console.log('beg');
var elem = document.getElementById('option-'+next);
elem.style.display="block";
console.log('hit this');
Thus, when you begin typing in #answer_answerb the #answer_answerc field is displayed (remember that next = 'c'). And if you type some more into #answer_answerb the #answer_answerc field remains visible. And now we know everything that your code does.
So, how do we fix it? Can you guess? We can make more promises. The full code:
<script>
$('#answer_answerb).keyup(function() {
var elem = document.getElementById('option-c');
elem.style.display="block";
})
$('#answer_answerc).keyup(function() {
var elem = document.getElementById('option-d');
elem.style.display="block";
})
$('#answer_answerd).keyup(function() {
var elem = document.getElementById('option-e');
elem.style.display="block";
})
</script>
This will have the desired effect, but is hard to maintain. If you decide to add more text fields, you will have to create a promise for each one. You can find a more elegant solution to your problem here http://jsfiddle.net/tppiotrowski/GkT2g/

Categories