Basic Validate javascript not working correctly - javascript

This is my simple code which I have been working to just show valid or invalid if the wrong text is inserted but the problem I’m having is that when I hit enter the valid and invalid flashes without staying on screen.
Here is my Fiddle
function validate ()
{
var me = document.getElementById("my").value;
if (me == 'my')
{
document.getElementById("Result").innerHTML = "valid";
document.getElementById("Result").style.color = "green";
}
else
{
document.getElementById("Result").innerHTML = "invalid";
document.getElementById("Result").style.color = "red";
}
}
<form>
<button type="button" onclick ="yes" class="fa fa-search"></button>
<input type="text" id="my" onchange="validate()"></input>
<label id="Result"></label>
</form>
What is the mistake i am doing and How can i fix this ?

The problem is that you have your code inside tag. You need to prevent form submission if you want to stay on the page.
I have not included CSS here!!
<div class="container">
<div id="nav">
<div id="search">
<form id="form1">
<button type="button" onclick ="yes" class="fa fa-search"></button>
<input type="text" id="my"></input>
<label id="Result"></label>
</form>
</div>
</div>
</div>
$(document).ready(function(){
$("#form1").submit(function(event){
if ( !validate()) {
alert("Error");
event.preventDefault();
return false;
}
});
});
function validate ()
{
var me = document.getElementById("my").value;
if (me == 'my')
{
document.getElementById("Result").innerHTML = "valid";
document.getElementById("Result").style.color = "green";
return true;
}
else
{
document.getElementById("Result").innerHTML = "invalid";
document.getElementById("Result").style.color = "red";
return false;
}
}
Here is a fiddle. Hope it will help.

Related

Problem with required warning message and submit form

I'm implemented the code taken from here to check if radio button is checked and if not, see a warning message.
My code works, but I have a button for submit with ajax (jQuery(function($)) that go ahead also if radio input is not checked.
Some idea to avoid to run function jQuery if function validateForm() is validated?
Here my code:
document.getElementById("filter").onsubmit = validateForm;
function validateForm() {
var validConsumo = validateConsumo();
//if all fields validate go to next page
return validConsumo;
}
function validateConsumo() {
var select = document.getElementById("filter").select,
errorSpan = document.getElementById("error_select"),
isChecked = false,
i;
errorSpan.innerHTML = "";
for (i = 0; i < select.length; i += 1) {
if (select[i].checked) {
isChecked = true;
break;
}
}
if (!isChecked) {
errorSpan.innerHTML = "* You must pick a value";
return false;
}
return true;
}
jQuery(function($) {
$('#filter').submit(function() {
var filter = $('#filter');
$.ajax({
url: filter.attr('action'),
data: filter.serialize(), // form data
type: filter.attr('method'), // POST
beforeSend: function(xhr) {
filter.find('button').text('Filtering...'); // changing the button label
},
success: function(data) {
filter.find('button').text('Filter'); // changing the button label back
$('#response').html(data); // insert data
}
});
return false;
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<form action="<?php echo site_url() ?>/wp-admin/admin-ajax.php" method="POST" id="filter">
<label class="toggler-wrapper style-19">
<input type="radio" name="select" onchange="changeThis1(this)">
<div class="toggler-slider">
<div class="toggler-knob"></div>
</div>
</label>
<div class="my"><strong>1</strong></div>
<label class="toggler-wrapper style-19">
<input type="radio" name="select" onchange="changeThis2(this)">
<div class="toggler-slider">
<div class="toggler-knob"></div>
</div>
</label>
<div class="my"><strong>2</strong></div>
<br>
<span id="error_select" class="error"></span>
<div class="buttonfiltra" id="buttonfiltra">
<button id="link-ida">Filter</button>
<input type="hidden" value="valuefilter" class="submit" id="link-id" name="action">
</div>
</form>
function validateForm() {
var validConsumo = validateConsumo();
//if all fields validate go to next page
return validConsumo;
}
function validateConsumo() {
var select = document.getElementById("filter").select,
errorSpan = document.getElementById("error_select"),
isChecked = false,
i;
errorSpan.innerHTML = "";
for (i = 0; i < select.length; i += 1) {
if (select[i].checked) {
isChecked = true;
break;
}
}
if (!isChecked) {
errorSpan.innerHTML = "* You must pick a value";
return false;
}
return true;
}
console.log(validateConsumo());
$(document).on("submit", "form#filter", function(e) {
e.preventDefault();
// Check for validations.
if (!validateConsumo()) {
console.log("Failed validation");
return;
}
console.log("Successful validation");
// Rest of the code here.
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<form action="#" method="POST" id="filter">
<label class="toggler-wrapper style-19">
<input type="radio" name="select" />
<div class="toggler-slider">
<div class="toggler-knob"></div>
</div>
</label>
<div class="my"><strong>1</strong></div>
<label class="toggler-wrapper style-19">
<input type="radio" name="select" />
<div class="toggler-slider">
<div class="toggler-knob"></div>
</div>
</label>
<div class="my"><strong>2</strong></div>
<br />
<span id="error_select" class="error"></span>
<div class="buttonfiltra" id="buttonfiltra">
<button type="submit" id="link-ida">Filter</button>
<input type="hidden" value="valuefilter" class="submit" id="link-id" name="action" />
</div>
</form>
Remove document.getElementById("filter").onsubmit = validateForm;
and then update jQuery code like this:
$("#filter").on("submit", function (e) {
e.preventDefault();
// Check for validations.
if (!validateForm()) {
return;
}
// Rest of the code here.
});

How would you make an iframe if the value is true in javascript?

I have a javascript login page (I know it's not secure!) How would I make the website create an iframe if the value is correct?
I have already tried window.location.assign but doesn't work! When you add any code it deletes the values in the inputs and puts the values you inserted in the url?
<div class="box" id="loginbox">
<h2>Login</h2>
<form id="form1" name="form1" action="" onsubmit="return checkDetails();">
<div class="inputBox">
<input type="text" name="txtusername" id="txtusername" class="info" required />
<label>Username</label>
</div>
<div class="inputBox">
<input type="password" name="txtpassword" id="txtpassword" class="info" required/>
<label>Password</label>
</div>
<input type="submit" name="Login" id="Login" value="Login"/>
</form>
</div>
<script>var remainingAttempts = 3;
function checkDetails() {
var name = form1.txtusername.value;
var password = form1.txtpassword.value;
console.log('name', name);
console.log('password', password);
var validUsername = validateUsername(name);
var validPassword = validatePassword(password);
if (validUsername && validPassword) {
alert('Login successful');
document.getElementById("loginbox").remove();
var next = document.createElement("IFRAME");
next.src = 'https://codepen.io';
next.classList.add("codepen");
document.body.appendChild(next);
} else {
form1.txtusername.value = '';
form1.txtpassword.value = '';
remainingAttempts--;
var msg = '';
if (validPassword) {
msg += 'Username incorrect: ';
} else if (validUsername) {
msg += 'Password incorrect: ';
} else {
msg += 'Both username and password are incorrect: ';
}
msg += remainingAttempts + ' attempts left.';
alert(msg);
if (remainingAttempts <= 0) {
alert('Closing window...');
window.close();
}
}
return validUsername && validPassword;
}
function validateUsername(username) {
return username == 'GG';
}
function validatePassword(password) {
return password == '123';
}</script>
I want the page to create the iframe and remove the login box.
The problem is that you are triggering a form submission when your login button is clicked, which triggers a page load.
<input type="submit" name="Login" id="Login" value="Login"/>
The submit input type type triggers this behaviour. To avoid this, bind to the submit event in the javascript rather than the HTML and use preventDefault() to prevent the page from reloading.
var ele = document.getElementById("loginbox");
if(ele.addEventListener){
ele.addEventListener("submit", checkDetails, false); //Modern browsers
} else if(ele.attachEvent){
ele.attachEvent('onsubmit', checkDetails); //Old IE
}
function checkDetails(e) {
e.preventDefault();
// rest of your code
Code taken from this answer, which you should read for more information about form submission events and how to handle them.

How to pass a value to a function and cont execute

I have a form and I'm validating the fields "onblur". what I trying to do is that when the user clicks submit make that any field is empty.
What I was trying to do is to pass the value to a function and run that function when the user click "submit" but I'm having a problem in doing that.
can somebody point me in the right direction on how to fix my problem.
HTML:
<form method="post" name="registerForms" >
<div class="form-group">
<label for="nusernames">Username: <span id="nusernamesErr" class="error">* </span></label>
<input type="text" class="form-control" id="nusernames" name="nusernames" onblur="validateForm('nusernames')">
</div>
<div class="form-group">
<label for="nemail">Email: <span id="nemailErr" class="error">* </span></label>
<input type="email" class="form-control" id="nemail" name="nemail" onblur="validateForm('nemail')">
</div>
<input type="submit" class="btn btn-default" value="Submit" id="registerButton">
</form>
JS:
function validateForm(id)
{
var value = document.getElementById(id).value;
var ok = true;
if(value === "" || value == null)
{
document.getElementById(id+'Err').innerHTML = "* <img src='images/unchecked.gif'> Field is required";
ok = false
yesNo(ok);
}
else
{
document.getElementById(id+'Err').innerHTML = "* ";
}
}
var button = document.getElementById('#registerButton');
button.onclick = function yesNo(ok)
{
alert("There's something wrong with your information!")
if(ok == false)
{
alert("There's something wrong with your information!")
return false;
}
}
If you want to attach the validation on the click event for your submit button I would suggest you to repeat the validation for each input field like you do on blur event.
Moreover, I would suggest you to save the ok value as an attribute of each input field. Set those attributes at dom ready to false and change it to true/false in validateForm function.
When submitting it's a good idea to run your valodator function and test for false fields.
You can use addEventListener in order to register a event handler, querySelectorAll for selecting elements.
The snippet:
function validateForm(id) {
var value = document.getElementById(id).value;
if (value === "" || value == null) {
document.getElementById(id+'Err').innerHTML = "* <img src='images/unchecked.gif'> Field is required";
document.getElementById(id).setAttribute('yesNo', 'false');
} else {
document.getElementById(id+'Err').innerHTML = "* ";
document.getElementById(id).setAttribute('yesNo', 'true');
}
}
document.addEventListener('DOMContentLoaded', function(e) {
document.querySelectorAll('form[name="registerForms"] input:not([type="submit"])').forEach(function(ele, idx) {
ele.setAttribute('yesNo', 'false');
});
document.getElementById('registerButton').addEventListener('click', function(e) {
var ok = true;
document.querySelectorAll('form[name="registerForms"] input:not([type="submit"])').forEach(function(ele, idx) {
validateForm(ele.id);
if (ele.getAttribute('yesNo') == 'false') {
ok = false;
}
});
if (ok == false) {
console.log("There's something wrong with your information!")
e.preventDefault();
}
});
});
<form method="post" name="registerForms" action="http://www.google.com">
<div class="form-group">
<label for="nusernames">Username: <span id="nusernamesErr" class="error">* </span></label>
<input type="text" class="form-control" id="nusernames" name="nusernames" onblur="validateForm('nusernames')">
</div>
<div class="form-group">
<label for="nemail">Email: <span id="nemailErr" class="error">* </span></label>
<input type="email" class="form-control" id="nemail" name="nemail" onblur="validateForm('nemail')">
</div>
<input type="submit" class="btn btn-default" value="Submit" id="registerButton">
</form>
You were trying to define var button with this
var button = document.getElementById('#registerButton');
but it needs to be this with regular javascript
var button = document.getElementById('registerButton');
That seemed to solve the problem

Webpage reloading in every form submit

I have a problem of page reloading.
HTML
<form onsubmit="return commentForm()">
<input type="text" id="text">
<input type="checkbox" id="check" name="check">
<input type="submit" value="Comment" class="txt2">
</form>
<p id="demo"></p>
Javascript
function commentForm() {
var x = document.getElementById('check').checked;
var y = document.getElementById('text').value;
if (y == null || y == "") {
alert('please enter some value');
return false;
}
if (x == false) {
alert('Please check the checkbox')
return false;
}
else {
document.getElementById('demo').innerHTML += document.getELementById('text').value + "<br>";
return true;
}
}
My problem is that when i submit the page it is reloading instead of copying the text.
Please help me with that.
Try this. I changed the button from a submit input to just a button input so that it only runs the script. You don't want the form to submit, that requires a reload of the page to "submit" the form to the sever. Also you need to get the value from the text input:
document.getElementById('demo').innerHTML += document.getElementById('text').value + "<br>
But since you already put that value into var text you can just reuse that variable. Additionally you weren't checking if if the checkbox was checked because it was looking at the variable x for both inputs. Try running this:
function commentForm() {
var checkBox = document.getElementById('check').checked;
var text = document.getElementById('text').value;
if (!text) {
alert('please enter some value');
return false;
}
if (!checkBox) {
alert('Please check the checkbox')
return false;
} else {
document.getElementById('demo').innerHTML += text + "<br>";
return true;
}
}
<form>
<input type="text" id="text">
<input type="checkbox" id="check" name="check">
<input type="button" value="Comment" class="txt2" onclick="return commentForm()">
</form>
<p id="demo"></p>
function commentForm() {
var checkbox = document.getElementById('check').checked;
var text = document.getElementById('text').value;
if (!text) {
alert('please enter some value');
return false;
}
if (!checkbox) {
alert('Please check the checkbox');
return false;
}
else {
document.getElementById('demo').innerHTML += text + "<br>";
return false;
}
}
<form onsubmit="return commentForm()">
<input type="text" id="text">
<input type="checkbox" id="check" name="check">
<input type="submit" value="Comment" class="txt2">
</form>
<p id="demo"></p>
If you want the page not to be redirected you can use the return false in the else statement.

Show div when textbox value is same as another div's content

I am making a quiz in which the answer will be random. I want the "Correct!" div to show when the textbox value is the same as another div.
Here's what I've got so far:
$(document).ready(function(){
$("#buttontest").click(function(){
if ($('#full_day').val() == '#answer') {
$("#correct").show("fast"); //Slide Down Effect
}
else {
$("#correct").hide("fast"); //Slide Up Effect
$("#incorrect").show("500").delay("1000").hide("500");
}
});
});
<p>What is the animal?</p>
<div id="correct">
That's Correct!
</div>
<div id="incorrect">
Sorry, Try again!
</div>
<div id="answer">Monkey</div>
<input type='text' id="full_day"/>
<input type='button' id="buttontest" value="clickme"/>
Use
$('#answer').text()
instead of just
'#answer'
in the if statement.
if ($('#full_day').val() == $('#answer').text())
This is case sensitive. To make it case insensitive:
if ($('#full_day').val().toLowerCase() == $('#answer').text().toLowerCase())
Edit: As requested, here is a solution which allows multiple answers:
$('#check').bind('click', function() {
var possibleAnswers = $('#answers').text().toLowerCase().split(' ');
var givenAnswer = $('#user-answer').val().toLowerCase();
var isAnswerCorrect = false;
for (var indexPossibleAnswers = 0; indexPossibleAnswers < possibleAnswers.length; indexPossibleAnswers++)
{
if (possibleAnswers[indexPossibleAnswers] == givenAnswer)
{
isAnswerCorrect = true
break;
}
}
if (isAnswerCorrect)
{
alert('Correct');
}
else
{
alert('Incorrect, try again.');
}
});
Live demonstration.
$(document).ready(function(){
$("#buttontest").click(function(){
if ($('#full_day').val() == $('#answer').html()) {
$("#correct").show("fast"); //Slide Down Effect
}
else {
$("#correct").hide("fast"); //Slide Up Effect
$("#incorrect").show("500").delay("1000").hide("500");
}
});
});
<p>What is the animal?</p>
<div id="correct" style="display:none;">
That's Correct!
</div>
<div id="incorrect" style="display:none;">
Sorry, Try again!
</div>
<div id="answer" style="display:none;">Monkey</div>
<input type='text' id="full_day"/>
<input type='button' id="buttontest" value="clickme"/>

Categories