Avatar of zizzz
zizzz
Flag for United States of America asked on

Verify select option is selected using db generated select option name variable in javascript

Hi

I need help with the selection object in js.

thx

Perl form will pull info form mysql db
put in html form. The "$ID" is generated from the mysql db and concatenate with "-Car". We alsways have more than one select option form field.

<form name='form1'>
Car field:
<select name="$ID-Car" size="1">
<option value="c1">car 1</option>
<option value="c2">car 2</option>
<option value="c3">car 3</option>
</select>

<select name="$ID-Car" size="1">
<option value="c1">car 1</option>
<option value="c2">car 2</option>
<option value="c3">car 3</option>
</select>


Age field:

<select name="$ID-AgeGroup" size="1">
<option value="teen">teen</option>
<option value="adult">adult</option>
<option value="senior">senior</option>
</select>

<select name="$ID-AgeGroup" size="1">
<option value="teen">teen</option>
<option value="adult">adult</option>
<option value="senior">senior</option>
</select>

Payment field:

<select name="$ID-Payment" size="1">
<option value="1500">teen</option>
<option value="1000">adult</option>
<option value="1500">senior</option>
</select>

<select name="$ID-Payment" size="1">
<option value="1500">teen</option>
<option value="1000">adult</option>
<option value="1500">senior</option>
</select>
</form>

First, I would like to be able to verify that at least one selection is selected and give error if none is selected
Second, If one of the Car is selected than the Age group must be selected, if not thatn give error.
Third, when car and age are selected then the price must be shown in the payment field.
Payment field can be re-arranged as "text field" if it is easier.

Thx

Jason
Scripting LanguagesJavaScriptMySQL ServerWeb Languages and StandardsWeb Development

Avatar of undefined
Last Comment
Michel Plungjan

8/22/2022 - Mon
oleggold

oleggold

quote:
sub display_form
{
    my $error_message = shift;
    my $your_name = shift;
    my $your_sex = shift;
    my $your_age = shift;

    # Remove any potentially malicious HTML tags
    $your_name =~ s/<([^>]|\n)*>//g;

    # Build "selected" HTML for the "Your Sex" radio buttons
    my $your_sex_f_sel = $your_sex eq "f" ? " checked" : "";
    my $your_sex_m_sel = $your_sex eq "m" ? " checked" : "";

    # Build "selected" HTML for the "Your Age" drop-down list
    my $your_age_html = "";
    my @your_age_opts = ("Please select","Under 18","18-35","35-55","Over 55");

    foreach my $your_age_option ( @your_age_opts )
    {
        $your_age_html .= "<option value=\"$your_age_option\"";
        $your_age_html .= " selected" if ( $your_age_option eq $your_age );
        $your_age_html .= ">$your_age_option</option>";
    }

    # Display the form
    print <<END_HTML;
    <html>
    <head><title>Form Validation</title></head>
    <body>

    <form action="form_validation.cgi" method="post">
    <input type="hidden" name="submit" value="Submit">

    <p>$error_message</p>

    <p>Your Name:<br>
    <input type="text" name="your_name" value="$your_name">
    </p>

    <p>Your Sex:<br>
    <input type="radio" name="your_sex" value="f"$your_sex_f_sel>Female
    <input type="radio" name="your_sex" value="m"$your_sex_m_sel>Male
    </p>

    <p>Your Age:<br>
    <select name="your_age">$your_age_html</select>
    </p>

    <input type="submit" name="submit" value="Submit">

    </form>

    </body></html>
END_HTML

}

Open in new window

zizzz

ASKER
Hi,

We need to use javascript to validate before sending the information back.
I need the javascript function to validate the selection.

Thx

Jason
Your help has saved me hundreds of hours of internet surfing.
fblack61
Michel Plungjan

I am working on this but I have a hard time testing on my iPad
http://jsfiddle.net/mplungjan/Mzf7P/

<html>
<head>
  <meta http=""-equiv="content-type" content="text/html; charset=UTF-8">
  <title> - jsFiddle demo by mplungjan</title>
  
 
  
  <style type="text/css">
    .payment { display:none }
  </style>

<script type="text/javascript">
window.onload=function() {
  var IDs = [],
  form = document.getElementById("form1"),
  sels = form.getElementsByTagName("select");

  for (var i=0;i<sels.length;i++) {
    if (sels[i].name.indexOf("-Car") != -1) {
      IDs.push(sels[i].name.split("-")[0]);
    }
  }
  form.onsubmit=function() {
    var atLeastOne = false,id,error="",fieldToFocus;
    for (var i=0;i<IDs.length;i++) {
      id=IDs[i];
      var sel1 = this.elements[id+"-Car"];
      var sel2 = this.elements[id+"-AgeGroup"];
      var sel3 = this.elements[id+"-Payment"];
      if (sel1.selectedIndex<1) { // no selection
        sel2.selectedIndex = 0;
        sel3.selectedIndex = 0;
      }
      else {
        atLeastOne = true; // one selected
        if (sel2.selectedIndex<1) {
          error += "Please select an age group\n";
          if (!fieldToFocus) fieldToFocus=sel2;
        }
      }
      document.getElementById(id+"-Payment-span").innerHTML= (sel3.selectedIndex>0)?
         "$"+sel3.options[sel3.selectedIndex].value:"";
    }
    if (!atLeastOne) {
      alert("Please select at least one car");
      this.elements[IDs[0]+"-Car"].focus();
      return false;
    }
    if (error!="") {
      alert(error);
      if (fieldToFocus) fieldToFocus.focus();
      return false;
    }
    return true; // allow submit
  }
}
</script>


</head>
<body>
  <form id="form1">
Car field:
<select name="$ID1-Car" size="1">
<option value="">Car:</option>
<option value="c1">car 1</option>
<option value="c2">car 2</option>
<option value="c3">car 3</option>
</select>

<select name="$ID2-Car" size="1">
<option value="">Car:</option>
<option value="c1">car 1</option>
<option value="c2">car 2</option>
<option value="c3">car 3</option>
</select><br/>


Age field:

<select name="$ID1-AgeGroup" size="1">
<option value="">Age:</option>
<option value="teen">teen</option>
<option value="adult">adult</option>
<option value="senior">senior</option>
</select>

<select name="$ID2-AgeGroup" size="1">
<option value="">Age:</option>
<option value="teen">teen</option>
<option value="adult">adult</option>
<option value="senior">senior</option>
</select><br/>

Payment field:

<select name="$ID1-Payment" size="1" class="payment">
<option value="">Payment:</option>
<option value="1500">teen</option>
<option value="1000">adult</option>
<option value="1500">senior</option>
</select><span id="$ID1-Payment-span"></span>

<select name="$ID2-Payment" size="1" class="payment">
<option value="">Payment:</option>
<option value="1500">teen</option>
<option value="1000">adult</option>
<option value="1500">senior</option>
</select><span id="$ID2-Payment-span"></span><br/>

<input type="submit" />
</form>
  
</body>


</html>

Open in new window

zizzz

ASKER
Hi mplungjan,

Appreciate the effort.

But still not working.

The scenario is:

The perl/cgi will use the "while loop function" to pull the $ID for each record and the fields (car,age,etc.) associated with each record and then CONCATENATE the "variable ID" to each select or check function in the HTML

We can add a "check" field to each record to make it easier for the owner check and renew the one car or multiple check for renewal of multiple cars.

So the Javascript function in the HTLM FORM WON'T WORK because of the for While loop in perl.



print <<EBILL;

<!DOCTYPE html>
<html>
<head>
  <meta http=""-equiv="content-type" content="text/html; charset=UTF-8">
  <title> - jsFiddle demo by mplungjan</title>
</head>

<div align="center">
<table size=70%>

<form name='form1' onsubmit"DO THE WORK";>

<tr>

EBILL

Ge the info from the database:

$sth = $dbh->prepare ("$getme_multipledatanow");

$sth->execute();

while ($row = $sth->fetchrow_hashref())

{

$match=1;

$ID=$row->{'Car_ID'};
$Car=$row->{'Car'};
$AgeGroup=$row->{'AgeGroup'};


So if $ID=10 than the field below will have the $ID10 which I already replaced
print <<EBILL;

<div align="center">
<table size=70%>
<form name='form1'>

<tr>

<TD ALIGN="CENTER" VALIGN="MIDDLE" WIDTH="10%" BGCOLOR="#FFE7BF">
<INPUT TYPE= "hidden" SIZE= "25" NAME= "ID" VALUE= "10">
<FONT CLASS="other"> Please Check to Renew      </FONT>
<INPUT TYPE= "checkbox" SIZE= "10" NAME= "10-ID" VALUE= "10">
</td>

<TD ALIGN="CENTER" VALIGN="MIDDLE" WIDTH="30%" BGCOLOR="#FFE7BF"><B><FONT CLASS="other">      

<select name="10-$Car" size="1">
<option value="c1">car 1</option>
<option value="c2">car 2</option>
<option value="c3">car 3</option>
</select></FONT></B>
</td>

<TD ALIGN="CENTER" VALIGN="MIDDLE" WIDTH="30%" BGCOLOR="#FFE7BF"><B><FONT CLASS="other">      

<select name="10-$AgeGroup" size="1">
<option value="teen">teen</option>
<option value="adult">adult</option>
<option value="senior">senior</option>
</select></FONT></B>
</td>

<TD ALIGN="CENTER" VALIGN="MIDDLE" WIDTH="30%" BGCOLOR="#FFE7BF"><B><FONT CLASS="other">      
<select name="10-Payment" size="1">
<option value="1500">teen</option>
<option value="1000">adult</option>
<option value="1500">senior</option>
</select></FONT></B>
</td>

EBILL

}

print <<EBILL;
<div align="center"><input type="submit" name="action" value="Multiple Renewal Update">
</form>

</div>
</tr></table>
</div>
</body></html>

EBILL

Again we will always have more than one car.


Thx Again for the help.

Zizzz
Michel Plungjan

Not sur I see the probl
You of course will need to change my -Car to $Car or such

I am alas not around to test much these days but I believe the code I provided is close to working. Seems there is also a big in jsfiddle that makes the demo code mess up. As I am not near a real computer until next week, I hope someone can continue from where I left off
Get an unlimited membership to EE for less than $4 a week.
Unlimited question asking, solutions, articles and more.
Michel Plungjan

Here is a new version where I changed the script to your naming standard

You can have as many ets of cars/agegroups/payments as you like
The script will find them all as long as you are consistent with the naming convention you have decided upon - please note I had to add a span with an ID that matched the hidden payment select

http://jsfiddle.net/mplungjan/hTMfA/

window.onload=function() {
  var IDs = [],
  form = document.getElementById("form1"),
  sels = form.getElementsByTagName("select");

  for (var i=0;i<sels.length;i++) {
    if (sels[i].name.indexOf("-$Car") != -1) {
      IDs.push(sels[i].name.split("-")[0]);
    }
    else if (sels[i].name.indexOf("-$AgeGroup") != -1) {
        sels[i].onchange=function() {
          var id = this.name.split("-")[0];  
          var sel3 = document.getElementsByName(id+"-$Payment")[0];
          sel3.selectedIndex=this.selectedIndex;            
          document.getElementById(id+"-$Payment-span").innerHTML= (this.selectedIndex>0)?
          "$"+sel3.options[sel3.selectedIndex].value:"";
        }            
    }  
  }
  form.onsubmit=function() {
    var atLeastOne = false,id,error="",fieldToFocus;
    for (var i=0;i<IDs.length;i++) {
      id=IDs[i];
      var sel1 = this.elements[id+"-$Car"];
      var sel2 = this.elements[id+"-$AgeGroup"];
      var sel3 = this.elements[id+"-$Payment"];
      if (sel1.selectedIndex<1) { // no selection
        sel2.selectedIndex = 0;
        sel3.selectedIndex = 0;
      }
      else {
        atLeastOne = true; // one selected
        if (sel2.selectedIndex<1) {
          error += "Please select an age group\n";
          if (!fieldToFocus) fieldToFocus=sel2;
        }
      }
    }
    if (!atLeastOne) {
      alert("Please select at least one car");
      this.elements[IDs[0]+"-$Car"].focus();
      return false;
    }
    if (error!="") {
      alert(error);
      if (fieldToFocus) fieldToFocus.focus();
      return false;
    }
    return true; // allow submit
  }
}

Open in new window

zizzz

ASKER
Hi,

Could you please include the js code  in the perl code and I will give you the 500 points.

Thx
Michel Plungjan

save my code as calc.js

change
print <<EBILL;

<!DOCTYPE html>
<html>
<head>
  <meta http=""-equiv="content-type" content="text/html; charset=UTF-8">
  <title> - jsFiddle demo by mplungjan</title>
</head>

<div align="center">
<table size=70%>

<form name='form1' onsubmit"DO THE WORK";>

Open in new window

to
print <<EBILL;

<!DOCTYPE html>
<html>
<head>
  <meta http=""-equiv="content-type" content="text/html; charset=UTF-8">
  <title> ... </title>
  <script src="calc,js"></script>
</head>

<div align="center">
<table size=70%>

<form name='form1'>

Open in new window


e.g. do not forget to remove the onsubmit too

also change
<TD ALIGN="CENTER" VALIGN="MIDDLE" WIDTH="30%" BGCOLOR="#FFE7BF"><B><FONT CLASS="other">      
<select name="10-Payment" size="1">
<option value="1500">teen</option>
<option value="1000">adult</option>
<option value="1500">senior</option>
</select></FONT></B>
</td>

Open in new window

to the equivalent of
<TD ALIGN="CENTER" VALIGN="MIDDLE" WIDTH="30%" BGCOLOR="#FFE7BF"><B><FONT CLASS="other">      
<select name="10-Payment" size="1" style="display:none">
<option value="1500">teen</option>
<option value="1000">adult</option>
<option value="1500">senior</option>
</select></FONT></B>
<span id="10-$Payment-span"></span>
</td>

Open in new window


e.g. change the 10 to the ID you have.

If you do not want to hide the payment dropdown, let me know exactly what you want so I can remove relevant code too:
for example this code that syncs the age with the payment :
else if (sels[i].name.indexOf("-$AgeGroup") != -1) {
        sels[i].onchange=function() {
          var id = this.name.split("-")[0];  
          var sel3 = document.getElementsByName(id+"-$Payment")[0];
          sel3.selectedIndex=this.selectedIndex;            
          document.getElementById(id+"-$Payment-span").innerHTML= (this.selectedIndex>0)?
          "$"+sel3.options[sel3.selectedIndex].value:"";
        }            
    }

Open in new window

I started with Experts Exchange in 2004 and it's been a mainstay of my professional computing life since. It helped me launch a career as a programmer / Oracle data analyst
William Peck
zizzz

ASKER
Hi,

The payment selection can be hidden becasue we can add the amount to the age field e.g. (Adult - $1000
Teen- $1500)
but the payment field need to be a text box with the same variable id as the car and the age field so we can send it together with car and age data to the database.

It is clear that 10 in 10-Car and 10-Age is a variable that it is supplied by the perl program from the database!!!

So if you can have a complete perl and html with all the necessary function call embedded.


thx

zizzzz
Michel Plungjan

I can change the span and have the age update a payment field
Fis the HTML/perl and I'll fix the script but not tonight. Way past my bedtime
zizzz

ASKER
Thx

I guess you are not in the US??? That is fine I can wait until tomorrow.

thx


Also another idea maybe will look more professional

The payment option can be shown like this:
<TD ALIGN="CENTER" VALIGN="MIDDLE" WIDTH="30%" BGCOLOR="#FFE7BF"><B><FONT CLASS="other">      
<select name="10-Payment" size="1">
<option value="1500">teen</option>
<option value="1000">adult</option>
<option value="1500">senior</option>
</select></FONT></B>
</td>

but when the customer choose, lets say, Teen from the age group dop menu e.g.


<select name="20-$AgeGroup" size="1">
<option value="">Age:</option>
<option value="teen">teen</option>
<option value="adult">adult</option>
<option value="senior">senior</option>
</select>

then only the teen payment option will be show in the payment drop menu e.g.
<select name="20-$Payment" size="1" class="payment">
<option value="">Payment:</option>
<option value="1500">teen</option>
<option value="1000">adult</option> (INVISIBLE)
<option value="1500">senior</option>(INVISIBLE)
</select><span id="20-$Payment-span"></span><

and the adult and senior will be invisible and vice versa if they choose adult the teen and senior will be invisible.

thx
Get an unlimited membership to EE for less than $4 a week.
Unlimited question asking, solutions, articles and more.
ASKER CERTIFIED SOLUTION
Michel Plungjan

Log in or sign up to see answer
Become an EE member today7-DAY FREE TRIAL
Members can start a 7-Day Free trial then enjoy unlimited access to the platform
Sign up - Free for 7 days
or
Learn why we charge membership fees
We get it - no one likes a content blocker. Take one extra minute and find out why we block content.
Not exactly the question you had in mind?
Sign up for an EE membership and get your own personalized solution. With an EE membership, you can ask unlimited troubleshooting, research, or opinion questions.
ask a question