I'm trying to have it so when a user enters a string in the txtNmr field, they get an output saying enter a number. Currently, what I have isn't working correctly, and I can't get anything to print out. I know there are other ways in doing, but I want to use a regular expression.
function greetMe() {
$("#errors").css("background-color", "white");
var name = document.getElementById("txtName").value;
var nr = document.getElementById("txtNmr").value;
$("#errors").empty();
$("#greetings").empty();
found_position = txtNmr.search(/\d/);
if (found_position = -1){
$("#errors").append("Enter a number not a string");
$("#errors").css("background-color", "yellow");
}
if (nr > 0 && nr < 21) {
for (var counter = 0; counter < nr; counter = counter + 1) {
$("#greetings").append("Hello, " + name + "<br />");
}
} else {
$("#errors").append("Please Enter A Number Between 1 and 20");
$("#errors").css("background-color", "yellow");
}
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<p>Type in your name</p>
<input type="text" id="txtName">
<p>Enter a number 1-20.</p>
<input type="text" id="txtNmr">
<input type="button" value="Greet Me!" onclick="greetMe()">
<hr>
<div id="greetings">
<!-- Section to output the greeting -->
</div>
<div id="errors">
<!-- Section to output the greeting -->
</div>
txtNmr.match(/\d/)or you can use/\d/.test(txtNmr)(which will return true/false depending on if the string matches regex)