Here is my input field disabled code
<input type="text" class="empl_date form-control" id="staffid" name="staffid" value="<?php echo $employeeworks[0]['employeeCode'];?>" arsley-maxlength="6" placeholder=" Schedule Date" disabled />
How can i prevent inspect element option in this field?
No it's not possible.
Code inspectors are designed for debugging HTML and Javascript. They will always do show the live DOM object of web page. It means that it reveals the HTML code of everything you see on the page, even if they're generated by Javascript.
As mentioned in other answers, it can't be prevented fully, once it is in the browser, user can manipulate it.
Rather than thinking how to prevent the inspect element or dev tools being used on your input, you should think about your goal, what do you want to achieve with this?
If you want to prevent from input value being changed, use some hash generated on server side, that includes value from your staffid field and store it in hidden input.
When user submits the form, just regenerate hash using staffid value and hash value from input. If they don't match, user has manipulated the staffid input manually.
Example:
<input type="text" class="empl_date form-control" id="staffid" name="staffid" value="<?php echo $employeeworks[0]['employeeCode'];?>" arsley-maxlength="6" placeholder=" Schedule Date" disabled />
<input type="hidden" name="hash" value="<?php echo md5($employeeworks[0]['employeeCode'] . 'some salt to avoid user just generating hash with md5 using value only'); ?> />
and then on submission:
$staffid = filter_input(INPUT_POST, 'staffid');
$hash_input = filter_input(INPUT_POST,'hash');
$hash_check = md5($staffid . 'some salt to avoid user just generating hash with md5 using value only');
if($hash_input !== $hash_check){
//looks like the user manipulated staffid value, throw a validation error
}
You can prevent inspect by right click.
This way to prevent right click
document.addEventListener('contextmenu', function(e) {
e.preventDefault();
});
If user press F12 and click arrow button and inspect, it still ok.
You also can prevent F12 by this code
document.onkeydown = function(e) {
if(event.keyCode == 123) { //F12 keycode is 123
return false;
}
}
Actually, you can not restrict user to check inspect element of any specific element but you can disable completely. Check below code which will not allow user to open debugger and not even page source.
document.onkeydown = function(e) {
if(e.keyCode == 123) {
e.preventDefault();
return false;
}
if(e.ctrlKey && e.shiftKey && e.keyCode == 'I'.charCodeAt(0)) {
e.preventDefault();
return false;
}
if(e.ctrlKey && e.shiftKey && e.keyCode == 'C'.charCodeAt(0)) {
e.preventDefault();
return false;
}
if(e.ctrlKey && e.shiftKey && e.keyCode == 'J'.charCodeAt(0)) {
e.preventDefault();
return false;
}
if(e.ctrlKey && e.keyCode == 'U'.charCodeAt(0)) {
e.preventDefault();
return false;
}
}
But this code also has some missings as well. Hope it helps you.
Try This,
<input type="text" oncontextmenu="return false;" class="empl_date form-control" id="staffid" name="staffid" value="<?php echo $employeeworks[0]['employeeCode'];?>" arsley-maxlength="6" placeholder=" Schedule Date" disabled />
Related
Is there a php way to validate a form that goes submitted to another page before submitting and stay on same page if fields are not valid or if everything valid send post data to another page?
Example would be:
I am on page somesite.com/orderitems and there would be form like
<form method="post" id="orderform" action="somesite.com/shoppingcart">
<input type="number" name="numitems" id="numitems" value="1">
<input type="date" name="date" id="date">
</form>
So google chrome for example already knows to validate if you put in input field required value and to validate date and number fields. I have also a jquery datepicker so user can select date easily, and also jquery validator to validate fields before submit, but all this can be overridden and/or fail at some point.
So end point would be validation in php when form is submitted.
But what i am stumbled upon is that i can't use GET request in getting data on somesite.com/shoppingcart so i must send POST to that page, but if some of the field fail to validate, like wrong date or wrong date format, than i shouldn't even go (redirect or post) to somesite.com/shoppingcart, instead i should stay on the page somesite.com/orderitems and display the errors.
So is there a solution to something like this, what suggestions would you recommend. Can i post form to the same page and validate fields if, all is good than redirect to another page and pass POST data, or stay on same page and display error?
I will show you how this can be done via JavaScript/Ajax and PHP. I think it won't be difficult to learn doing it from this tutorial, but if some questions arise I am ready to help you.
JavaScript/Ajax request
First of all, we need to add "Submit" button to form and set "sendData()" function as its "onclick" listener. Which means each time you click on "Submit" button, "sendData()" function will execute. Also, we need to add 'class' attribute to 'number' and 'date' input elements, to get their values in more cleaner way.
<form method="post" id="orderform" action="somesite.com/shoppingcart">
<input type="number" class='myForm' name="numitems" id="numitems" value="1">
<input type="date" class='myForm' name="date" id="date">
<input type="Submit" value="Send" onclick = sendData(); return false;"/>
</form>
<script type="text/javascript">
function sendData()
{
var formElements = document.querySelectorAll(".myForm"); // We use 'class' attribute to get form elements (number and date).
var formData = new FormData(); // we create FormData object with which we can send data to "PHP" script (server side).
for(var i = 0; i < formElements.length; i++)
{
formData.append(formElements[i].name, formElements[i].value);
}
//AJAX Starts Here
var xmlHttp = new XMLHttpRequest(); // Create "ajax" object
xmlHttp.onreadystatechange = function() //This is to wait for response from your PHP script
{
if(xmlHttp.readyState === 4 && xmlHttp.status === 200) //And when status is OK use result
{
var responseText = xmlHttp.responseText; //here you save your response from server side.
if(responseText["Status"] === "OK") //if you send from server side that "Status" is OK, then you can go to that page
{
window.location.href = "somesite.com/shoppingcart";
}
else //otherwise you refresh page
{
window.location.reload();
}
}
}
xmlHttp.open("POST", "somesite.com/shoppingcart"); //set page value, where you want to send form values
xmlHttp.send(formData); //send actual data
}
</script>
PHP validation (to avoid manipulation/override on client-side)
When you validate values in server-side, set $_SESSION["Status"] = "OK".
After that if someone tries to "hack" your page and "change" your JavaScript functions to navigate to somesite.com/shoppingcart page, you will check:
somesite.com/shoppingcart
<?php
if($_SESSION["Status"] === "OK"])
{
//give permission
}
else
{
return false;
}
?>
i am also facing this problem. and i solve it by doing this
UPDATE
$(document).ready(function () {
$('#orderform').validate({
rules: {
numitems: {
required: true,
number: true
},
date: {
required: true,
date: true
}
}
});
$('#orderform input').on('keyup blur', function () {
if ($('#orderform').valid()) {
$("#button1").removeClass("submit");
//TRIGGER FORM
//$('#orderform').submit();
}
});
});
.submit{
user-select: none;
color:red;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/jquery-validation#1.17.0/dist/jquery.validate.js"></script>
<form method="post" id="orderform" action="somesite.com/shoppingcart">
<input type="number" name="numitems" id="numitems"><br/>
<input type="date" name="date" id="date"><br/>
<span class="submit" id="button1">SUBMIT</span>
</form>
i Hope it helps.!
I have various input elements which control the "hidden" state of various dependent divs.
The type of input varies, and the value which the input must equal (to reveal the div) also varies. I have used php to write javascript (jQuery) depending on these factors, by using the general piece of code:
php
$remove .=" $('#".$id."').removeClass('hide');";
$add .="$('#".$id."').addClass('hide');";
...
$jquery ="
$(\"input[name$='$name."']\").change(function(){
if(this.value == '".$key_val."') {
".$remove."
} else {
".$add."
}
}).trigger('change');
";
Note: the $remove and $add variables are built using concatenation and loops as there may be several hidden elements which need to be hidden or revealed (hence the .=)
This generally results in a piece of code on page (actual code) such as:
jQuery
$(document).ready(function(){
$("input[name$='q_32']").change(function(){
if(this.value == 'Yes') {
$('#qu_33').removeClass('hide');
} else {
$('#qu_33').addClass('hide');
}
}).trigger('change');
$("input[name$='q_32']").change(function(){
if(this.value == 'No') {
$('#qu_34').removeClass('hide');
} else {
$('#qu_34').addClass('hide');
}
}).trigger('change');
});
On the page this works well: when the radio button in question (input name q_32) is changed, the corresponding element is hidden or revealed.
The .trigger('change'); is there because I want the divs to be hidden or revealed on page load having set the checked state server side.
The following is the HTML is how the page now loads:
HTML
<span>Yes</span>
<input type="radio" id="q_32_Yes" value="Yes" name="q_32" checked="">
<span>No</span>
<input type="radio" id="q_32_No" value="No" name="q_32">
<div id="qu_33" class="hide">...</div>
<div id="qu_34" class="">...</div>
i.e. the radio button is loading in the checked state for Yes, but the incorrect div is being revealed - so it is triggering, however it seems that the value is being read wrong.
The script should be
$(document).ready(function () {
$("input[name$='q_32']").change(function () {
if (this.value == 'Yes') {
$('#qu_33').removeClass('hide');
} else {
$('#qu_33').addClass('hide');
}
});
$("input[name$='q_32']").change(function () {
if (this.value == 'No') {
$('#qu_34').removeClass('hide');
} else {
$('#qu_34').addClass('hide');
}
});
$("input[name$='q_32']").filter(':checked').change()
});
Demo: Fiddle
a more correct script will be
$(document).ready(function () {
$("input[name$='q_32']").change(function () {
if (this.value == 'Yes') {
$('#qu_33').removeClass('hide');
$('#qu_34').addClass('hide');
} else {
$('#qu_33').addClass('hide');
$('#qu_34').removeClass('hide');
}
}).filter(':checked').change();
});
Demo: Fiddle
If you have more instances of the same code then try this
I have been working on creating a form with a set of fields like username, passwords etc....
I want to make validation when the SUBMIT button is clicked.
I'm trying to get alert from my border color. All fields are valid my border must change into Green color If it has any errors it should change to red color.
Any one has any ideas regarding to my problem
If anyone has any suggestion??
You can use jquery plugin.... here you are. JQuery Form validation custom example
Use jQuery validation plugin: http://docs.jquery.com/Plugins/Validation
In this plugin, you have to define validation rules for the field. You can also set the error messages for given field for given validation rule.
This plugin adds classes to valid and invalid field.
You have to give the css for that class.
For example:
$(document).ready(function(){
$(".my_form").validate({
rules:{ // validation rules
email_address: {
required:true,
email: true
},
password:{
minlength: 6
},
confirm_password: {
equalTo:"#password"
}
},
messages: {
email_address: {
required: "Please enter email address",
email: "Please enter valid email address",
},
/*
likewise you can define messages for different field
for different rule.
*/
}
errorClass: "signup_error",
/*This is error class that will be applied to
invalid element. Use this class to style border.
You can give any class name.*/
});
});
Once you click on submit button, and field is invalid, the plugin adds class to the element that you have specified as errorClass, and when you enter valid value in the field, the plugin will remove this class and will add 'valid' class by default.
You can use these two classes to style valid and invalid element using simple element.
.valid {
border-color:"green"
}
.signup_error {
border-color:"red"
}
Hope this resolves your problem.
Js i the way to go. You can find some really good validators for jQuery should you google for it.
To custom build a simple validator I would go like this
<form class="validator">
<input type="text" name="my-input-1" data-validator="integer"/>
<input type="text" name="my-input-2" data-validator="email"/>
....
</form>
<script>
$("form.validator").submit(evt, function() {
var errors = 0;
$(this).find('[data-validator]').each(function(e, i) {
var value = $(this).value;
switch($(this).data('validator')) {
case 'integer':
if (!(parseFloat(value) == parseInt(value)) && !isNaN(value)) {
$(this).css({'border-color': '#FF0000'});
errors++;
} else
$(this).css({'border-color': '#000000'});
break;
case 'email':
if (..... // regex validate email ...) {
$(this).css({'border-color': '#FF0000'});
errors++;
} else
$(this).css({'border-color': '#000000'});
break;
}
});
if (errors > 0) {
// If you want to prevent default event execution no matter what
evt.preventDefault();
// If you want you other attached events to NOT run
evt.stopPropagation();
// signal failure
return false;
}
// All is well, go on
return true;
});
</script>
of course it's always good practice to build functions for every validator and even better to wrap the whole thing in a jQuery widget (I would suggest using jQuery Widget Factory) which would allow you to enhance it in the future and keep you flexible to changes
You can use DOJO library to validate form fields. It's easy to implement.
Given below is the tutorial to implement dojo
http://dojotoolkit.org/documentation/tutorials/1.6/validation/
and this is the working example you can see...
http://dojotoolkit.org/documentation/tutorials/1.6/validation/demo/dijitcheck.html
I made a validation library just for general javascript purposes. It is even unit tested! You can override whatever you want fairly easily as well: https://github.com/parris/iz
As far as highlighting invalid fields you can just change the style of that field or add a class. The example below just changes the background color of the input and adds a message.
Working example: http://jsfiddle.net/soparrissays/4BrNu/1/
$(function() {
var message = $("#message"),
field = $("#field");
$("#the-form").submit(function(event) {
if (iz(field.val()).alphaNumeric().not().email().valid){
message.text("Yay! AlphaNumeric and not an email address");
field.attr("style","background:green;");
} else {
message.text("OH no :(, it must be alphanumeric and not an email address");
field.attr("style","background:red;");
}
return false;
});
});
The validator is called iz. It simply lets you chain validations together and it will tell you if everything passed or if you check the "errors" object it'll give you more specifics. Beyond that you can specify your own error messages. Check the docs on github.
What is happening here is we are setting a click handler for the submit event once the page is ready. return false; at the bottom of the submit callback prevents the form from submitting. If you return true; the form will continue on. Instead of return false you could also event.preventDefault(); but I prefer the return syntax for consistency. In the real world with multiple form elements you may do something like this (psuedo code):
var passed = true;
if (check field 1 is false)
...
if (check field 2 is false)
...
if (check field n is false)
passed = false
style and add message
if passed
return true
else
return false
The if statement checks the validation rules and makes changes to the DOM accordingly. By doing it in this way you are able to give a complete list of all passed and failed fields with a full description of what is incorrect.
I have used this plugin in the past, makes implementation very easy and has good documentation and examples.
My advice use jQuery
to try first create multiple inputs and give them a class
html:
<input type="text" class="validate" value="asdf" />
<input type="text" class="validate" value="1234" />
<input type="text" class="validate" value="asd123" />
<input type="text" class="validate" value="£#$&" />
<input type="text" class="validate" value=" " />
then use the code below to see how it works
jQuery:
// Validate Function
function validate(element) {
var obj = $(element);
if (obj.val().trim() != "") {
// Not empty
if (!/^[a-zA-Z0-9_ ]{1,10}$/.test(obj.val())) {
// Invalid
obj.css('border-color', '#FAC3C3');
if (!obj.next().hasClass('error'))
{ obj.after('<span class="error">Please use letters or numbers only and not more than 10 characters!</span>'); }
else
{ obj.next().text('Please use letters or numbers only and not more than 10 characters!'); }
} else {
// Valid
obj.css('border-color', 'lightgreen');
if (obj.next().hasClass('error'))
{ obj.next().remove(); }
}
} else {
// Empty
obj.css('border-color', '#FAC3C3');
if (obj.next().hasClass('error'))
{ obj.next().text('This field cannot be empty!'); }
else
{ obj.after('<span class="error error-keyup-1">This field cannot be empty!</span>'); }
}
}
$(document).ready(function() {
// Each
$('.validate').each(function() {
// Validate
validate(this);
// Key up
$(this).keyup(function() {
// Validate
validate(this);
});
});
});
jsfiddle : http://jsfiddle.net/BerkerYuceer/nh2Ja/
A server side validation example of your need. You may try it out.
<?php
error_reporting(0);
$green = "border: 3px solid green";
$red="border: 3px solid red";
$nothing="";
$color = array ("text1"=>$nothing , "text2"=>$nothing) ;
if ( $_POST['submit'] ) {
if($_POST['text1']) {
$color['text1'] = $green;
}
else $color['text1'] = $red;
if($_POST['text2'] ) {
$color['text2'] = $green;
}
else $color['text2'] = $red;
}
?>
<form method="post">
<input type="text" name="text1" style="<?php echo $color ['text1']?>" value="<?php echo $_POST['text1']?>">
<input type="text" name="text2" style="<?php echo $color ['text2']?>" value="<?php echo $_POST['text2']?>">
<input type="submit" name="submit">
</form>
Note
Always sanitize user input.
error_reporting off is not a good practice at all. I did it as this is not a code of production environment.
Check before trying to access in the post array using isset or something similar function like this.
Always check if a variable exist before using.
$("#btn").click(function(){
// Check all of them
if( $.trim($("#file").val()) == ""){
$("#file").css("border","1px solid #ff5555");
}else{
$("#file").css("border","1px solid #cccccc");
if( $.trim($("#showboxResimBaslik").val()) == ""){
$("#showboxResimBaslik").css("border","1px solid #ff5555");
}else{
$("#showboxResimBaslik").css("border","1px solid #cccccc");
if( $.trim($("#showboxResimEtiket").val()) == ""){
$("#showboxResimEtiket").css("border","1px solid #ff5555");
}else{
if($.trim($("#showboxResimSehir").val()) == ""){
$("#showboxResimSehir").css("border","1px solid #ff5555");
}else{
$("#showboxResimSehir").css("border","1px solid #cccccc");
$("#resimYukleForm").removeAttr("onSubmit");
$('#resimYukleForm').bind('submit', form_submit);
}
}
}
}
});
probably the easiest way is to use this javascript:
http://livevalidation.com/examples#exampleComposite
I think it suits your description the best.
check below link, here i have only checked for empty fields and if the fields are empty then changed input fields id which will change input field border color.
http://jsfiddle.net/techprasad/jBG7L/2/
I have used
$("#myb").click(function(){
that is on button click event but you can use submit event.
Here is what I would say is short precise and concise way to do this in jQuery.
HTML:
<form id="myform" name="form" action="http://www.google.com">
<div class="line"><label>Your Username</label><input class="req" type="text" /></div>
<div class="line"><label>Your Password</label><input class="req" type="password" /></div>
<div class="line"><label>Your Website</label><input class="req" type="text" /></div>
<div class="line"><label>Your Message</label><textarea class="req"></textarea></div>
<div class="line"><input type="submit" id="sub"></submit>
</form>
CSS:
.line{padding-top:10px;}
.inline input{padding-left: 20px;}
label{float:left;width:120px;}
jQuery:
$(function() {
function validateform() {
var valid = true;
$(".req").css("border","1px solid green");
$(".req").each(function() {
if($(this).val() == "" || $(this).val().replace(/\s/g, '').length == 0) {
$(this).css("border","1px solid red");
valid = false;
}
});
return valid;
}
$("#sub").click(function() {
$('#myform').submit(validateform);
$('#myform').submit();
});
});
LIVE DEMO
Well hi, you can use html5 "required" and "pattern" in your form's fields.
You'll get red border if it's wrong and green if it's right.
You can even style the :valid and :invalid entry fields if the colors aren't which you wanted.
I've never tested it but why not, it's better than nothing ;)
html5 solution
Firs Learn javascript, if you have some basic knowledge of js and need to know the logic, go on read..
First you need an event handler to run a function on form submit
Easiest way is (though there are better ways)
<form action="som.php" onsubmit="functionName()">
form here
</form>
This will trigger the function called functionname.
In function name function access the input fields and validate using regular expressions
function functionName()
{
//verification code
if(verified)
{
//code to change border to green
}
}
You need to get the input fields and validate them. If you don't know how to do that, get a few Javascript books
If you need to validate as soon as value is typed use the on onchange event on input fields
I have registration form on my website that, using jquery I append default values to, and onFocus/blur the default values hide and show accordingly.
My problem is that when the form is submitted and has kicked back errors using php validation, I am unable to show the posted values in the fields. The javascript seems to write over the posted data that is echoed using php in the input value.
When I look at the page source after posting my form I see that in the value of the input I do appear to have the posted value, the value that I want shown. Example:
<input type="text" name="first_name" value="Harry" />
PHP has done it's work in echoing the posted data into the value of my input. Then Javascript changes it so that instead of the user seeing their name (Harry in this example) they once again see the default jquery appended "First name".
This happens even though I have a value in the input.
How can I modify my Javascript to take note of the value of my input and not write over it?
This is the code so far:
$(document).ready(function() {
$('input[name=first_name]').val('First name');
$('input[name=last_name]').val('Last name');
$('input[name=email_address]').val('Email address');
// cache references to the input elements into variables
var passwordField = $('input[name=password]');
var emailField = $('input[name=email_address]');
var firstnameField = $('input[name=first_name]');
var lastnameField = $('input[name=last_name]');
// get the default value for the fields
var emailFieldDefault = emailField.val();
var firstnameFieldDefault = firstnameField.val();
var lastnameFieldDefault = lastnameField.val();
// add a password placeholder field to the html
passwordField.after('<input id="passwordPlaceholder" type="text" value="Password" autocomplete="off" />');
var passwordPlaceholder = $('#passwordPlaceholder');
// show the placeholder with the prompt text and hide the actual password field
passwordPlaceholder.show();
passwordField.hide();
// when focus is placed on the placeholder hide the placeholder and show the actual password field
passwordPlaceholder.focus(function() {
passwordPlaceholder.hide();
passwordField.show();
passwordField.focus();
});
// and vice versa: hide the actual password field if no password has yet been entered
passwordField.blur(function() {
if(passwordField.val() == '') {
passwordPlaceholder.show();
passwordField.hide();
}
});
// when focus goes to and moves away from the fields, reset it to blank or restore the default depending if a value is entered
emailField.focus(function() {
if(emailField.val() == emailFieldDefault) {
emailField.val('');
}
});
emailField.blur(function() {
if(emailField.val() == '') {
emailField.val(emailFieldDefault);
}
});
firstnameField.focus(function() {
if(firstnameField.val() == firstnameFieldDefault) {
firstnameField.val('');
}
});
firstnameField.blur(function() {
if(firstnameField.val() == '') {
firstnameField.val(firstnameFieldDefault);
}
});
lastnameField.focus(function() {
if(lastnameField.val() == lastnameFieldDefault) {
lastnameField.val('');
}
});
lastnameField.blur(function() {
if(lastnameField.val() == '') {
lastnameField.val(lastnameFieldDefault);
}
});
});
$('input[name=first_name]').val('First name');
This unconditionally sets the value of that element to First Name. It's not a "only set the value if it's empty", it's "set the value to First Name, regardless of what it's in there".
You'd need something like this to preserve what's in there:
if ($('input[name=first_name]').val() == '') {
$('input[name=first_name]').val('First name');
}
instead, which would only reset the field's value if it starts out empty.
Just get some placeholder plugin, your code repeat itself too much and still does not do what you need
This is just what you need:
http://plugins.jquery.com/project/input-placeholder
With it your code will look very clear and simple, like:
<input type="text" name="first_name" placeholder="First Name" />
<input type="text" name="last_name" placeholder="Last Name" />
<input type="text" name="email_address" placeholder="Email" />
<script>
$(function(){
$('input[placeholder]').placeholder();
})
</script>
Instead all of your javascript
on ready function your are setting some values before your default values
$('input[name=first_name]').val('First name');
$('input[name=last_name]').val('Last name');
$('input[name=email_address]').val('Email address');
so your defalut values cannot be empty
This is how i would do it so it would be more dynamic and less code.
<input type="text" name="first_name" rel="First Name" value="<?=$first_name?>" />
<input type="text" name="last_name" rel="Last Name" value="<?=$last_name?>" />
<input type="text" name="email" rel="Email" value="<?=$email?>" />
$(function(){
$('input').each(function(){
var val = $(this).val(),
rel = $(this).attr('rel');
$(this).focus(function(){
if(val === rel){
$(this).val('');
}
});
$(this).blur(function(){
if(val === ''){
$(this).val(rel);
}
});
if(val === ''){
$(this).val(rel);
}
});
});
With the minimum changes:
if($('input[name=first_name]').val()!='')
$('input[name=first_name]').val('First name');
if($('input[name=last_name]').val()!='')
$('input[name=last_name]').val('Last name');
if($('input[name=email_address]').val()!='')
$('input[name=email_address]').val('Email address');
Another cool way:
if($('input[name=first_name]').val()!='') {
$('input[name=first_name]').val('First name');
$('input[name=first_name]').class('init');
}
if($('input[name=last_name]').val()!='') {
$('input[name=last_name]').val('Last name');
$('input[name=last_name]').class('init');
}
if($('input[name=email_address]').val()!='') {
$('input[name=email_address]').val('Email address');
$('input[name=email_address]').class('init');
}
var initVals = new Array();
$("form input").each( function (i) { initVals[i] = this.value; } );
$("form input").focus( function () {
if ( $(this).hasClass("init") ){
$(this).removeClass("init");
$(this).val("");
}
} );
$("form input").blur( function (i) {
if ( $(this).val() == "" || $(this).val() == initVals[$("form input").index(this)] ){
$(this).addClass("init");
$(this).val( initVals[$("form input").index(this)] );
};
} );
Don't forget to use hasClass("init") or similar to avoid sending inputs with its default value.
I’m not sure whether the problem I’m having is with JavaScript or with PHP.
My objective: To validate a simple yes no form using JavaScript then process it via PHP and have a message displayed.
My problem: When JavaScript is enabled and I click the radio button and submit it the PHP doesn’t output “YES status checked”. Instead it refreshes the page (ie. I think it simply posts the form to user_agreement4.php and does nothing else) When JavaScript is disabled and I click on the YES radio button and submit it, the message “YES status checked” displays correctly. Please note that the code below is for user_agreement4.php. The form will be submitted to itself.
What am I doing wrong?
Please note that this is unfinished code-I haven't added things like cookies, redirection etc. yet.
Also I have a question about choosing answers. May I choose more than one reply as an answer?
<?php
// Set variables
$selected_radio = 'test';
session_start(); // start up your PHP session!
// The below code ensures that $dest should always have a value.
if(isset($_SESSION['dest'])){
$dest = $_SESSION['dest'];
}
// Get the user's ultimate destination
if(isset($_GET['dest'])){
$_SESSION['dest'] = $_GET['dest']; // original code was $dest = $_GET['dest'];
$dest = $_SESSION['dest']; // new code
}
else {
echo "Nothing to see here Gringo."; //Notification that $dest was not set at this time (although it may retain it's previous set value)
}
// Show the terms and conditions page
//check for cookie
if(isset($_COOKIE['lastVisit'])){
/*
Add redirect >>>> header("Location: http://www.mywebsite.com/".$dest); <<This comment code will redirect page
*/
echo "aloha amigo the cookie is seto!";
}
else {
echo "No cookies for you";
}
//Checks to see if the form was sent
if (isset($_POST['submitit'])) {
//Checks that a radio button has been selected
if (isset($_POST['myradiobutton'])) {
$selected_radio = $_POST['myradiobutton'];
//If No has been selected the user is redirected to the front page. Add code later
if ($selected_radio == 'NO') {
echo "NO status checked";
}
//If Yes has been selected a cookie is set and then the user is redirected to the downloads page. Add cookie code later
else if ($selected_radio == 'YES') {
echo "YES status checked";
// header("Location: http://www.mywebsite.com/".$dest);
}
}
}
?>
<HTML>
<HEAD>
<TITLE>User Agreement</TITLE>
<script language="javascript">
function valbutton(thisform) {
// validate myradiobuttons
myOption = -1;
for (i=thisform.myradiobutton.length-1; i > -1; i--) {
if (thisform.myradiobutton[i].checked) {
myOption = i;
}
}
if (myOption == -1) {
alert("You must choose either YES or NO");
return false;
}
if (myOption == 0) {
alert("You must agree to the agreement to download");
return false;
}
thisform.submit(); // this line submits the form after validation
}
</script>
</HEAD>
<BODY>
<H1> User Agreement </H1>
<P>Before downloading you must agree to be bound by the following terms and conditions;</P>
<form name="myform" METHOD ="POST" ACTION ="user_agreement4.php">
<input type="radio" value="NO" name="myradiobutton" />NO<br />
<input type="radio" value="YES" name="myradiobutton" />YES<br />
<input type="submit" name="submitit" onclick="valbutton(myform);return false;" value="ANSWER" />
</form>
</BODY>
</HTML>
See this line:
if (isset($_POST['submitit'])) {
If the user presses the submitit button, and javascript is disabled, everything works as expected - the button inserts its name/value pair into the posted data right before the form gets posted, so $_POST['submitit'] is set.
If, however, javascript is enabled, the button doesn't trigger a postback itself, instead it calls a javascript function which posts the form. Unfortunately though, when you call form.submit(), it won't go looking for buttons and add their name/value pairs to the posted data (for various reasons). So you need to find a different way of telling whether you are processing a post-back; the easiest way is to just put a hidden field into your form and check for that, e.g.:
(in the HTML part, somewhere inside the <form></form>):
<input type="hidden" name="is_postback" value="1" />
...and then change your PHP check to:
if ($_POST['is_postback'] == '1')
Change your javascript to:
function valbutton(thisform) {
// validate myradiobuttons
myOption = -1;
for (i=thisform.myradiobutton.length-1; i > -1; i--) {
if (thisform.myradiobutton[i].checked) {
myOption = i;
}
}
if (myOption == -1) {
alert("You must choose either YES or NO");
return false;
}
if (myOption == 0) {
alert("You must agree to the agreement to download");
return false;
}
return true; // this line enables the form to submit as normal and is not actually required
}
And remove the "return false;" from the on click event of the button. Having the validation function return false on validation fail is sufficient to stop the from from validating.
This should enable your php to work as is.