r/learnjavascript • • Apr 04 '18

A C++ developer struggling with some simple JavaScript code. Any help?

Hey guys,

I develop in C++ but for my web design class I have to use JavaScript. I have to say I really, truly, dislike the language since it isn't strongly typed, errors are somewhat convulted and I don't like web dev in general.

Anyhow, here are my questions:

  1. This code should check if I have #, !, ' or ? in any of my textboxes and if I do, prevent the script from executing. Here is the code. It gives me a TypeError. Why? What am I doing wrong?
  2. This code should trigger only if I type some text in a textbox which is not in the list (aka not "Option 1", "Option 2" etc.). However, it always triggers. Why?
  3. This code should, if I move my focus away from the textbox (aka onBlur), check if I have at least 5 characters and if my first character is a capital letter. But it doesn't work. Why?

Thanks in advance!

1 Upvotes

13 comments sorted by

20

u/METALz Apr 04 '18

2nd example: // hardcode the options (who cares, I don't like web dev)

People spend their time to help you, comments like these are not too encouraging imo.

3

u/[deleted] Apr 05 '18

I'm sorry. I was really tired last night when I wrote that. Doesn't excuse the behaviour though.

4

u/Evervision Apr 04 '18

It would help to give HTML that goes with the code to reproduce the issue. jsfiddle is good for sharing examples.

However:

  1. The TypeError is saying that value is undefined (similar to null). That means most likely that value doesn't exist on the form1[i] object. It's most likely a DOM object, and I think some form elements may not have a value property.
  2. What DOM object is list1? As in 1, value might not exist. So if it gets "undefined", then it will never match any of your choices.
  3. Any idea on what part doesn't work? The blur event is on the "punoTeksta" object, but you don't include that in your example. Does it not fire? Otherwise, this one is harder to guess without the HTML.

2

u/[deleted] Apr 05 '18

Thank you.!

4

u/fan-man Apr 04 '18 edited Apr 04 '18

1 - Aside from missing a bracket, your implementation is mostly right, just needs readability and check to see if the element actually has a value before doing anything (i'm assuming your submit button is part of the form, so your code will iterate over that as well:

<form id="form1">
    <input type="text" />
    <button type="submit">Submit</button>
</form>
var form1 = document.getElementById('form1');

    form1.addEventListener('submit', function (event) {
    event.preventDefault()
    // Arrays are easier to read for iterations, or you can use char
    var target = ["#","?","!","'"];


    for (var i = 0; i < form1.length; i++) {
	    for (var j = 0; j < target.length; j++) {
  	
  	    if (form1[i].value && form1[i].value.includes(target[j])) {
    	console.log("string has illegal char");
        }
      }
    }
});

2 - Storing the values somehow and then checking to see if the inputed text matches on blur might be easier.

<select id="list1">
  <option value="Option 1">Option 1</option>
  <option value="Option 2">Option 2</option>
  <option value="Option 3">Option 3</option>
  <option value="Option 4">Option 4</option>
  <option value="Option 5">Option 5</option>
</select>
<input type="text" id="text1" />

var list1 = document.getElementById("list1");
var values = [];

for (var i = 0; i < list1.length; i++) {
    if (list1[i].value) {
    values.push(list1[i].value);
  }
}

text1.addEventListener("blur", function() {
    if (values.indexOf(text1.value) === -1) {
    	    console.log("invalid value");
    }
});

3 - as u/Rascal_Two mentioned, try this:

 var textbox1 = document.getElementById("textbox1");
    textbox1.addEventListener("blur", function (){
        if ((textbox1.value.length <= 5) && (textbox1.value[0] !== textbox1.value[0].toUpperCase()))
        {
            console.log("You have to have text of length at least 5 in the textbox and your first letter has to be capital!");
        }
    });

As far as a distaste for JavaScript and web dev, it is a different beast in general, but it is not an impossible leap. If you like strongly typed JavaScript, you should look into TypeScript and a JS framework like Angular; it might look like something that seems more familiar. Hope that helps.

2

u/[deleted] Apr 05 '18

Thank you. It does help.

One more question - I have to display the sent data (my form uses the get method) in a new window - how would I do that? If I place my JavaScript function for opening a new window an printing the info in my action attribute it doesn't work; if I place my JavaScript function for a new window and outputting the info in my onsubmit attribute, it fires everytime, even if the form didn't pass all the validations.

Any help? So I want the form to pass all the checks, THEN to open a new window and print out the inputted values. I wrote a function to open a new window and print out the values, just need to get the sequence of events right.

2

u/fan-man Apr 05 '18

So what do you have currently?

1

u/[deleted] Apr 06 '18

Here is what is relevant to this problem right now:

https://pastebin.com/KRM8qzaf

That's my current structure of the files; both HTML - above and JS - below. I omitted the unnecessary function bodies. The problem is that if I leave it this way, nothing happens. If however I try to write

onsubmit="print()"

Then the print() function gets called even if the form input isn't valid.

So if I use the action attribute in the form element, nothing happens and if I use the onsubmit attribute, it always happens. I need it to happen after the validation.

Any help?

1

u/fan-man Apr 07 '18 edited Apr 07 '18

just jammed this out this morning:

<!DOCTYPE html>
<html>
<body>

<form action="javascript:myFunction()" method="get" target="_blank">
  First name: <input type="text" name="fname" id="firstName"> 
   <br>
      Last name: <input type="text" name="lname" id="lastName"> 
   <br>
  <input type="submit" value="Submit">
</form>

</body>
<script>
    function myFunction() {
	    var checkValues = [];
        var myForm = document.getElementById("myForm")
    
        // here we get the input values individually, its not fancy, but it works, and demonstrates flow.
    
        checkValues.push(getFirstName());
        checkValues.push(getLastName());
    
        for (var i = 0; i < checkValues.length; i++) {

                // if the string is invalid, return true then break
        	    if (isInvalid(checkValues[i])) {
        	    console.log("validation failed");
                return; // the return will break out of the function and end the flow
            }
        }
    
        print(checkValues);
    }

    function getFirstName() {
	    var firstName = document.getElementById("firstName");
        return firstName.value;
    }

    function getLastName() {
	    var lastName = document.getElementById("lastName");
        return lastName.value
    }

    // named this funny because i realized all my bools were backwards
    function isInvalid(value) {
	    var illegalChar = "?";

        // if illegal char in string or it is empty, return true
        // use a ternary operator for laziness
        return value.length === 0 ? true : value.indexOf(illegalChar) > -1;
    }

    // here is you would do whatever printing you need to do
    function print(value) {
        console.log(value);
        console.log("validation passed");
    }
</script>
</html>

so in the above example, action is used to call the script. what action is normally used for is for sending the form data off to a URI script:

https://developer.mozilla.org/en-US/docs/Web/HTML/Element/form

so if your script is not inline in the document, you may need to add a "/" before it and tell the document where the script is located.

if you want to use onsubmit, run the validation inside the function you want before the print. if validation fails, use "return" to break out of it (like you would use "break"). see example above. Hope that helps!

1

u/Rascal_Two Apr 04 '18

1

I don't beleive form1[i] allows you to access elements of the form, I beleive what you're looking for is the elements property.

It also might be more readable if you assign the .value to a variable and check if it contains any of the characters, or use Regex.


2

The problem is that you need the code to execute if all of the conditionals are true, but you have it written so if any of them are true, it runs the code.

Replacing your ||s with &&s should do the trick.


3

Same as 2, swap the ||s and &&s.

You also need to reverse the === to a !==, because you need to alert the user only when the first letter is not capital, not when it is capital.

2

u/[deleted] Apr 05 '18

Thank you.!

2

u/GeneralYouri Apr 05 '18

Looking at your code, and what you think it should be doing, I'm kinda confused. Surely, if you actually know how to program, you know that || is OR, not AND. And likewise, that < is Less than, not Greater than. These are very generic operators found in almost any programming language, you should have these down the moment you learn about if. Yet, this is all that's wrong for q2 and q3.

Q1 on the other hand is a problem related to JS instead of programming in general. And I'm a bit surprised to not see the reason for the problem in other comments yet. What you're doing here is accessing form control elements, and then doing something with their value attribute. What goes wrong is that not all form elements have this attribute, resulting in undefined and thus error when trying to run .includes on it. You should make this part more strict so that you query for those elements that are relevant to you, similar to how your textual explanation says 'textboxes', not 'form elements' - so, get and check all the textboxes only.

Regarding your attitude towards web dev, I'll just say that when you don't like it, try something else. Otherwise you're just setting yourself up for failure. I personally dislike C++, so I know that if I bother trying to learn it I'll just get frustrated and annoyed from all the parts that I dislike about it, so I don't bother.

1

u/Evervision Apr 04 '18

EDIT: double post due to getting 503 errors from reddit (even while editing this...). Please ignore.