I have 2 modal and I check validation of form of first modal and if entries of textboxes were empty .second modal should not be shown.I cannot do this. user is id of my first modal and permission is id of my second modal.
java script code:
function valid() {
var bool = true;
var pt = /^[\w.]+#[a-z0-9-]+\.[a-z]{2,6}/i;
var email = document.getElementById('email').value;
if (!pt.test(email)) {
bool = false;
}
var name = document.getElementById('name').value;
if (name.length < 1) {
bool = false;
}
return bool;
}
$("#btn1").click(function() {
var bool = valid();
if (bool == false) {
$('#permission').modal('hide');
} else {
$('#user').modal('hide');
$('#permission').modal('show');
}
});
my html code:
<form onsubmit="return valid()">
<button role="button" class="btn btn-default" data-toggle="modal" data-target="#permission" id="btn1">set permission</button>
What about trying this in the valid() function?
function valid() {
var pt = /^[\w.]+#[a-z0-9-]+\.[a-z]{2,6}/i;
var email = document.getElementById('email').value;
var name = document.getElementById('name').value;
return pt.test(email) && name.length>1;
}
Related
So i have following objectives from the checkbox click event
1] Create A Button having id = 'id-of-checkbox'+'some-character-here' in specified div
2] Clicking On That Particular Button Will Remove The Button As Well As Checkbox tick related to it
3] If User wants to remove button in specified div through unchecking the checkbox it should be done
4] And If User again checks the checkbox button should be created in specified div
Now i have achieved first 3 objectives and im having issue with 4th one , i.e
if i click on checkbox again after unticking it button is not getting created and console doesnt return any error associated with it.. please help
Here Is My HTML Code
<div id="filterDropArea container">
<input type="checkbox" name="priceFilter" id="priceFilter" class="btn" onclick="updateValue(this.id,this.name)">
Price Filter
</div>
<div id="DropArea">
</div>
Here is My Javascript Code
var objTo = document.getElementById('DropArea');
var checked = ""
function updateValue(id,name)
{
if(document.getElementById(id).checked)
{
checked='yes'
}
else if(!document.getElementById(id).checked)
{
checked='no'
}
if(checked=='yes')
{
addButton(id,name);
}
else if(checked=='no')
{
removeButton(id,name);
}
}
function addButton(id,name)
{
var nameOfButton = name+'X';
var idofButton = id+'11';
var btn = document.createElement("BUTTON");
btn.innerHTML=nameOfButton;
btn.setAttribute("class","btnCancel");
btn.setAttribute("id",idofButton);
btn.setAttribute("onclick","someMsg(this.id)")
objTo.appendChild(btn);
}
function removeButton(id,name)
{
var idofButton = id+'11'
if(document.getElementById('DropArea').contains(document.getElementById(idofButton)))
{
document.getElementById('DropArea').remove(document.getElementById(idofButton));
console.log('Button Removed');
}
}
function someMsg(id)
{
var name = id.substring(0,id.length-2);
document.getElementById(id).remove();
document.getElementById(name).checked=false;
console.log('Deleted');
}
Another approach to achieving the same result:
const dropArea = document.querySelector("#dropArea");
const checkbox = document.querySelector("#priceFilter");
checkbox.addEventListener("change", function(e) {
if (this.checked) {
const btn = createSpecificButton();
dropArea.appendChild(btn);
} else {
const btn = dropArea.querySelector("button");
dropArea.removeChild(btn);
}
});
const createSpecificButton = () => {
const btn = document.createElement("button");
btn.innerText = "Click Here";
btn.addEventListener("click", function(e) {
checkbox.checked = false;
this.remove();
});
return btn;
};
<div id="filterDropArea container">
<input type="checkbox" name="priceFilter" id="priceFilter" /> Price Filter
</div>
<div id="dropArea"></div>
Element.remove() don't have any parameters, so when you call by your way, it will remove DropArea element (includes children, like idofButton).
Solution: Change the below line
document.getElementById('DropArea').remove(document.getElementById(idofButton));
To
document.getElementById(idofButton).remove();
var objTo = document.getElementById('DropArea');
var checked = ""
function updateValue(id, name) {
if (document.getElementById(id).checked) {
checked = 'yes'
} else if (!document.getElementById(id).checked) {
checked = 'no'
}
if (checked == 'yes') {
addButton(id, name);
} else if (checked == 'no') {
removeButton(id, name);
}
}
function addButton(id, name) {
var nameOfButton = name + 'X';
var idofButton = id + '11';
var btn = document.createElement("BUTTON");
btn.innerHTML = nameOfButton;
btn.setAttribute("class", "btnCancel");
btn.setAttribute("id", idofButton);
btn.setAttribute("onclick", "someMsg(this.id)")
objTo.appendChild(btn);
}
function removeButton(id, name) {
var idofButton = id + '11'
if (document.getElementById('DropArea').contains(document.getElementById(idofButton))) {
document.getElementById(idofButton).remove();
console.log('Button Removed');
}
}
function someMsg(id) {
var name = id.substring(0, id.length - 2);
document.getElementById(id).remove();
document.getElementById(name).checked = false;
console.log('Deleted');
}
<div id="filterDropArea container">
<input type="checkbox" name="priceFilter" id="priceFilter" class="btn" onclick="updateValue(this.id,this.name)"> Price Filter
</div>
<div id="DropArea">
</div>
I'm trying to create a login page. I need to validate username and password but my js does not seem to work. I made it simpler now just for the sake to make it work. This is my html:
<script type="text/javascript" src = "js/checklogin.js"></script>
<h3>Already have an account?</h3>
<span id = "feedback"></span>
<form id = "login" action = "login.html" method = "post">
<label for = "name">User name:</label><br>
<input type = "text" name = "username " id = "username"><br>
<label for = "password">Password:</label><br>
<input type = "password" name = "password" id = "password"><br>
<input type="submit" value="Login">
</form>
And this is my js:
var elUsername = document.getElementById('username');
var elPassword = document.getElementById('password')
var elMsg = document.getElementById('feedback');
function checkFilled(length) {
if (length == "") {
elMsg.innerHTML = 'Please fill out this field';
} else {
document.getElementById("login").submit();
}
}
elUsername.addEventListener('blur', checkFilled(elUsername.value),false);
elPassword.addEventListener('blur', checkFilled(elPassword.value),false);
I still cannot make it to work. Also, how can i make it to appear as a pop up right on the textbox? Something that looks like this:
Error image
There's several issues with the code you had, so here's a complete example of the way I would do it (use the same HTML you already have). This works for me as tested in JSFiddle and below in the snippet.
var elUsername = document.getElementById('username');
var elPassword = document.getElementById('password')
var elMsg = document.getElementById('feedback');
var elForm = document.getElementById('login');
function checkFilled() {
if (elUsername.value == "" || elPassword.value == "") {
elMsg.innerHTML = 'Please fill out this field';
event.preventDefault();
} else {
elMsg.innerHTML = '';
}
}
if (elForm.addEventListener) {
elForm.addEventListener('submit', function() {
checkFilled();
}, false);
} else {
elForm.attachEvent('onsubmit', function() {
checkFilled();
});
}
if (elUsername.addEventListener) {
elUsername.addEventListener('blur', function() {
checkFilled();
}, false);
} else {
elUsername.attachEvent('onblur', function() {
checkFilled();
});
}
if (elPassword.addEventListener) {
elPassword.addEventListener('blur', function() {
checkFilled();
}, false);
} else {
elPassword.attachEvent('onblur', function() {
checkFilled();
});
}
<!--<script type="text/javascript" src = "js/checklogin.js"></script>-->
<h3>Already have an account?</h3>
<span id = "feedback"></span>
<form id = "login" action = "login.html" method = "post">
<label for = "name">User name:</label><br>
<input type = "text" name = "username " id = "username"><br>
<label for = "password">Password:</label><br>
<input type = "password" name = "password" id = "password"><br>
<input type="submit" value="Login">
</form>
I have this email validation function in plain JavaScript:
function isEmail() {
var slides = document.getElementsByClassName("email");
for (var i = 0; i < slides.length; i++) {
emailValue = slides.item(i).value;
var regex = /^[a-zA-Z0-9._-]+#[a-zA-Z0-9.-]+\.[a-zA-Z]{2,4}$/i;
var res = regex.test(emailValue);
if (res == false) {
alert("Enter valid email");
return false;
} else {
return true;
}
}
}
I want to convert this in to jQuery in this format:
$(document).ready(function() {
$("#form").submit(function() {
$(".email").each(function() {
});
});
});
Is that what you need??
$(document).ready(function() {
$(".button").click(function() {
$("li.email").each(function() {
emailValue = $(this).text();
console.log(emailValue);
var regex = /^[a-zA-Z0-9._-]+#[a-zA-Z0-9.-]+\.[a-zA-Z]{2,4}$/i;
var res = regex.test(emailValue);
if (res == false) {
alert(emailValue+" email invalid");
} else {
alert(emailValue+" email valid");
}
});
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<ul>
<li class="email">email_valid#gmail.com</li>
<li class="email">email_valid2#gmail.com</li>
<li class="email">email_invalid#gmailcom</li>
<li class="email">email_valid3#gmail.com</li>
<li class="">not email</li>
</ul>
<input type="button" class="button" value="validate emails"/>
It seams like the code above it trying to validate multiple emails fields on the page. So I'm going to make some dummy data on my js fiddle for you. I also optimized your code so that the variables are cached outside of the loop. If they were cached inside of the $.each loop, then it would create a new variable each time.
function isEmail() {
var slides = $('.email');
var emailValue = null;
var regex = /^[a-zA-Z0-9._-]+#[a-zA-Z0-9.-]+\.[a-zA-Z]{2,4}$/i
var res = null;
console.log(slides);
$(slides).each(function(){
emailValue = $(this).val();
res = regex.test(emailValue);
if (res==false){
alert("Enter valid email");
return false;
}
alert("Success!")
return true;
})
}
Here is the JSFiddle
the correct or wrong answer outputs and quickly disappears. How do I get the answer to remain on the screen. I want to keep the html and js files separate. What I want to do later is add other phrases to the program.
INDEX.HTML
<head> </head>
<body>
<form name="myForm">
<div id ="phrase"></div>
<input type = "text" id = "textinput">
<button id="myBtn">Click here</button>
<div id ="feedback"></div>
</form>
<script src = "phraseScrambler.js"></script>
</body>
</html>
PHRASESCRAMBLER.JS
var words = ['how', 'are', 'you', 'today?'];
var correctInput = "how are you today";
var userInput = 'how are you today?';
var newWords = words.slice(0);
shuffle(newWords);
question();
function question() {
var el = document.getElementById('phrase');
el.textContent = newWords.join(' ');
document.getElementById("myBtn").onclick = checkAnswer;}
function checkAnswer() {
var elMsg = document.getElementById('feedback');
if (document.myForm.textinput.value == correctInput) {
elMsg.textContent= "correct";}
else {
elMsg.textContent= "wrong answer";}}
function shuffle(newWords) {
var counter = newWords.length, temp, index;
while (counter > 0) {
index = Math.floor(Math.random() * counter);
counter--;
temp = newWords[counter];
newWords[counter] = newWords[index];
newWords[index] = temp;}
return newWords;}
First of all don't bind click event if you want to handle form submission, forms have dedicated event called onsubmit. When form is submitted default browser behavior is to navigate to form action (in your case reload the page). You need to prevent this by returning false from the onsubmit handler.
Corrected HTML will be (I gave an id to the form):
<form name="myForm" id="myForm"> ... </form>
And then event handling will look like (note return false; in checkAnswer function):
var words = ['how', 'are', 'you', 'today?'];
var correctInput = "how are you today";
var userInput = 'how are you today?';
var newWords = words.slice(0);
shuffle(newWords);
question();
function question() {
var el = document.getElementById('phrase');
el.textContent = newWords.join(' ');
document.getElementById("myForm").onsubmit = checkAnswer;
}
function checkAnswer() {
var elMsg = document.getElementById('feedback');
if (document.myForm.textinput.value == correctInput) {
elMsg.textContent = "correct";
} else {
elMsg.textContent = "wrong answer";
}
return false;
}
function shuffle(newWords) {
var counter = newWords.length,
temp, index;
while (counter > 0) {
index = Math.floor(Math.random() * counter);
counter--;
temp = newWords[counter];
newWords[counter] = newWords[index];
newWords[index] = temp;
}
return newWords;
}
<form name="myForm" id="myForm">
<div id ="phrase"></div>
<input type = "text" id = "textinput" />
<button>Click here</button>
<div id ="feedback"></div>
</form>
I want my form submit button to be disabled/enabled depending on if the form is completely filled.
When the inputs are filled, the disabled button changes to enabled. That works great.
But I would like it to disable the button when an input gets emtied.
This is my script:
<script type="text/javascript" language="javascript">
function checkform()
{
var f = document.forms["theform"].elements;
var cansubmit = true;
for (var i = 0; i < f.length; i++) {
if (f[i].value.length == 0) cansubmit = false;
}
if (cansubmit) {
document.getElementById('submitbutton').disabled = false;
}
}
</script>
<form name="theform">
<input type="text" onKeyup="checkform()" />
<input type="text" onKeyup="checkform()" />
<input id="submitbutton" type="submit" disabled="disabled" value="Submit" />
</form>
Just use
document.getElementById('submitbutton').disabled = !cansubmit;
instead of the the if-clause that works only one-way.
Also, for the users who have JS disabled, I'd suggest to set the initial disabled by JS only. To do so, just move the script behind the <form> and call checkform(); once.
Just add an else then:
function checkform()
{
var f = document.forms["theform"].elements;
var cansubmit = true;
for (var i = 0; i < f.length; i++) {
if (f[i].value.length == 0) cansubmit = false;
}
if (cansubmit) {
document.getElementById('submitbutton').disabled = false;
}
else {
document.getElementById('submitbutton').disabled = 'disabled';
}
}
Put it inside a table and then do on her:
var tabPom = document.getElementById("tabPomId");
$(tabPom ).prop('disabled', true/false);
I just posted this on Disable Submit button until Input fields filled in. Works for me.
Use the form onsubmit. Nice and clean. You don't have to worry about the change and keypress events firing. Don't have to worry about keyup and focus issues.
http://www.w3schools.com/jsref/event_form_onsubmit.asp
<form action="formpost.php" method="POST" onsubmit="return validateCreditCardForm()">
...
</form>
function validateCreditCardForm(){
var result = false;
if (($('#billing-cc-exp').val().length > 0) &&
($('#billing-cvv').val().length > 0) &&
($('#billing-cc-number').val().length > 0)) {
result = true;
}
return result;
}
Here is the code
<html>
<body>
<input type="text" name="name" id="name" required="required" aria-required="true" pattern="[a-z]{1,5}" onchange="func()">
<script>
function func()
{
var namdata=document.form1.name.value;
if(namdata.match("[a-z]{1,5}"))
{
document.getElementById("but1").disabled=false;
}
}
</script>
</body>
</html>
Using Javascript
I think this will be much simpler for beginners in JavaScript
//The function checks if the password and confirm password match
// Then disables the submit button for mismatch but enables if they match
function checkPass()
{
//Store the password field objects into variables ...
var pass1 = document.getElementById("register-password");
var pass2 = document.getElementById("confirm-password");
//Store the Confimation Message Object ...
var message = document.getElementById('confirmMessage');
//Set the colors we will be using ...
var goodColor = "#66cc66";
var badColor = "#ff6666";
//Compare the values in the password field
//and the confirmation field
if(pass1.value == pass2.value){
//The passwords match.
//Set the color to the good color and inform
//the user that they have entered the correct password
pass2.style.backgroundColor = goodColor;
message.style.color = goodColor;
message.innerHTML = "Passwords Match!"
//Enables the submit button when there's no mismatch
var tabPom = document.getElementById("btnSignUp");
$(tabPom ).prop('disabled', false);
}else{
//The passwords do not match.
//Set the color to the bad color and
//notify the user.
pass2.style.backgroundColor = badColor;
message.style.color = badColor;
message.innerHTML = "Passwords Do Not Match!"
//Disables the submit button when there's mismatch
var tabPom = document.getElementById("btnSignUp");
$(tabPom ).prop('disabled', true);
}
}
<form name="theform">
<input type="text" />
<input type="text" />`enter code here`
<input id="submitbutton" type="submit"disabled="disabled" value="Submit"/>
</form>
<script type="text/javascript" language="javascript">
let txt = document.querySelectorAll('[type="text"]');
for (let i = 0; i < txt.length; i++) {
txt[i].oninput = () => {
if (!(txt[0].value == '') && !(txt[1].value == '')) {
submitbutton.removeAttribute('disabled')
}
}
}
</script>
Here is my way of validating a form with a disabled button. Check out the snippet below:
var inp = document.getElementsByTagName("input");
var btn = document.getElementById("btn");
// Disable the button dynamically using javascript
btn.disabled = "disabled";
function checkForm() {
for (var i = 0; i < inp.length; i++) {
if (inp[i].checkValidity() == false) {
btn.disabled = "disabled";
} else {
btn.disabled = false;
}
}
}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8"/>
<meta name="viewport" content="width=device-width, initial-scale=1.0"/>
<title>JavaScript</title>
</head>
<body>
<h1>Javascript form validation</h1>
<p>Javascript constraint form validation example:</p>
<form onkeyup="checkForm()" autocomplete="off" novalidate>
<input type="text" name="fname" placeholder="First Name" required><br><br>
<input type="text" name="lname" placeholder="Last Name" required><br><br>
<button type="submit" id="btn">Submit</button>
</form>
</body>
</html>
Example explained:
We create a variable to store all the input elements.
var inp = document.getElementsByTagName("input");
We create another variable to store the button element
var btn = document.getElementById("btn");
We loop over the collection of input elements
for (var i = 0; i < inp.length; i++) {
// Code
}
Finally, We use the checkValidity() method to check if the input elements
(with a required attribute) are valid or not (Code is inserted inside the
for loop). If it is invalid, then the button will remain disabled, else the
attribute is removed.
for (var i = 0; i < inp.length; i++) {
if (inp[i].checkValidity() == false) {
btn.disabled = "disabled";
} else {
btn.disabled = false;
}
}
You can enable and disable the submit button based on the javascript validation below is the validation code.
<script>
function validate() {
var valid = true;
valid = checkEmpty($("#name"));
valid = valid && checkEmail($("#email"));
$("#san-button").attr("disabled",true);
if(valid) {
$("#san-button").attr("disabled",false);
}
}
function checkEmpty(obj) {
var name = $(obj).attr("name");
$("."+name+"-validation").html("");
$(obj).css("border","");
if($(obj).val() == "") {
$(obj).css("border","#FF0000 1px solid");
$("."+name+"-validation").html("Required");
return false;
}
return true;
}
function checkEmail(obj) {
var result = true;
var name = $(obj).attr("name");
$("."+name+"-validation").html("");
$(obj).css("border","");
result = checkEmpty(obj);
if(!result) {
$(obj).css("border","#FF0000 1px solid");
$("."+name+"-validation").html("Required");
return false;
}
var email_regex = /^([a-zA-Z0-9_.+-])+\#(([a-zA-Z0-9-])+\.)+([a-zA-Z0-9]{2,3})+$/;
result = email_regex.test($(obj).val());
if(!result) {
$(obj).css("border","#FF0000 1px solid");
$("."+name+"-validation").html("Invalid");
return false;
}
return result;
}
</script>