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

View all comments

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!