473,804 Members | 3,464 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Client-side Javascript validation of "select multiple" for PHP

Has anyone here ever done a case where you have a select multiple form
element and you have to do both server-side and client-side validation?

I am honestly not sure how to do it in Javascript (I keep getting errors
thrown that I can't verify because the form processes onto itself too
quickly for me to check the Javascript errors) because the select multiple
form element name has to be in the form of "var[]" because PHP will then
recognize $var as an array and not as a scalar (if it sees "$var" it will
only capture the LAST element you entered in the select multiple, if it sees
"$var[]" it gets them all).

However, "var[]" is not friendly to Javascript either, at least as far as I
can tell. So, what I need to find out is how anyone out there has ever
dealt with select-multiple form elements for BOTH Javascript AND PHP.

Thanx
Phil

PS: Code below:

<?
require_once('/home/nordicnet.no/include/nordicnet_globa l_vars_function s.php
');
require_once("$ ACTUAL_STARTPAT H/reports/include/reports_global_ vars.php");
require_once("$ ACTUAL_STARTPAT H/reports/include/reports_classes .php");

if ($hasChosenRepo rt) {
/*
$stuff = '<html><head><t itle>stuff</title></head><body><b>H ello</b>
World</body></html>';
$fileName = 'stuff.doc';

header("Content-type: application/msword");
header("Content-Length: " . strlen(ltrim($s tuff)));
header("Content-Disposition: inline; filename=" . $fileName);

echo ltrim($stuff);
*/
print_r($_POST) ;
print_r("<P>");
print_r($report Type);
}

if (!$hasChosenRep ort) {
$report = new Report;
$report->dbOpen();

?>
<html>
<head>
<title><?= $brand ?>s Report</title>
<link rel=stylesheet href=/stylesheets/nordicnet_style .css type=text/css>
</head>
<script>
<!--
function isValidReportOp tion() {
hasPickedUsers = false;
userArray = eval('document. reportForm.user s' . String.fromChar Code(91) .
String.fromChar Code(93));
for (i = 0; i < userArray.lengt h; i++) {
if (userArray[i].selected) {
hasPickedUsers = true;
break;
}
}
if (!hasPickedUser s) {
alert("Velg brukern for report");
return false;
}
hasPickedType = false;
for (i = 0; i < document.report Form.reportType .length; i++) {
if (document.repor tForm.reportTyp e[i].checked) {
hasPickedType = true;
break;
}
}
if (!hasPickedType ) {
alert("Velg reportstil");
return false;
}
hasPickedInfo = false;
for (i = 0; i < document.report Form.reportInfo .length; i++) {
if (document.repor tForm.reportInf o[i].checked) {
hasPickedInfo = true;
break;
}
}
if (!hasPickedInfo ) {
alert("Velg reportinfo");
return false;
}
}
//-->
</script>
<body>
<h2><?= $font ?>Jeg vill få <?= $brand ?>s reporten!</font></h2>
<a href=<?= $PHP_SELF ?>>Reset for ny reporten</a>
<form name=reportForm method=post action="<?= $PHP_SELF ?>"
onSubmit="retur n isValidReportOp tion()">
<?= $font ?>Velg brukern for reporten:</font><br>

<?
$reportQuery = $report->getUsers();
echo $report->userDropdown($ reportQuery);
?>

<p>
<?= $font ?>Velg reportstil:</font><br>

<? echo $report->getTypes($repo rt->getReportStilT ypes(), 'reportType'); ?>

<p>
<?= $font ?>Velg reportinfo:</font><br>

<? echo $report->getTypes($repo rt->getReportInfoT ypes(), 'reportInfo'); ?>

<p>
<input type=hidden name=hasChosenR eport value=1>
<input type=submit name=submit value="Få Min Report Nu!"
class=blue_butt on>
</form>
</body>
</html>

<?
$report->dbClose();
$report = null;
}
?>
Jul 20 '05 #1
4 4978
Hello,

On 10/19/2003 05:34 PM, Phil Powell wrote:
Has anyone here ever done a case where you have a select multiple form
element and you have to do both server-side and client-side validation?

I am honestly not sure how to do it in Javascript (I keep getting errors
thrown that I can't verify because the form processes onto itself too
quickly for me to check the Javascript errors) because the select multiple
form element name has to be in the form of "var[]" because PHP will then
recognize $var as an array and not as a scalar (if it sees "$var" it will
only capture the LAST element you entered in the select multiple, if it sees
"$var[]" it gets them all).

However, "var[]" is not friendly to Javascript either, at least as far as I
can tell. So, what I need to find out is how anyone out there has ever
dealt with select-multiple form elements for BOTH Javascript AND PHP.


This class does exactly what you need:

http://www.phpclasses.org/formsgeneration

--

Regards,
Manuel Lemos

Free ready to use OOP components written in PHP
http://www.phpclasses.org/

Jul 20 '05 #2

"Phil Powell" <so*****@erols. com> schreef in bericht
news:HIBkb.8963 6$0Z5.7232@lake read03...

I am honestly not sure how to do it in Javascript (I keep getting errors
thrown that I can't verify because the form processes onto itself too
quickly for me to check the Javascript errors) because the select multiple
form element name has to be in the form of "var[]" because PHP will then
recognize $var as an array and not as a scalar (if it sees "$var" it will
only capture the LAST element you entered in the select multiple, if it sees "$var[]" it gets them all).

The usage of $var[] is not mandatory when you are able to parse the
$HTTP_RAW_POST_ DATA string, which will be the case when you have enabled the
option 'always_populat e_raw_post_data ' in your php.ini file.

When the form method is set to GET you should parse
$_SERVER['QUERY_STRING'].
However, "var[]" is not friendly to Javascript either, at least as far as I can tell. So, what I need to find out is how anyone out there has ever
dealt with select-multiple form elements for BOTH Javascript AND PHP.


You can get around it by accessing the JavaScript Form object's elements
array:

<script language="JavaS cript">
function showSelected(fo rm) {
var s = form.elements['var[]'];
for (var i = 0; i < s.length; i++) {
if (s[i].selected) alert (s[i].value);
}
}
</script>
.....
<form method="post">
<select name="var[]" multiple="true" size="4">
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
<option value="4">4</option>
</select>
<br />
<input type="button" value="Check" onclick="showSe lected(form)" />
</form>

BTW, this is a FAQ in the comp.lang javascript newsgroup. See
http://www.jibbering.com/faq/ for more info.
JW

Jul 20 '05 #3
In article <HIBkb.89636$0Z 5.7232@lakeread 03>, "Phil Powell" <so*****@erols. com>
writes:
Has anyone here ever done a case where you have a select multiple form
element and you have to do both server-side and client-side validation?
Yes, quite often.
I am honestly not sure how to do it in Javascript (I keep getting errors
thrown that I can't verify because the form processes onto itself too
quickly for me to check the Javascript errors) because the select multiple
form element name has to be in the form of "var[]" because PHP will then
recognize $var as an array and not as a scalar (if it sees "$var" it will
only capture the LAST element you entered in the select multiple, if it sees
"$var[]" it gets them all).


Change your submit button to a type="button" and use the onclick of it to call
your validation function. Then, it won't get submitted, and you can see the
errors to debug it.

http://www.jibbering.com/faq/#FAQ4_25

Explains how to access the var[] select element, although the part about
"illegal characters" is incorrect

<FAQENTRY>
http://www.jibbering.com/faq/#FAQ4_25
Incorrectly states that [] are illegal characters in HTML. It was discussed not
long ago and I believe the final concensus was that [] are in fact legal in the
name.
</FAQENTRY>
--
Randy
Jul 20 '05 #4
Phil Powell wrote:
However, "var[]" is not friendly to Javascript either, at least as far as I
can tell.
You cannot use document.formna me.elements.var[] because
`['...`]' is the index operator in JavaScript. Use
document.forms['formname'].elements['var[]'] instead.
<?
I suggest you disable short tags and use `<?php' instead.
<html>
<head>
<title><?= $brand ?>s Report</title>
<link rel=stylesheet href=/stylesheets/nordicnet_style .css type=text/css>
</head>
<script>
That's invalid HTML. The DOCTYPE declaration is missing before the `html'
element, the charset declaration with the `meta' element is missing in the
`head' element and the `type' attribute is missing for the `script' element.
Also attribute values that contain the `/' character must be enclosed
in single or double quotes. (You should always enclose attribute values in
quotes as there are more characters that require quotes and
lookup/correction takes time.)

---> http://validator.w3.org/
[...]
<script>
<!--
function isValidReportOp tion() {
hasPickedUsers = false;
The `var' keyword is missing, you are defining global variables which you
want to avoid.
userArray = eval('document. reportForm.user s' . String.fromChar Code(91) .
String.fromChar Code(93));


eval(...) is evil[tm] and you are mixing PHP and JavaScript. In
JavaScript, the string concatenation operator is `+', not `.':

var userArray = document.forms['reportForm'].elements['users[]'];
F'up2 comp.lang.javas cript

PointedEars

Jul 20 '05 #5

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

4
2552
by: TJS | last post by:
how do I get "onSubmit" to work in .net ? <Form id="Form1" name="Form1" method="post" onSubmit="return validateStandard(this, 'error');" runat="server">
5
2592
by: JJ_377 | last post by:
I want a JavaScript validation function to fire on an ASP.NET textbox's change event. Here's what I've been trying and it is not working. The following added in the webform's page load event: txtBirthdate.Attributes.Add("txtBirthdate_TextChanged", "MyJSFunction()") txtBirthdate.Attributes.Add("TextChanged", "MyJSFunction()")
3
1733
by: Mike P | last post by:
I have a method that I use for Javascript validation (see below). What I want to do is change the alert title, buttons, icon etc. Does anybody know the correct syntax to do this? private void Gen_Alert(string Key, string msg) { string str = ""; str += "<script language='javascript'>"; str += "alert('"+msg+"')"; str += "</script>";
1
12796
by: bill | last post by:
I need to be able to dynamically add items to a <asp:listbox> (or HTML <select runat=server>) using clientside javascript, and retrieve the items when the page is posted back. I use this code to add the option to the listbox. It works for <select> or <asp:listbox> controls. var opt = document.CreateElement("OPTION"); opt.text = "test"; opt.value="test";
1
1963
by: karen987 | last post by:
I have a comment form, on a news website, ASP page, which users fill in and it adds comments to a news article. The reader clicks on a headline and the comments open up in a new window. It already has server side validation in but i want to add some client side javascript validation. How can do i this when there is alreay a "returnvalidate comment()" in? The only two fields i want to validate are "subject" and "comment" since the rest are drawn...
1
1662
by: ll | last post by:
Hi, I am working with a page that has both cfform elements and 'plain html' form elements. In particular, I am needing to validate my textarea form field and my email text field. On one of my html pages, I have been using a great javascript validation script; however, I am wondering if I can use that in a coldfusion page? I've included the javascript I'd been using before. Thanks for any help you can provide, Regards, Louis
1
1643
by: shrin | last post by:
Hi all, I want to use asp.net validator and javascript validation function on a single form for different fields. also I want to execute some code on button click after the validation is completed. My problem is that when i click on the button at first instacne it execute the javascript function however when page load event occures the error messages are not shown, even after the failed javascript validation it execute the code on button...
2
10731
by: John Kotuby | last post by:
Hi all, In ASP.NET 2.0 and VB.NET, I am trying to get the OnSelectedIndexChanged event to fire a Javascript function. There is no OnClientClick event for that control. When I try something like: OnSelectedIndexChanged="javascript:SetOwner('<%= lstOwner.ClientID %>');" I get an error.
21
16925
by: kiran83 | last post by:
My Text box can accept all types of data like alphabets,numeric,special characters ... Should give an error message 'if space is not a valid value ' when i am clicking a button... in asp.net with c# through javascript.(javascript validation after clicking a button).
1
2775
by: jerrydigital | last post by:
Hello, I have a form that i use ASP to process the form to my access database. It works well but I'm struggling to get the javascript validation to work. I have posted a small version of my form to see if any of you know why this isn't working. I believe this is supposed to have a box pop up to say "You must enter a first name." when you leave the text box blank. However, I get nothing. Any thoughts are greatly appreciated. Thanks -...
0
10562
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
0
10319
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
1
10303
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
10070
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
0
9132
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
0
6845
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
5508
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
0
5639
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
2
3803
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.