I have been trying to validate my form fields and showing alert if any of this fields are empty. But after that if user enters the value in that field and than when they click submit button again it keeps showing the error alert even if there are no fields empty anymore.
I have tried following code and found that it works perfectly fine for the first time that is - if there are any empty fields, it will show the error alert. But after that if user enters the value in that field and then again click submit, it's not updating the entered value in jquery and keep showing null value and that is why it's keep showing error alert. I am not able to find any error. Any help would be appreciated. I have tried following code:
<form id="desc-form" action="addRecords.php" method="POST" enctype="multipart/form-data">
<div class="question-input">
<textarea required placeholder="Write description here..." name="desc" id="desc" rows="5" cols="50"></textarea>
<script type="text/javascript">
CKEDITOR.replace( 'desc' );
</script>
<select id="select-gender" name="gender">
// have few options
</select>
<input type="radio" name="subscribe" value="1"> Yes
<input type="radio" name="subscribe" value="2"> No
<a id="submit-btn" class="btn btn-submit">Submit</a>
</div>
</form>
<script type="text/javascript>
$(".btn-submit").click(function() {
var desc = CKEDITOR.instances['desc'].getData();
if (desc === "" || $.trim($("#select-gender").val()) === "" || $.trim($('input[name=subscribe]:checked').val()) != 1) {
alert("Please enter all mandatory details!");
} else {
$("#desc-form").submit();
}
});
</script>
So this code is working when there is empty field, but once any value is entered in all the empty field and when the button is clicked again, it still shows the error alert. I know I am missing minor thing, but not getting it. Any help is appreciated. TIA
$(document).on("click",".btn-submit", function() {
var text = $(document).find('#desc');
var radio = $(document).find('input[name="subscribe"]');
var gender = $(document).find('#select-gender option:selected')
if(text.val() == "" || radio.is(':checked') == false || gender.val() == 'Select') {
alert('Please enter all mandatory details!')
}else{
alert('submit data')
}
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<link href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" rel="stylesheet"/>
<form id="desc-form" action="addRecords.php" method="POST" enctype="multipart/form-data">
<div class="question-input">
<textarea required placeholder="Write description here..." name="desc" id="desc" rows="5" cols="50"></textarea>
<select id="select-gender" name="gender">
<option hidden>Select</option>
<option value="1">MALE</option>
<option value="2">FEmale</option>
</select>
<input type="radio" name="subscribe" value="1"> Yes
<input type="radio" name="subscribe" value="2"> No
<a id="submit-btn" class="btn btn-submit">Submit</a>
</div>
</form>
Related
So I have an hidden field, which I want to fill with multiple other input values, when I click on the submit button of an form.
So I use the event.preventDefault(); and then fill the field using JS and afterwards submit the form.
But when I check the returned value in the database I have an empty string instead of the filled values.
What am I doing wrong and how do i have to fix my code?
This is the whole JS file for that functionality:
if (getHiddenLicenseField() != undefined) {
$('.buybox--button').click(function(event){
event.preventDefault();
fillHiddenLicensePlateField();
$(this).closest('form').submit();
});
}
function getHiddenLicenseField() {
return $('.personalizeAttr')[0];
}
function getLicencePlateInputList() {
return $('.custom-input-inner')[0].getElementsByTagName('input');
}
function fillHiddenLicensePlateField() {
let hiddenCustomField = getHiddenLicenseField();
for (let input of getLicencePlateInputList()) {
hiddenCustomField.value += input.value;
}
}
HTML
Field where the user inputs the data:
Hidden Field, where the input of the user gets inserted to:
<input class="personalizeAttr" type="text" name="sAttr1" data-pers-article="2" value="" placeholder="">
Form:
<form name="sAddToBasket" method="post" action="https://www.123autokennzeichen.de/checkout/addArticle" class="buybox--form" data-add-article="true" data-eventname="submit"> <input type="hidden" name="sActionIdentifier" value=""> <input type="hidden" name="sAddAccessories" id="sAddAccessories" value=""> <input type="hidden" name="sAdd" value="123ak10002"> <input style="display:none" class="personalizeBuyAttr personalize_sAttr1" type="text" name="sAttr1" value="" placeholder="sAttr1">
<div class="buybox--button-container block-group">
<div class="buybox--quantity block">
<div class="js--fancy-select select-field quantity--select">
<select id="sQuantity" name="sQuantity" class="quantity--select">
<option value="1" test="">1</option>
...
<option value="100" test="">100</option>
</select>
</div>
</div>
<button class="buybox--button block btn is--primary is--icon-right is--center is--large" name="In den Warenkorb">
<span class="buy-btn--cart-add">In den</span> <span class="buy-btn--cart-text">Warenkorb</span> <i class="icon--arrow-right"></i>
</button>
</div>
<input type="hidden" name="__csrf_token" value="A14oWCR0O16TU8TmYucIFTdnN8Vz3j">
</form>
Page: https://www.123autokennzeichen.de/kfz-kennzeichen/autokennzeichen/euro-kennzeichen-e-kennzeichen-fuer-elektrofahrzeuge-520mm-x-110mm
I want to check if the Value enter in the input is in the datalist.
If not i inform that the value is not in the list, I write something but the submit is done anyway, i miss something ?
Edit: I edit to have a trial form. If i enter productD the submit can't not be done becuase is not in the list defined.
<tbody>
<div class="fichetechniquediv">
<form action="{% url 'createdfichetechnique' %}" method='post' onclick="return myCheckFunction(this)">
<h1>Create the technical Sheet</h1>
<br><br>
<div class="divlot">
<label for="lot">Enter your Lot:</label>
<input type="text" id="lot" name="lot" required minlength="7" oninput="this.value = this.value.toUpperCase()">
</div>
<br><br>
<div class="divproduct">
<label for="productlist">Enter or Select Product:</label>
<input type="text" name="Product" id="productlist" list="productslist" label="'Enter or Select your Product:">
<datalist id="productslist">
<option value="productA">productA</option>
<option value="productB">productB</option>
<option value="productC">productC</option>
</datalist>
</div>
<br><br>
<input class="buttonsave" type="submit" value="Create" name="submit">
</form>
</div>
</tbody>
<script>
function myCheckFunction(form) {
var list = document.getElementsById("productslist");// get the values that are currently under the datalist tag in option tags
var val = document.getElementsByName("Product");// get the user input
if( list.include(val)){ // compare the options with the user input
submit(form)}// if one is equal with the user input submit the form with the method submit();
else{
return false// else don't submit the form, the user will have to change his input
}
}
</script>
Example productD
const list = document.querySelector("#productslist")
const btn = document.querySelector(".buttonsave")
console.log(list.options.length)
if(list.options.length <= 0 ){
btn.disabled = true
}else {
btn.disabled = false
}
Check if is any products. If the script can't see any products disable the button to send. I hope I helped
You cannot use include for DOM elements like you do.
Also you have duplicate IDs
Instead do this:
const list = document.querySelectorAll("productslist option")
document.getElementById("myForm").addEventListener("submit", function(e) {
const val = document.getElementById("productlistInput").value
const found = [...list].find(opt => opt.value===val)
if (!found) {
alert("Please choose an existing value");
e.preventDefault();
}
})
<form id="myForm" action="..." method='post'>
<h1>Create the technical Sheet</h1>
<br><br>
<div class="divlot">
<label for="lot">Enter your Lot:</label>
<input type="text" id="lot" name="lot" required minlength="7" oninput="this.value = this.value.toUpperCase()">
</div>
<br><br>
<div class="divproduct">
<label for="productlist">Enter or Select Product:</label>
<input type="text" name="Product" id="productlistInput" list="productslist" label="'Enter or Select your Product:">
<datalist id="productslist">
<option value="prod1">Product 1</option>
<option value="prod2">Product 2</option>
</datalist>
</div>
<br><br>
<input class="buttonsave" type="submit" value="Create" name="submit">
</form>
There are two things going wrong in this:
document.getElementsById("productslist"); is incorrect. The function is getElementById(...)
document.getElementById("productslist"); will get you an HTML nodes, not the values.
One of the ways to get the values is:
const values = [];
Array
.from(document.getElementById("productslist").options)
.forEach((option) => {
values.push(option.value);
}
Now that you have the values in the values array, you can look it up to check if the value is already present.
I was trying to send form data from one webpage to another using this:
Passing data from one web page to another
I am pasting the javascript code of the function i created:
function store(){
window.localStorage.setItem("name",document.getElementById("name").value);
window.localStorage.setItem("email",document.getElementById("email").value);
window.localStorage.setItem("tele",document.getElementById("tele").value);
window.localStorage.setItem("gender",document.getElementById("gender").value);
window.localStorage.setItem("comment",document.getElementById("comments").value);
window.location.href = "contact.html";
}
But the Problem is that the window.location.href is not working and the webpage is not redirected.
I have seen the console for errors but there aren't any.
Can anyone tell Where is the fault?
EDIT 1:
Validate function:
function validate(){
var comment = document.getElementById("comments").value;
var gender = document.getElementById("gender").value;
var len = comment.length;
if (len > 100)
{
alert("Reduce the length of the comment less than 100 characters");
}
else if (gender == "Select Gender")
{
alert("Please Select a gender");
}
else {
store();
}
}
Form's html:
<form class="form-horizontal" role="form">
Submit Button:
<input type="submit" id="submit" value="Submit" onclick="validate()">
Have a look at this plunker:
https://plnkr.co/edit/P4XqhYciFxZeYlRbWXtd?p=preview
<form class="form-horizontal" role="form">
<textarea rows="4" cols="50" id="comments" placeholder="Enter comments"></textarea>
<br />
<select id="gender">
<option value="Select Gender">Select Gender</option>
<option value="male">male</option>
<option value="female">female</option>
</select>
<br />
<button type="button" id="submit" onclick="validate()">Go</button>
</form>
I have updated the plunker. The page is redirecting and you can see that the values are saved in the local storage. It works fine.
Perhaps you had a problem because of your input submit, I used a button instead.
Please bear with me as I am a beginner when it comes to JavaScript !
I have a dymamic form that pulls information from a database. For each line in the database there is a new row of form fields and the select name incorporates the id from the database - this is all on the same form e.g
<select name="supplier<%=objRst.fields("returnpartid")%>" id="supplier<%=objRst.fields("returnpartid")%>" onchange="validatelink3(<%=objRst.fields("returnpartid")%>)">
<select name="STOCKACTION<%=objRst.fields("returnpartid")%>" id="STOCKACTION<%=objRst.fields("returnpartid")%>" onchange="validatelink3(<%=objRst.fields("returnpartid")%>)">
<select name="stockreason<%=objRst.fields("returnpartid")%>" id="stockreason<%=objRst.fields("returnpartid")%>">
<select name="creditaction<%=objRst.fields("returnpartid")%>" id="creditaction<%=objRst.fields("returnpartid")%>" onchange="validatelink3(<%=objRst.fields("returnpartid")%>)">
<select name="rejectreason<%=objRst.fields("returnpartid")%>" id="rejectreason<%=objRst.fields("returnpartid")%>">
Users are currently missing out data when they are saving the record and I want to prevent this, The save button saves ALL of the records in one go so some lines will be totally blank if they have not yet been processed.
If a user has started to fill in the row but not completed all the information for that record then I need to stop the form submission.
Take a look at Parsley. I use this to validate my login and create user page of my website. Let me know what you think of it!
This is a great javascript tool that utilizes jQuery to validate different forms. Its really nice as you can have it validate several different things such as max and or min text length. It is very easy to implement because all you need to do is add the identifiers to the HTML element.
EDIT:
To avoid a link only answer, here is the code that could be helpful.
<form id="demo-form" data-parsley-validate>
<label for="question">Do you code? *</label>
<p>
<input type="radio" name="question" value="true" required /> Yes
<input type="radio" name="question" value="false" /> No
</p>
<label for="languages">If yes, in which language(s)?</label>
<input type="text" class="form-control" name="languages" data-parsley-conditionalrequired='[" [name=\"question1\"]:checked", "yes"]' data-parsley-validate-if-empty data-parsley-success-class="" data-parsley-conditionalrequired-message="This value is required since you are a programmer!" />
<label for="question">Do you eat dog food? *</label>
<p>
<input type="radio" name="question2" value="yes" required /> Yes
<input type="radio" name="question2" value="no" /> No
</p>
<label for="why">If no, why?</label>
<input type="text" class="form-control" name="why" data-parsley-conditionalrequired='[" [name=\"question2\"]:checked", "no"]' data-parsley-validate-if-empty data-parsley-success-class="" data-parsley-conditionalrequired-message="This value is required since you do not eat dog food!" />
<input type="submit" class="btn btn-default pull-right" />
</form>
<script type="text/javascript">
window.ParsleyConfig = {
validators: {
conditionalrequired: {
fn: function (value, requirements) {
// if requirements[0] value does not meet requirements[1] expectation, field is required
if (requirements[1] == $(requirements[0]).val() && '' == value)
return false;
return true;
},
priority: 32
}
}
};
</script>
<script type="text/javascript" src="../../dist/parsley.js"></script>
EDIT 2:
This is also a simple html file that could do something close to what I think that you want:
<!DOCTYPE html>
<html>
<head>
<style>
.democlass {
color: red;
}
</style>
</head>
<body>
<h1>Hello World</h1>
<input id="test" type="checkbox" id="chk"/>asdfad
<form>
<textarea></textarea>
<button onclick="myFunction()">asd</button>
<form>
<p>If the check box is check the thing is required and if the box is not check then it is not required. So tell your form to only save the rows that have the box checked?</p>
<script>
function myFunction() {
if(document.getElementById("test").checked){
document.getElementsByTagName("textarea")[0].setAttribute("required", "true");
}
else{
document.getElementsByTagName("textarea")[0].removeAttribute("required");
}
}
</script>
</body>
</html>
Hi am new to Javascript and don't know how to validate my check-boxes I have looked up many examples but still don't understand it can someone please tell me how to validate it and also my drop down menu inst validating at all any help in advance will be appreciated.
My Java Script and HTML
function validateForm(){
var fname, lname, sex, address, email, length, songs, a, i, check, error;
a=0;
check=false;
error=false;
fname=document.getElementById("firstname").value;
lname=document.getElementById("lastname").value;
sex=document.getElementsByName("sex");
address=document.getElementById("address").value;
email=document.getElementById("email").value;
length=document.getElementById("len").value;
// songs=document.getElementByName("f_song");
if(fname=="" || fname==null){
alert("please input a first name");
error=true;
return false;
}
if(lname=="" || lname==null){
alert("please input your last name");
error=true;
return false;
}
for(i=0; i<sex.length; i++){
if(sex.item(i).checked==false){
a++;
}
}
if(a==sex.length){
alert("Please select Male or Female");
error=true;
return false;
}
if(address=="" || address==null){
alert("Please input your address thanks");
error=true;
return false;
}
if(email=="" || email==null){
alert("Please enter a email address");
error=true;
return false;
}
if(length=="" || length==null){
alert("Be select how long have you been a fan");
error=true;
return false;
}
alert("Am working ");
}
MY HTML
<head>
<title>] </title>
<link rel="stylesheet" type="Text/css" href="wit_frm.css"/>
<script type="text/javascript" src="java.js">
</script>
</head>
<body>
<div id="container">
<div id="header">
</div>
<div id="topnav">
<div id="link">
Home
Fan Site
Register
</div>
</div>
<div id="contentarea">
<form method="post" action="" onsubmit= "return validateForm();">
<fieldset>
<legend>Personal Information</legend>
First Name:<input type="text" name="fname" id="firstname"/>
<br/>
<br/> Last Name:<input type="text" name="lname" id="lastname"/>
<br/>
<br/> Sex: <input type="radio" name="sex" id="m"/>Male <input type="radio" name="sex" id="f"/>Female
<br/>
<br/>Address: <textarea id="address" name="add" rows="4" cols="30"></textarea>
</fieldset>
<fieldset>
<legend> User Information</legend>
<br/>Email: <input type="text" name="e_address" id="email"/>
<br/>
<br/>No of years listening to her music: <select name="n_years" id="len">
<option value="less than a yr"> less than 1yr</option>
<option value="2-5 years">2-5 years</option>
<option value="5+ years">5+ years</option>
</select>
<br/>
<br/>Favorite Songs:I will always love you<input type="checkbox" name="f_song" value="I will always love you"/> I look to you<input type="checkbox" name="f_song" value="I look to you"/></p>
<br/> I have nothing<input type="checkbox" name="f_song" value="I have nothing"/> One moment in time<input type="checkbox" name="f_song" value="one moment in time"/></p>
<br/> I wanna dance with somebody<input type="checkbox" name="f_song" value="I wanna dance with somebody"/> Greatest Love of All<input type="checkbox" name="f_song" value="Greatest love of all"/></p>
</fieldset>
<br/><input type="submit" name="sub_button" value="SUBMIT"/> <input type="reset" name="res_button" value="CLEAR"/>
</form>
</div>
<div id="footerfix">
</div>
<div id="footer">
<div id="link_1">
Home
Fan Site
About Her
</div>
</div>
</div>
</body>
</html>
I would do it like this:
Bin example
var f_song = document.getElementsByName("f_song");
var oneSongSelected = 0;
//Loop through the checkbox elements, and tally the selected
for(var ss = 0; ss < f_song.length; ss++){
if(f_song[ss].checked){
oneSongSelected++;
}
}
//If none are selected, then alert your error, and return false
if(oneSongSelected === 0){
alert("Please select at least one song");
return false;
}
You could use jquery, but you can do something like this:
In your html code, you can use the first dropdown option "Select" and value "-1":
<select id="dropDown">
<option value="-1">Select</option>
</select>
CheckBox:
<input type="checkbox" name="checkbox" id="checkbox" />
DropDown JavaScript:
var aValue;
aValue = document.getElementById("dropDown").value;
if(aValue == "-1"){
return false;
}
CheckBox JavaScript:
var checkbox = document.getElementById('checkbox');
if(!checkbox.checked){
return false;
}
as you are new in JavaScript, I recommend that you to learn jQuery, it's easier and simpler than JavaScript. If you have checkboxes and you want to validate them, you can try this:
$('#checkbox').click(function(){
if (this.checked) {
}
});
Explanation of Code
$('#checkbox').click(function() => this line says "when the element with id of #checkbox is clicked, do the stuff inside this function." You will need to replace #checkbox with the id of your checkbox (example: #yourCheck) or its class (example: .yourClass).
if (this.checked) => this if statement checks to see if the element is checked or not. You should include your code for when the checkbox is checked inside of the brackets.
EDIT: Here is a JSFiddle example that I made.