Controllo checkbox con javascript

Tommy1981

Utente Attivo
1 Mag 2010
84
0
0
Ciao a tutti,

io avrei bisogno di un aiuto...

PHP:
<script type="text/javascript">

function CAPTCHA()
{
var car, min, max, dif, lun, inc;
car  = "abcdefghijklmnopqrstuvwxyz";
car += "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
car += "1234567890";
min  = 5;
max  = 5;
dif  = max - min;
lun  = Math.round((Math.random() * dif) + min);
inc  = 0;
cod  = "";
while (inc < lun)
{
  cod += car.charAt(Math.round(Math.random() * car.length));
  inc++;
}
return cod;
}<!--Crea il captcha -->


function Prova(){
document.getElementById("captcha").innerHTML = CAPTCHA();<!--crea immagine captcha -->
}

function Invia()
{
var key2 = document.enter.key2.value;
if (key2 != document.getElementById("captcha").innerHTML)
{
  alert("Please enter a correct code");
  document.enter.key2.value = "";
  document.enter.key2.focus();
}
else
{
  document.enter.method = "post";
  document.enter.action = "<?php print($_SERVER['PHP_SELF']); ?>";
  document.enter.submit();
}
}<!--Verifica il captcha -->
</script><!--Java-->

</head>

<body>
  <?php
session_start();	// Maintain session state
header("Cache-control: private");	// Fixes IE6's back button problem.

// Dont allow members to go to add user page
if(@$_SESSION['user']) header("location: login.php");
elseif(@$_POST['user']){
	// Get and set vars (without html characters)
	$user = htmlspecialchars(strtolower($_POST["user"]));
	$pass = htmlspecialchars($_POST["pass"]);
	$permission = 0;		// Default: user, until admin changes
	$email = htmlspecialchars($_POST["email"]);
	$url = htmlspecialchars($_POST["url"]);

	// Add dots to date
	$joined = $_POST["joined"];

	// Create the string to append
	$string = "\r\n". $user. "<del>". md5($pass). "<del>". $permission. "<del>". $email. "<del>". $joined;

	// Make sure username doesn't already exist
	//-----------------------------------------
	// Include the flat-file
	$file = file("users.php") or die("Problem getting the user details flat-file [users.php]");

	// Get the size of file
	$totalLines = sizeof($file);

	// Get the users details line by line
	$line = 0;
	$match = 0;
	do{
		// Check the line isn't a comment
		if("//" != substr($file[$line], 0, 2)){
			// Break our records up
			@list($username, $password, $permission, $email, $url, $joined) = explode("<del>", $file[$line]);

			// Check the username and passwords match
			if((strtolower($user) == strtolower($username))) $match = 1;
			else $match = 0;
		}

		// Exit loop if match found
		if($match) break;
			
		// Increment line count
		$line++;
	} while($line < $totalLines);

	// Only add new user if a match is not found
	if($match){
	?>
		<script language = "javascript" type = "text/javascript">
		<!-- // Go back
			alert("Username already taken, taking you back to choose another");
			history.go(-1);
		-->
		</script>
      <?php
	}
	else{
		// Open the users file
		$fp = fopen("users.php", "a+");

		// Append the new user to end of users file
		fwrite($fp, $string);

		// Close the file
		fclose($fp);

		// Redirect to index
		header("location: index.php?new=1");
	}
}
else{
?>
      <?php
}
?>
      <form name="enter" action="">
	    <table width="451" border = "0" align = "left" cellpadding = "10" cellspacing = "0" style = "height: 80%; text-align: left;">
	<tr>
		<td height="52" colspan = "3" align="left" valign = "top">
			<span class = "bold">Join our member list!</span></td>
	</tr>
	<tr>
		<td width = "162" height = "10" align="left" valign = "top">
			<span class = "hilight">Username:</span>
		</td>
		<td width = "249" height = "10" align="left" valign = "top">
			<input name = "user" type = "text" class = "text" id = "user" style = "width: 80%" tabindex = "1" maxlength="20">
	</tr>
	<tr>
		<td width = "162" height = "10" align="left" valign = "top">
			<span class = "hilight">Password:</span>
		</td>
		<td width = "249" height = "10" align="left" valign = "top">
			<input name = "pass" type = "password" class = "text" id = "pass" style = "width: 80%" tabindex = "2" maxlength="20">
		</td>
	</tr>
	<tr>
		<td width = "162" height = "10" align="left" valign = "top">
			<p class="hilight"> Repeat Password:</p></td>
		<td width = "249" height = "10" align="left" valign = "top">
			<p>
			  <input name = "pass2" type = "password" class = "text" id = "pass2" style = "width: 80%" tabindex = "3" maxlength="20">
		    </p></td>
	</tr>
	<tr>
		<td width = "162" height = "10" align="left" valign = "top">
			Email:
		</td>
		<td width = "249" height = "10" align="left" valign = "top">
			<input type = "text" id = "email" name = "email" style = "width: 80%" class = "text" tabindex = "4">
		</td>
	</tr>
	<tr>
		<td width = "162" height = "10" align="left" valign = "top">
			Repeat Email:
		</td>
		<td width = "249" height = "10" align="left" valign = "top">
			<input type = "text" id = "url" name = "url" style = "width: 80%" class = "text" tabindex = "5">
		</td>
	</tr> 
	<tr>
		<td width = "162" height = "10" align="left" valign = "top">
			Join our newsletter:
		</td>
		<td width = "249" height = "10" align="left" valign = "top"><label>
		  <input type="checkbox" name="news" id="news" />
		  </label></td>
	</tr>
    <tr>
		<td width = "162" height = "10" align="left" valign = "top">
			Read and approve privacy policy:
		</td>
		<td width = "249" height = "10" align="left" valign = "top"><label>
		  <input type="checkbox" name="privacy" id="privacy" />
		  </label></td>
	</tr>
    <tr>
        <th width="199" height="74" scope="row"><p>Enter code from image (case sensitive):</p></th>
        <td width="181"><label>          
          <center>
            <span id="captcha"></span><br><br>
            <input name="key2" type="text" id="key2" size="10">
          </center>
        </label>        
        </td>
        </tr>
	<tr>
		<td  width = "100" height = "30" colspan = "3" valign = "top"><input name = "submit" type = "Image" tabindex = "10" onfocus = "return checkFields();" src = "Immagini/Enter/Join.gif" alt = "arrow pointing right: next" align = "middle" onclick="Invia()"/>		  <input type = "hidden" name = "joined" value = "<?php print(date("d.m.Y H:i:s", mktime())); ?>" /></td>
	</tr>
</table>
</form> <!--Form registrazione -->

<script language = "javascript" type = "text/javascript">
<!--// Check field values are correct before submitting
	function checkFields(){
		var flag = 1;	// Return flag

		// Check for empty values in important fields first
		if(!document.getElementById("user").value || !document.getElementById("pass").value || !document.getElementById("pass2").value || !document.getElementById("email").value ||!document.getElementById("url").value ||!document.getElementById("key2").value){
			alert("Please enter all values, join the newsletter and approve privacy terms");
			document.getElementById("user").focus();
			return true;
		}
		// Check that passwords are the same
		else if(document.getElementById("pass").value != document.getElementById("pass2").value){
			alert("Please enter two matching passwords");
			document.getElementById("pass").value = '';
			document.getElementById("pass2").value = '';
			document.getElementById("pass").focus();
			return true;
		}
		// Check that email are the same
		else if(document.getElementById("email").value != document.getElementById("url").value){
			alert("Please enter two matching email");
			document.getElementById("email").value = '';
			document.getElementById("url").value = '';
			document.getElementById("email").focus();
			return true;
		}
		else flag = 0;

		// One final check if the others went through fine
		if(!flag){
			if(document.getElementById("email").value){
				// Finally, check the email
				if(document.getElementById("email").value.indexOf("@") == -1 || document.getElementById("email").value.indexOf(".") == -1){
					alert("Please make sure email is valid");
					document.getElementById("email").focus();
					return true;
				}
				else return false;
			}
			else return false;
		}
	}

-->
</script>
  </div> 
  <!--Registrazione -->

</body>
</html>

Il codice qui sopra è un form riadattato da me che raccoglie dati di registrazioni e fa un pò di verifiche, se l'user esiste già, la mail, che tutto sia inserito e cose così più la generazione del CAPTCHA.

Quello che non riesco a fare è verificare che i checkbox siano stati spuntati....

Credo dovrei prima definire le variabile e poi inserire nello script il controllo delle stesse....una cosa tipo:

PHP:
// Get and set vars (without html characters)
	$user = htmlspecialchars(strtolower($_POST["user"]));
	$pass = htmlspecialchars($_POST["pass"]);
	$permission = 0;		// Default: user, until admin changes
	$email = htmlspecialchars($_POST["email"]);
	$url = htmlspecialchars($_POST["url"]);
        $news = $_POST["news"];
        $privacy = $_POST["privacy"];

 Check for empty values in important fields first
		if(!document.getElementById("user").value || !document.getElementById("pass").value || !document.getElementById("pass2").value || !document.getElementById("email").value ||!document.getElementById("url").value ||!document.getElementById("privacy").value ||!document.getElementById("news").value||!document.getElementById("key2").value){
			alert("Please enter all values, join the newsletter and approve privacy terms");
			document.getElementById("user").focus();
			return true;
		}

Però così non va....sbaglio i comandi....Chi sa dirmi come devo inserire le variabili e recuperarle nello script?

Grazie
 

alessandro1997

Utente Attivo
6 Ott 2009
5.302
1
0
26
Roma
alessandro1997.netsons.org
Con Javascript per controllare se una checkbox è spuntata basta controllarne il valore. Se è quello definito nel parametro value allora è spuntata, altrimenti no. Una cosa del genere:
Codice:
if(document.getElementById('IDcheck').value == 'valoredefinito')
{
    // ...
}
else
{
    // ...
}
 

Tommy1981

Utente Attivo
1 Mag 2010
84
0
0
E il "valoredefinito" lo setto così:

PHP:
<input type="checkbox" name="privacy" id="privacy" value="1" />

E quindi dopo avrò una cosa tipo:

PHP:
// Check newsletter
		else if(document.getElementById("news").value == "1")
		{
			alert("Please join the newsletter");
			document.getElementById("news").focus();
			return true;
		}
		// Check newsletter
		else if(document.getElementById("privacy").value == "1")
		{
			alert("Please you need to approve privacy terms");
			document.getElementById("privacy").focus();
			return true;
		}

O no?
 

Tommy1981

Utente Attivo
1 Mag 2010
84
0
0
Ho risolto con uno script così...

PHP:
if(document.forms[0].news.checked != true) {
		alert("Please join our newsletter");
        document.forms[0].news.focus();
        return false;
        }

Grazie Ale.
 
Discussioni simili
Autore Titolo Forum Risposte Data
T [Javascript] un controllo con checkbox che non... controlla... Javascript 3
MarcoGrazia jquery validate() controllo checkbox jQuery 2
P [PHP] Controllo al checkbox privacy PHP 6
P Controllo php su checkbox PHP 2
C controllo campo email e checkbox Javascript 18
M pulsante per aprire una maschera che contiene controllo schede MS Access 0
G [PHP] Creare script di prenotazione con controllo disponibilità. PHP 7
Z Controllo giorni MYSQL PHP 0
M Problema con controllo form in real time jQuery 6
M Controllo del codice fiscale/partita iva PHP 11
S Software windows10 per controllo contenuti web Windows e Software 6
S Controllo appuntamenti disponibili sul db PHP 5
L input (controllo se è stato modificato o no). PHP 1
W Controllo competitors serp SEO e Posizionamento 2
bubino8 [Javascript] popup di controllo elimina dopo window.print(); Javascript 0
M [MS Access] controllo valido se MS Access 8
MarkRed Come indicare, in una maschera, il primo controllo d'input, tipo "SetFocus" jQuery 9
C [PHP] Controllo <select> comportamento anomalo PHP 2
elpirata [Javascript] Controllo campi required non effettuato Javascript 2
A [PHP] Controllo nome utente form di registrazione PHP 4
L [PHP] controllo dimensione immagine per il resize PHP 2
M [ASP] Upload file da form controllo Classic ASP 5
S [MySQL] Controllo dati di una tabella in tempo reale MySQL 0
T [php] controllo su estensione file PHP 7
M [PHP] Script per controllo disponibilitá negozio in citta PHP 4
I Recupero accesso pannello di controllo dominio Leggi, Normative e Fisco 2
F Controllo dati sui campi di input tramite php PHP 1
R [MS Access] CONDIZIONE CHE CAMBIA PROPRIETA' DI UNA CONTROLLO MS Access 7
M [PHP] Dubbio controllo IF PHP 15
M [PHP] Controllo campo cap con trattino oltre ai numeri PHP 3
Fede72 Controllo registrazioni PHP Mysql PHP 5
L jquery e json controllo valori da determinate chiavi - keys jQuery 0
bubino8 [PHP] Controllo Log e Modifiche Utenti PHP 5
P [PHP] Realizzare un controllo accessi cantiere, problema lettore Qrcode... PHP 0
M [PHP] Controllo inserimento in tempo reale PHP 0
M [PHP] Help: controllo valori inseriti in un campo PHP 1
M [PHP] Impedire di digitare determinati caratteri nell’input (controllo in tempo reale) PHP 4
giancadeejay [PHP] Controllo inserimento tot caratteri PHP 5
giancadeejay [PHP] Controllo su quantita' di caratteri inseriti, in colonna db PHP 5
F [Javascript] Controllo stringa jquery Javascript 4
B [MySQL] CONTROLLO SE CAMPO1 > CAMPO2 MySQL 0
CristianB72 [PHP] Controllo sintassi indirizzo email non funziona PHP 13
M [PHP] controllo inserimento dati un un form PHP 4
ANDREA20 [PHP] Controllo email se e valida PHP 5
elpirata [Javascript] Controllo su campo ricerca data Javascript 1
P scavalca il controllo dello username PHP 1
A problema controllo Javascript 2
C controllo con metodo text non funzionante Javascript 7
P Controllo valori duplicati in un campo a Maschere continue MS Access 0
P controllo browser sul server o in php? PHP 2

Discussioni simili