Java Script Drop Down Menu Validation - javascript

Ok I have a drop down menu that is dynamically generated by PHP and populated with data fetched from database. Frontally this works vert well, The problem that I am having is with a JS validation, am not so good with JavaScript ('Dislike it'), but for the purposes of my mini project I have to work with it anyway....
The problem is that with JS I am checking if a user has selected one of the options available in drop down menu is so the form can be submitted else display a warning.
So what I am trying to do is this.....Give a value="f" to the first option which displays "PLEASE SELECT workshop" so if at the submission of the form the value of this drop down menu == f return false else submit the form.
now if at the submission the value ==f the error is displayed but if the value is not == f and i select one of the values from drop down menu i cannot proceed with the submission its does not allow me
PHP code:
function getForex($link){
$timestamp = date("Y-m-d");
$sql = "SELECT id, course, status, endingDate, schedule FROM courses WHERE course LIKE '%Forex%' OR course LIKE '%forex%' AND status=5";
$query = mysqli_query($link, $sql);
$option='<select id="Forex" name="workshop">';
$option.='<option id="fx" value="Forex">Select Forex Workshop</option>';
$option.='';
while($result = mysqli_fetch_assoc($query))
{
if($timestamp < $result['endingDate'])
{
$option.='<option id="'.$result['id'].'" value='.$result['endingDate'].'>'.$result['course']." ".$result['schedule'].'</option>';
}
}
$option.='</select>';
return $option;
}
JS CODE:
var sel=document.getElementById('fx').value="Forex";
if(sel.match("Forex")){
document.getElementById('error').innerHTML = "Choose Forex Workshop Date";
document.getElementById('fx').style.borderColor = "red";
return false;
}else{
document.getElementById('fx').style.borderColor = "green";
}
OK guys combination of many very helpful answers have helped but when I add another drop down menu like
PHP code:
function getBinary($link){
$timestamp = date("Y-m-d");
$sql2 = "SELECT id, course, status, endingDate, schedule FROM courses WHERE course LIKE '%Binary%' OR course LIKE '%binary%' AND status=5";
$query2 = mysqli_query($link, $sql2);
$option2='<select id="Binary" name="workshop">';
$option2.='<option id="bi" value="Binary">Select Binary Workshop</option>';
$option2.='';
while($result2 = mysqli_fetch_assoc($query2))
{
if($timestamp < $result2['endingDate'])
{
$option2.='<option id="'.$result2['id'].'" value="'.$result2['endingDate'].'">'.$result2['course']." ".$result2['schedule'].'</option>';
}
}
$option2.='</select>';
return $option2;
}
JS Code:
var selbi=document.getElementById('Binary').value;
if(selbi.match("Binary")){
document.getElementById('error').innerHTML = "Choose Binary Workshop Date";
return false;
}
The problem becomes that The Inner HTML message displays only for forex and get twisted around i.e. if forex is not selected it shows the message choose forex workshop if i choose the forex workshop it then shows choose binary workshop :D

You are not using select id use select id
var sel=document.getElementById('Forex').value;
if(sel.match("Forex")){
document.getElementById('error').innerHTML = "Choose Forex Workshop Date";
document.getElementById('fx').style.borderColor = "red";
return false;
}else{
document.getElementById('fx').style.borderColor = "green";
}

i have done javaScript drop-down validation .when in drop down value is "select one" in that time give you messages "please select your value ".My hole project in github .Project link
is Javascript drop-down value validation

you have to use drop down Id 'Forex' for get the selected value of drop down not option id, like below
var sel = document.getElementById('Forex').value;

Html Code
<form id="send" name="myfrom" action="confrimationPage.php" method="POST" onsubmit="return validateForm(this);" >
<p>
<label for="company">Gender</label>
<select id="gender" name="gender">
<option value="Select One">Select One</option>
<option>Male</option>
<option>Female</option>
</select>
</p>
<p>
<label for="country">Postal Code</label>
<input id="Country" type="text" name="postalCode" />
</p>
<p>
<button id="submit" type="submit">Submit</button>
</p>
</form>
*JavaScript *
<script type="text/javascript">
function validateForm(form)
{
// Gender empty or not
var selectGender=document.getElementById('gender').value;
if(selectGender=="Select One")
{
alert("Please Select gender");
return false;
}
//Postal code empty or not
if(form.postalCode.value=="")
{
alert("Filled the Postal Code Field");
form.postalCode.focus();
return false;
}
}
</script>

Check It
var sel=document.getElementById('Forex').value;
var binary=document.getElementById('Binary').value;
if(sel.match("Forex")){
document.getElementById('error').innerHTML = "Choose Forex Workshop Date";
document.getElementById('Forex').style.borderColor = "red";
return false;
}else{
document.getElementById('error').innerHTML = "";
document.getElementById('Forex').style.borderColor = "green";
}
if(binary.match("Binary")){
document.getElementById('error').innerHTML = "Choose Forex Workshop Date";
document.getElementById('Binary').style.borderColor = "red";
return false;
}else{
document.getElementById('error').innerHTML = "";
document.getElementById('Binary').style.borderColor = "green";
}

Related

Trying to fix email validation for school project

Hey so uh I have a project due in a few days which requires us to make a contact page where someone can enter a name, email address, subject and message. We need to create javascript to make sure all fields are filled in and that the email is valid.
I have written the HTML for the form, as well as the javascript but I have 2 problems:
No error message displays when no message is entered in the memo field
The email field will not accept a valid email
I have tried to change the ID tag for the email but it automatically allows me to submit straight away without entering any data, I'm quite stuck.
Yes, they are both in two separate documents.
Note: I have not included all the code for the contact page, just the relevant form.
Thank you so much
Here are the images of my code:
HTML for contact page:
Javascript for Contact page:
function checkForm(){
var isValid = true;
var name = document.forms['contact']['name'].value;
var email = document.forms['contact']['emailaddress'].value;
var emailpattern = /\S+#\S+\.\S+/;
var subject = document.forms["contact"]["subject"].value;
var textarea = document.forms["contact"]["memo"].value;
console.log(name, email, subject, textarea);
if(name == ""){
document.getElementById('namemessage').innerHTML = "PLEASE enter a name";
isValid = false;
} else {
document.getElementById('namemessage').style.display = "none";
}
if(!emailpattern.test(emailaddress)){
document.getElementById('emailmessage').innerHTML = "PLEASE enter a valid email";
isValid = false;
}
else {
document.getElementById('emailmessage').style.display = "none";
}
if(subject == ""){
document.getElementById('subjectmessage').innerHTML = "PLEASE enter a subject";
isValid = false;
} else {
document.getElementById('subjectmessage').style.display = "none";
}
if(memo == ""){
document.getElementById('memomessage').innerHTML = "PLEASE enter your request";
isValid = false;
} else {
document.getElementById('memomessage').style.display = "none";
}
return isValid;
}
<main><form action="thankyou.html" name="contact" onsubmit="return checkForm()">
<label for="name">Name:</label>
<input type="text" id="name">
<p id="namemessage"></p><br><br>
<label for="emailaddress">Email Address:</label>
<input type="text" id="emailaddress">
<p id="emailmessage"></p><br><br>
<label for="subject">Subject:</label>
<input type="text" id="subject"><p id="subjectmessage">
</p><br><br>
<label for=memo>Message:</label><br><br>
<textarea id="memo" placeholder = "please type your message here.">
</textarea>
<br><p id="memomessage"></p><br><br>
<input type="submit" value="Submit">
</form>
</main>
No error message displays when no message is entered in the memo field
Because you have:
var textarea = document.forms["contact"]["memo"].value;
...
if (memo == "") {
Change textarea to memo.
The email field will not accept a valid email
Because you have:
var email = document.forms['contact']['emailaddress'].value;
...
if (!emailpattern.test(emailaddress)) {
Change emailaddress to email.
Fix those issues and it "works".

Show and hide element through different tabs PHP

I have a select inside a form with different types of devices from the database (devices.insert.php):
Type:<select name="type" form="form_select" onchange="showDiv(this)">
<?php
$sql = "SELECT *
FROM Property
WHERE PRP_PRP_TYP_Id = 1";
$result = sqlsrv_query($con, $sql);
echo "<option disabled selected value> -- select an option -- </option>";
while ($row = sqlsrv_fetch_array($result)){
echo "<option value='".$row['PRP_Id']."'>".$row['PRP_Value']."</option>";
}
?>
</select><br>
<script type="text/javascript">
function showDiv(elem){
if(elem.value == 3 || elem.value == 24 || elem.value == 25){
document.getElementById('sc_div').style.display = "block";
}
else{
document.getElementById('sc_div').style.display = "none";
}
}
</script>
And when I select one of the items with the correct id, a div element turns visible with more options.
<div id="sc_div" style="display:none">
...
Register new SIM<br>
</div>
In sim_cards_insert.php I have a form with submit and cancel and when I press to go back (to devices_insert.php) the div sc_div is not visible again but the data that I've filled before is in the same place.
<button type="button" class="log-btn" onClick="history.go(-1)">Cancel</button>
How can I get it visible again passing through different windows?
Sounds like the browser is reverting the DOM to it's initial state - ie with the sc_div hidden.
Perhaps you could check the previous URL for the devices_insert.php page load.
<script type="text/javascript">
function showDiv(elem){
//example
var filename = document.referrer.split('/').pop();
if(filename === 'sim_card_insert.php'){
document.getElementById('sc_div').style.display = "block";
}
//...rest of function
</script>

Drop Down Menu Validation JS

I have a dynamically generated drop down menus using PHP, I use these manes on different web pages, Now I also want to add some JS validation to these menus so that the user does not forget to choose an option while filling in a form.
The problem is that my JS code does not work and does not validate my menus, The code looks good to me I have IF statements where they check if the first option value =0 therefore there has not been selection but it still does not work
PHP code:
$option='<select id="Forex" name="workshop">';
$option.='<option value="0">Select Forex Workshop</option>';
$option.='';
while($result = mysqli_fetch_assoc($query))
{
if($timestamp < $result['endingDate'])
{
$option.='<option id="'.$result['id'].'" value='.$result['endingDate'].'>'.$result['course']." ".$result['schedule'].'</option>';
}
}
$option.='</select>';
return $option;
}
function getBinary($link){
$timestamp = date("Y-m-d");
$query2 = mysqli_query($link, $sql2);
$option2='<select id="Binary" name="workshop">';
$option2.='<option value="0">Select Binary Workshop</option>';
$option2.='';
while($result2 = mysqli_fetch_assoc($query2))
{
if($timestamp < $result2['endingDate'])
{
$option2.='<option id="'.$result2['id'].'" value="'.$result2['endingDate'].'">'.$result2['course']." ".$result2['schedule'].'</option>';
}
}
$option2.='</select>';
return $option2;
}
?>
JS CODE:
var workshop=document.getElementById('Binary').value;
if(workshop==0){
document.getElementById('Binary').style.borderColor = "red";
document.getElementById('error').innerHTML = "Please Select Workshop1";
return false;
}else{
document.getElementById('Binary').style.borderColor = "green";
}
var workshop2=document.getElementById('Forex').value;
if(workshop2==0){
document.getElementById('Forex').style.borderColor = "red";
document.getElementById('error').innerHTML = "Please Select Workshop";
return false;
}else{
document.getElementById('Forex').style.borderColor = "green";
}
You have wrongly named the select id/name.
$option='<select id="Forex" name="workshop">';
and yet you are trying to access it from JS by calling it by id workshop while the name attribute is workshop not the id.
var work=document.getElementById('workshop').value;
The id is Forex not workshop. And you call Forex from different Js line. I think your error is in trying to access a null variable. Unless you have another element with the id workshop that I'm not aware of.

Validating check box and input

i have a form that includes several text inputs and checkboxes (the checkboxes comes from a DB), so... i know how to validate them separetly but i need to validate them together, the way i'm doing this only validate checkboxes, i know why its happening but i don't know how to write the right way... ¿can you help me? here is the code:
<form action="sendreq.php" name="contact" onsubmit="return valida_frm(this)" method="post">
<label>Name</label>
<input name="name" type="text" />
<label>Email</label>
<input name="email" type="text"/><!-- And Severeal inputs then the checkboxes-->
<?php $list3 = mysql_query("SELECT * FROM products ORDER BY id ASC LIMIT 20");
while($row = mysql_fetch_object($list3)){ ?>
<input id="product" name="product[]" class="label" type="checkbox" value="<?php echo $row->name?>"><label class="label"><?php echo $row->name?></label>
<?php }?>
The Validation doesn't work fine its evident why, i just need the right way to write and unify the return of the alert:
function valida_frm(form){
var alerta="Ooops:\n";
if (form.name.value == "") {alerta+="Name.\n";}
if (form.email.value == "") {alerta+="Email.\n";}
for(var i = 0; i < form.product.length; i++){
if(form.product[i].checked)return true;}
alert('Oooops');
return false;
if (alerta!="Error:\n"){
alert(alerta);
return false;
}else{
return true;
}
}
Thanks for your time!
Do not call a field for "name" and then test form.name since it already has a .name
Then test form["product[]"] and not form.product - you cannot have id="product" since ID has to be unique!
I suggest you give id="product<?echo $somecounter; ?>" />...<label for="product<? echo $somecounter; ?>">...</label>
Also test against Error (or nothing as in my suggesion) and not Oops
Also more issues fixed
DEMO
function valida_frm(form){
var alerta="";
if (form.name.value == "") {alerta+="Name.\n";} // Please use FullName or such
if (form.email.value == "") {alerta+="Email.\n";}
var chks = form["product[]"],
checked = false;
for(var i = 0; i < chks.length; i++) {
if(chks[i].checked) {
checked = true;
break;
}
}
if (!checked) {
alerta+='Product.\n';
}
if (alerta){
alert("Error:\n"+alerta);
return false;
}
return true;
}

Duplicate form submition through $("#formname").submit();

I have a line of HTML drop down lists, and whenever the user selects one of the options, it calls a jQuery function through a class which submits the form.
<form id="workorderform" action="saveworkorder.php" method="post">
<select name="applicationtype" class="checkvalueonchange savevalueonchange">
<option></option>
<option value="Uplift" <?php echo ($wo['applicationtype']=='Uplift')?'selected':''; ?>>Uplift</option>
</select>
</form>
the savevalueonchange class calls
$(".savevalueonchange").change(function() {
autoSave();
});
which then calls
function autoSave() {
if($("#wostatus").val()=='open'){
$("#workorderform").submit();
}
}
which posts the information to the saveworkorder.php
//remove existing chargecodes
$sql = "DELETE FROM workorderchargecodes WHERE compresscoid = '".trim($_REQUEST['formid'])."'";
mssql_query($sql, $dbconn);
//now save chargecodes
$code_prefix = 'code_';
foreach($_POST as $thisPostKey => $thisPostValue) {
if((substr($thisPostKey, 0, strlen($code_prefix)))==$code_prefix) {
if(trim($thisPostValue)!=''):
$exists=false;
$sql = "SELECT * FROM workorderchargecodes WHERE compresscoid='".trim($_REQUEST['formid'])."' AND code='".substr($thisPostKey, strlen($code_prefix), strlen($thisPostKey))."'";
$res = mssql_query($sql, $dbconn);
while($arr = mssql_fetch_assoc($res)){
$exists=true;
}
if($exists==false){
$sql = "INSERT INTO workorderchargecodes (
compresscoid,
code,
time
) VALUES (
'".trim($_REQUEST['formid'])."',
'".substr($thisPostKey, strlen($code_prefix), strlen($thisPostKey))."', '".$thisPostValue."'
)";
mssql_query($sql, $dbconn);
}
endif;
}
}
As you can see, I am selecting the code from the database before I insert it into the database and am somehow still getting duplicate charge codes. I have messed with this for a few months now, and it still keeps happening.
Any ideas?
Try to add return false; in your autosave(), like this :
function autoSave() {
if($("#wostatus").val()=='open'){
$("#workorderform").submit();
return false; // add here
}
}
It will prevent to submit twice.
<form id="workorderform" action="saveworkorder.php" method="post" onsubmit="return false;">
<select name="applicationtype" class="checkvalueonchange savevalueonchange">
<option></option>
<option value="Uplift" <?php echo ($wo['applicationtype']=='Uplift')?'selected':''; ?>>Uplift</option>
</select>
</form>
use this form
it use obsubmit="return false;"

Categories

Resources