This is my first post and second day with Javascript ;). I try to create a simple form, which:
Allows user put any letter / letters in an input field.
Than I want to send it to my script and:
a) check if anything was given in a form
b) if the user put any sign i want to put it in an array and count up the number of tries
c) if the number of tries reach 10 I want to to stop the script
My script doesn't remeber the number of tries. Moreover, it saves the data in an array but after the script is done it erases everything (I put some console.log() in the script, to see if it does anything). It looks like my variable count doesn't remember the number of tries :(.
How can I fix it ? - but in a simple way of coding :) (I don't want to do a lot of changes in my code)
<script type= "text/javascript">
var given_letters = []; // create an empty array
function givenLetter() {
var count = 0;
var max_count = 10;
var letter = document.getElementById('letter').value;
while (count < max_count) {
if (letter === "") {
alert("No letter given");
return false;
} else {
count++;
given_letters.unshift(letter);
console.log(letter); // returns letter
console.log(given_letters); // returns array with 1 element
console.log(count); // returns "1"
alert("OK");
return true;
}
}
while (count === max_count) {
alert("Sorry. You exceeded the limit of tries.");
return false;
}
}
</script>
// in BODY section
<div>
<form><p>Put your letter here: <input type="text" id="letter" size="5" required><button onclick="givenLetter();">Send</button></p></form>
</div>
You can use given_letters.length instead of count, less code and its the same value, you need to use e.preventDefault(); so the form doesnt submit the form yet, here its a working example, for e.preventDefault(); to work you need to send the event in the button, like this:
<div>
<form>
<p>Put your letter here: <input type="text" id="letter" size="5" required>
<button onclick="givenLetter(event);">Send</button></p>
</form>
</div>
the JS updated:
var given_letters = []; // create an empty array
function givenLetter(e) {
e.preventDefault();
var max_count = 10;
var letter = document.getElementById('letter').value;
while (given_letters.length <= max_count) {
if (letter === "") {
alert("No letter given");
return false;
}
else {
given_letters.unshift(letter);
console.log(letter); // returns letter
console.log(given_letters); // returns array with 1 element
console.log(given_letters.length);//here is your count already
alert("OK");
return true;
}
}
while (given_letters.length === max_count) {
alert("Sorry. You exceeded the limit of tries.");
return false;
}
}
The default behaviour of a button in a form is to submit the form... and reload the page (quite stupid, IMO). This is why your script doesn't seem to remember anything. But there's a way to prevent that.
Also, write var count = 0; outside the function, otherwise it's being set to 0 every time the function is called.
var count = 0;
function givenLetter(event) {
event.preventDefault();
// ....
Try this.
Since the button i within the form tag the default behavior of button is submit. so the form will be submitted and reload the page. So to prevent that behavior we use event.preventDefault(); and make count as a global variable.
var given_letters = []; // create an empty array
var count = 0;
function givenLetter() {
event.preventDefault(); //to prevent reloading the page.
var max_count = 10;
var letter = document.getElementById('letter').value;
while (count < max_count) {
if (letter === "") {
alert("No letter given");
return false;
}
else {
count++;
given_letters.unshift(letter);
console.log(letter); // returns letter
console.log(given_letters); // returns array with 1 element
console.log(count); // returns "1"
alert("OK");
return true;
}
}
while (count === max_count) {
alert("Sorry. You exceeded the limit of tries.");
return false;
}
}
<div>
<form>
<p>Put your letter here: <input type="text" id="letter" size="5" required>
<button onclick="givenLetter();">Send</button></p></form>
</div>
Related
So I am making a game and I need to check if these two HTML <input> fields have some data before I do an alert(); saying that they won. Unfortunately, I don't know how to implement this and I have been stuck at it for hours, please do help, attaching a screenshot for assistance.
In the image, I want to constantly monitor the 2 empty <input> fields and once there is data IN BOTH, then I want to throw up an alert();
Here's what I tried:
var firstLetterField = document.querySelectorAll("input")[0].value.length;
var secondLetterField = document.querySelectorAll("input")[1].value.length;
if (!firstLetterField && !secondLetterField) {
console.log("Please ignore this message: NOT_FILLED...");
} else {
alert("That's right! The word was " + spellingOfWord.join("").toUpperCase() + "! Thanks for playing!");
window.location.href = "/";
}
How about just adding a common class to your user input and use querySelectorAll to perform your check ?
eg
<html>
<body id="game">
<input data-expected="m" class="user-input" />
<input data-expected="a" class="user-input" />
<div id="keyboard">
<button>d</button>
<button>c</button>
<button>b</button>
<button>a</button>
<button>d</button>
<button>m</button>
<button>e</button>
</div>
</body>
<script>
const inputs = document.querySelectorAll(".user-input");
const keyboard = document
.querySelector("#keyboard")
.querySelectorAll("button");
let inputPosition = 0;
function nextInput() {
inputPosition += 1;
if (inputPosition === inputs.length) {
alert("you won");
}
}
function handleClick(event) {
const input = inputs.item(inputPosition);
const submittedValue = event.target.innerHTML;
if (input.dataset.expected === submittedValue) {
input.value = submittedValue;
setTimeout(nextInput);
}
}
keyboard.forEach((button) => button.addEventListener("click", handleClick));
</script>
</html>
You could register an event-listener and check if your condition is met:
var firstLetterField = document.querySelectorAll("input")[0];
var secondLetterField = document.querySelectorAll("input")[1];
// Function to call when both inputs contain values
function bothReady() {
console.log("bothReady", firstLetterField.value, secondLetterField.value);
}
document.addEventListener("keyup", function (e) {
// Wait for both fields to have values
if (firstLetterField.value.length > 0 && secondLetterField.value.length > 0) {
bothReady();
}
});
Your code just works fine. There were just some mistakes that I noticed.
You tried to use the length to detect if it is empty. You could instead compare it with an empty string.
You reversed the boolean value using else. It looks that does the opposite of what you want.
In the code you showed you didn't actually defined spellingOfWord. So I did it for you.
The location "/" is not compatible in every server. So I would recomment replacing it by "index.html".
Here is the code that I just created
function input_inputEvent() {
var firstLetterField = document.querySelectorAll("input")[0].value;
var secondLetterField = document.querySelectorAll("input")[1].value;
var thirdLetterField = document.querySelectorAll("input")[2].value;
if (firstLetterField.length != "" && secondLetterField != "") {
alert(
"That's right! The word was " +
[firstLetterField,secondLetterField,thirdLetterField].join("").toUpperCase() +
"! Thanks for playing!"
);
window.location.href = "index.html";
}
}
Okay, so I have a form. Applied a function to it.
All I want to do is when the form is submitted it launches the function, it checks to see if there is white space and throws out a message. I have the following:
function empty() {
var x;
x = document.getElementById("Username").value;
if (x == "") {
alert("Please ensure you fill in the form correctly.");
};
}
<input type='submit' value='Register' onClick='return empty()' />
<input type='text' id="Username" />
This is fine for if someone pressed the space-bar once and enters one line of whitespace, but how do I edit the function so that no matter how many spaces of whitespace are entered with the space-bar it will always throw back the alert.
Thanks in advance. I am very new to JavaScript. So please be gentle.
Trim the string before testing it.
x = document.getElementById("Username").value.trim();
This will remove any whitespace at the beginning and end of the value.
I have made a function for the same, i added another checks (including a regular expresion to detect multiples empty spaces). So here is the code:
function checkEmpty(field){
if (field == "" ||
field == null ||
field == "undefinied"){
return false;
}
else if(/^\s*$/.test(field)){
return false;
}
else{
return true;
}
}
Here is an example working with jquery: https://jsfiddle.net/p87qeL7f/
Here is the example in pure javascript: https://jsfiddle.net/g7oxmhon/
Note: the function checkEmpty still be the same for both
this work for me
$(document).ready(function() {
$('#Description').bind('input', function() {
var c = this.selectionStart,
r = /[^a-z0-9 .]/gi,
v = $(this).val();
if (r.test(v)) {
$(this).val(v.replace(r, ''));
c--;
}
this.setSelectionRange(c, c);
});
});
function checkEmpty(field) { //1Apr2022 new code
if (field == "" ||
field == null ||
field == "undefinied") {
return false;
} else if (/^\s*$/.test(field)) {
return false;
} else {
return true;
}
}
I have the follow script on a form.
jQuery(document).ready(function($) {
$('#bizloctype').on('change',function() {
$('#packages div').show().not(".package-" + this.value).hide();
});
});
</script>
Basically, depending on the value of the select box #bizloctype (value="1","2","3" or "4") the corresponding div shows and the rest are hidden (div class="package-1","package-2","package-3", or "package-4"). Works perfectly.
BUT, I need to add an additional condition. I need the text box #annualsales to be another condition determining which div shows (if the value is less than 35000 then it should show package-1 only, and no other packages.
I think the below script works fine when independent of the other script but I need to find out how to marry them.
<script>
$("#annualsales").change(function(){
$(".package-1,.package-2,.package-3,.package-4").hide();
var myValue = $(this).val();
if(myValue <= 35000){
$(".package-1").show();
}
else
{
$(".package-2").show();
}
});
</script>
Help please?
I would remove the logic from the anonymous functions and do something like this:
// handle display
function displayPackage( fieldID ) {
var packageType = getPackageType(fieldID);
$('#packages div').show().not(".package-" + packageType).hide();
}
// getting the correct value (1,2,3 or 4)
function getPackageType( fieldID ) {
// default displayed type
var v = 1;
switch(fieldID) {
case 'bizloctype':
// first check it annualsales is 1
v = (getPackageType('annualsales') == 1) ?
1 : $('#' + fieldID).val();
break;
case 'annualsales':
v = (parseInt($('#' + fieldID).val(),10) <= 35000) ? 1 : 2;
break;
}
return v;
}
jQuery(document).ready(function($) {
$('#bizloctype,#annualsales').on('change',function() {
displayPackage($(this).attr('id'));
});
});
If I understand your question properly, try this code out. It first adds an onChange listener to #annualsales which is the code you originally had. Then, for the onChange listener for #bizloctype, it simply checks the value of #annualsales before displaying the other packages.
jQuery(document).ready(function($) {
// Check value of #annualsales on change
$("#annualsales").change(function(){
$(".package-1,.package-2,.package-3,.package-4").hide();
var myValue = $(this).val();
if(myValue <= 35000){
$(".package-1").show();
}
// Only show other packages if value is > 35000
$('#bizloctype').on('change',function() {
$(".package-1,.package-2,.package-3,.package-4").hide();
if ($('#annualsales').val() <= 35000) {
$(".package-1").show();
} else {
$('#packages div').show().not(".package-" + this.value).hide();
}
});
});
Since you already use JQuery you can use the data() function to create a simple but dynamic condition system. For example, you could annotate each element with the required conditions and then attach change listeners to other elements to make the condition active or inactive for the elements.
For example, with this HTML:
<div id="conditions">
Condition 1: <input type="checkbox" id="check1" /> <= check this<br/>
Condition 2: <input type="checkbox" id="check2" /><br/>
Condition 3: <input type="text" id="value1" /> <= introduce 1001 or greater<br/>
Condition 4: <input type="text" id="value2" /><br/>
</div>
<p id="thing" data-show-conditions="check1 value1-gt-1000"
style="display: none;">
The thing to show.
</p>
And this Javascript:
function setShowCondition(el, condition, active) {
var conditions = $(el).data('conditions') || {};
conditions[condition] = active;
$(el).data('conditions', conditions);
var required = ($(el).data('show-conditions') || "").split(" ");
var visible = required.every(function (c) {
return conditions[c];
});
if (visible) {
$(el).show();
} else {
$(el).hide();
}
}
$("#conditions input[type='checkbox'").change(function () {
setShowCondition('#thing',
$(this).attr('id'),
$(this).is(':checked'));
});
$("#value1").change(function () {
var number = parseInt($(this).val());
setShowCondition('#thing', 'value1-gt-1000', number > 1000);
});
You can maintain conditions easily without having to nest and combine several if statements.
I've prepared a sample to show this in https://jsfiddle.net/2L5brd80/.
I have rather large form and along with PHP validation (ofc) I would like to use jQuery. I am a novice with jQuery, but after looking around I have some code working well. It is checking the length of a Text Box and will not allow submission if it is under a certain length. If the entry is lower the colour of the text box changes Red.
The problem I have is as the form is so large it is going to take a long time, and a lot of code to validate each and every box. I therefore wondered is there a way I can loop through all my variables rather than creating a function each time.
Here is what I have:
var form = $("#frmReferral");
var companyname = $("#frm_companyName");
var companynameInfo = $("#companyNameInfo");
var hrmanagername = $("#frm_hrManager");
var hrmanagernameInfo = $("#hrManagerInfo");
form.submit(function(){
if(validateCompanyName() & validateHrmanagerName())
return true
else
return false;
});
Validation Functions
function validateCompanyName(){
// NOT valid
if(companyname.val().length < 4){
companyname.removeClass("complete");
companyname.addClass("error");
companynameInfo.text("Too Short. Please Enter Full Company Name.");
companynameInfo.removeClass("complete");
companynameInfo.addClass("error");
return false;
}
//valid
else{
companyname.removeClass("error");
companyname.addClass("complete");
companynameInfo.text("Valid");
companynameInfo.removeClass("error");
companynameInfo.addClass("complete");
return true;
}
}
function validateHrmanagerName(){
// NOT Valid
if(hrmanagername.val().length < 4){
hrmanagername.removeClass("complete");
hrmanagername.addClass("error");
hrmanagernameInfo.text("Too Short. Please Enter Full Name.");
hrmanagernameInfo.removeClass("complete");
hrmanagernameInfo.addClass("error");
return false;
}
//valid
else{
hrmanagername.removeClass("error");
hrmanagername.addClass("complete");
hrmanagernameInfo.text("Valid");
hrmanagernameInfo.removeClass("error");
hrmanagernameInfo.addClass("complete");
return true;
}
}
As you can see for 50+ input boxes this is going to be getting huge. I thought maybe a loop would work but not sure which way to go about it. Possibly Array containing all the variables? Any help would be great.
This is what I would do and is a simplified version of how jQuery validator plugins work.
Instead of selecting individual inputs via id, you append an attribute data-validation in this case to indicate which fields to validate.
<form id='frmReferral'>
<input type='text' name='company_name' data-validation='required' data-min-length='4'>
<input type='text' name='company_info' data-validation='required' data-min-length='4'>
<input type='text' name='hr_manager' data-validation='required' data-min-length='4'>
<input type='text' name='hr_manager_info' data-validation='required' data-min-length='4'>
<button type='submit'>Submit</button>
</form>
Then you write a little jQuery plugin to catch the submit event of the form, loop through all the elements selected by $form.find('[data-validation]') and execute a generic pass/fail validation function on them. Here's a quick version of what that plugin might look like:
$.fn.validate = function() {
function pass($input) {
$input.removeClass("error");
$input.addClass("complete");
$input.next('.error, .complete').remove();
$input.after($('<p>', {
class: 'complete',
text: 'Valid'
}));
}
function fail($input) {
var formattedFieldName = $input.attr('name').split('_').join(' ');
$input.removeClass("complete");
$input.addClass("error");
$input.next('.error, .complete').remove();
$input.after($('<p>', {
class: 'error',
text: 'Too Short, Please Enter ' + formattedFieldName + '.'
}));
}
function validateRequired($input) {
var minLength = $input.data('min-length') || 1;
return $input.val().length >= minLength;
}
return $(this).each(function(i, form) {
var $form = $(form);
var inputs = $form.find('[data-validation]');
$form.submit(function(e) {
inputs.each(function(i, input) {
var $input = $(input);
var validation = $input.data('validation');
if (validation == 'required') {
if (validateRequired($input)) {
pass($input);
}
else {
fail($input);
e.preventDefault();
}
}
})
});
});
}
Then you call the plugin like:
$(function() {
$('#frmReferral').validate();
});
You could give them all a class for jQuery use through a single selector. Then use your validation function to loop through and handle every case.
$(".validate").each(//do stuff);
form.submit(function(){
if(validateCompanyName() && validateHrmanagerName()) // Its logical AND not bitwise
return true
else
return false;
You can do this.
var x = $("input[name^='test-form']").toArray();
for(var i = 0; i < x.length; i++){
validateCompanyName(x[i]);
validateHrmanagerName(x[i]);
}
I have this function which i am using to compare two input fields. If the user enters the same number in both the text field. On submit there will be an error. Now i would like to know if there is a way to allow same number but not higher than or lower the value of the previous text box by 1. For example if user enters 5 in previous text box, the user can only input either 4, 5 or 6 in the other input field.Please give me some suggestions.
<script type="text/javascript">
function Validate(objForm) {
var arrNames=new Array("text1", "text2");
var arrValues=new Array();
for (var i=0; i<arrNames.length; i++) {
var curValue = objForm.elements[arrNames[i]].value;
if (arrValues[curValue + 2]) {
alert("can't have duplicate!");
return false;
}
arrValues[curValue] = arrNames[i];
}
return true;
}
</script>
<form onsubmit="return Validate(this);">
<input type="text" name="text1" /><input type="text" name="text2" /><button type="submit">Submit</button>
</form>
A tidy way to do it which is easy to read:
var firstInput = document.getElementById("first").value;
var secondInput = document.getElementById("second").value;
if (firstInput === secondInput) {
// do something here if inputs are same
} else if (firstInput > secondInput) {
// do something if the first input is greater than the second
} else {
// do something if the first input is less than the second
}
This allows you to use the values again after comparison as variables (firstInput), (secondInput).
Here's a suggestion/hint
if (Math.abs(v1 - v2) <= 1) {
alert("can't have duplicate!");
return false;
}
And here's the jsfiddle link, if you want to see the answer
Give them both IDs.
Then use the
if(document.getElementById("first").value == document.getElementById("second").value){
//they are the same, do stuff for the same
}else if(document.getElementById("first").value >= document.getElementById("second").value
//first is more than second
}
and so on.