Form validation causing wrong input in database from form field - javascript

I'm using a javascript that validates a form by radio buttons being checked, depending on which button is checked I want a value for that button submitted to MySQL but when I select a button it submits the button name to MySQL. changing the name of the button causes the script to stop working. How can I change the script so it allows the button value to post to MySQL instead of the button name?
jsFiddle
function ValidateForm(form) {
ErrorText = "";
if ((form.job_status[0].checked === false) && (form.job_status[1].checked === false)) {
alert("Before you can get a signature you must mark a selection.\n Is the work completed or do you need to return?");
return false;
}
if (ErrorText = "") {
form.submit();
}
}

job_status[0] ,job_status[1] means with name job_status two radio buttons exist.
If you change one of the radio buttons name either of job_status[0] job_status[1] one will exist.So you are getting exception
Instead of doing all that process by default select a radio button.That solves all your problems.I updated the link
see here

Related

validate error message not displaying for drop down list when not selected

Please bear with me as I am not sure what I have done wrong here:
Basically I have a form and I have some drop down lists.
If I hard code the select list for my drop down list with styleClass="requiredinpfield" then I will get a proper validation error message pops up below the select list whenever I don't select an option from the list and if I try hit submit button.
However, because some of the drop down lists are not always required (they only required when certain option was selected) so in this case I am not hard coding these select lists to have styleClass="requiredinpfield" but instead I am using jQuery to dynamically add the requiredinpfield class to the list object whenever an associate radio button was selected.
The problem I am having now is this won't show the validation error message when I don't select any option and try to hit the Submit button. It prevent me from continue, however. Its just I don't get to see the error message. Can you see what I have done wrong?
Here is an example of how I use jQuery to add the requiredinpfield class and it is not showing me the validation error message when needed:
HTML
<div id="fruitDivId">
<apex:inputField id="testPickList" value="{!PickTheFruitYouLike__c}" styleClass="selectpicker"/>
</div>
A radio button to confirm that the list is needed
<apex:selectRadio value="{!DoYouLikeFruit}" onchange="whenAnOptionWasSelectedAndINeedToAddRequiredInpField(this.value,'fruitDivId');" styleClass="requiredinpfield radio pa-cus pa-cus-other">
Script to add requiredinpfield class
function whenAnOptionWasSelectedAndINeedToAddRequiredInpField(t,divId)
{
if (t == 'Yes' ){
$('[id$='+divId+']').show();
$('[id$="testPickList"]').addClass('requiredinpfield');
}
else{
$('[id$='+divId+']').hide();
$('[id$="testPickList"]').removeClass('requiredinpfield');
}
}
Script to validate
Note: my submit button will trigger the !checkRequired() method.
function checkRequired(){
var isValidate = true;
//$('.errorIcon').css('opacity', '0');
$('.requiredinpfield').each(function(){
if($(this).is("select") && $(this).val() == ''){
/*alert("Hello!!");*/
if(!($(this).next('.requiredinpfield').first().next('.errorMsg').size()>0)){
console.log($(this).next('.requiredinpfield'));
$(this).next('.requiredinpfield').first().after('<div class="errorMsg"><strong></strong> You must select an option</div>');
}
isValidate = false;
}
else{
if($(this).is("select") && (($(this).next('.requiredinpfield').first().next('.errorMsg').size()>0)))
{
$(this).next('.requiredinpfield').first().next('.errorMsg').remove();
}
}
});
//alert(isValidate);
return isValidate;
}
Assuming that the rest of the code is correct, the problem might in the way you are selecting elements by ID
in jQuery, to select an element by id simply write
$('#idoftheelement')
so in your whenAnOptionWasSelectedAndINeedToAddRequiredInpField function,
try replacing
$('[id$='+divId+']')
with
$('#'+divId)
do the same at all locations where you are selecting by id.

How to assign value to unchecked checkboxes

I'm creating a form with multiple checkboxes and I want to value of the checked checkboxes to be "yes" and the value of unchecked checkboxes to be "no". The site I'm hosting my form on does not let me add the hidden field with the same name and a different value so I have to find script that will add the hidden checkbox on submission and include the value of "no". Currently, when I submit the form the unchecked boxes are recorded as undefined but for data purposes I need it to be filled with "no".
Here is what I found:
$(document).ready($("#foo").submit(
function() {
// Add an event listener on #foo submit action...
// For each unchecked checkbox on the form...
$(this).find($("input:checkbox:not(:checked)")).each(
// Create a hidden field with the same name as the checkbox and a value of 0
// You could just as easily use "off", "false", or whatever you want to get
// when the checkbox is empty.
function(index) {
var input = $('<input />');
input.attr('type', 'hidden');
input.attr('name', $(this).attr("name")); // Same name as the checkbox
input.attr('value', "no"); // or 'off', 'false', 'no', whatever
// append it to the form the checkbox is in just as it's being submitted
var form = $(this)[0].form;
$(form).append(input);
} // end function inside each()
); // end each() argument list
return true; // Don't abort the form submit
} // end function inside submit()
));
Why is the script not working?
You need to check out the jQuery API documents
$(document).ready(function(){}); it takes function callback, which may not needed here.
$("#foo").submittakes function callback, which will be called right before the form is submitted.
No need to wrap selector in $.find
You need to figure out the context of this
The this in $(this).attr("name") is referring the input box
The this in $(this)[0].form is still the input box
I guess you are trying to get the reference of forms. You may use document.forms
You need to change the input with $(this). Within the .each function $(this) will refer to the checkbox itself.
It isn't normal to have severals input with same name you can put the value directly in checkbox
$(this).find($("input:checkbox:not(:checked)")).each(function(){
$(this).val($(this).is(':checked') ? "yes" : "no")
})
I was able to use this much simpler script. Works perfectly.
$('#foo').click(function () {
$(this).find('input[type="checkbox"]').each( function () {
var checkbox = $(this);
if( checkbox.is(':checked')) {
checkbox.attr('value','yes');
} else {
checkbox.after().append(checkbox.clone().attr({type:'hidden', value:'no'}));
}
});
});

How to see if a form element was not posted

I have a form where e-mail is optional. To control that there is a checkbox. If that checkbox is unchecked, the e-mail textbox would be disabled and therefore not posted on submit. However, on the next page, if I have code like as shown below, it gives me an error if the e-mail textbox is disabled.
if (isset($_POST['submit']))
{
$_SESSION["email"] = $_REQUEST['YourEMail'];
....
}
To get around that problem, I progammatically enable a disabled e-mail textbox just before submitting besides setting its value to an empty string. The code for that is shown below.
document.getElementById('YourEMail').disabled = false
document.getElementById('YourEMail').value = ''
However, one annoying problem remains, which is that, if the user goes back to the original page, the e-mail textbox is enabled, since I enabled it problematically just before submitting the form. However, I want it to be disabled in that case. How, can I achieve that? Alternatively, how in the next page, I could see that e-mail box was disabled and therefore not even try to read $_REQUEST['YourEmail']?
if the field "#YourEMail" is optional you can check if exists in PHP. There is no need for enable/disable the field using JS.
if (isset($_POST['submit']))
{
if (isset($_REQUEST['YourEMail']) && !empty($_REQUEST['YourEMail'])){
$_SESSION["email"] = $_REQUEST['YourEMail'];
}
}
You can test it like this using a ternary:
(isset($_REQUEST['YourEMail']) && !empty($_REQUEST['YourEMail'])) ? $_SESSION["email"] = $_REQUEST['YourEMail'] : FALSE;
This would only set the session variable if the request variable is set.

How do I use jQuery to disable a form's submit button until every required field has been filled?

I have a form with multiple inputs, select boxes, and a textarea. I would like to have the submit button be disabled until all of the fields that I designate as required are filled with a value. And after they are all filled, should a field that WAS field get erased by the user, I would like the submit button to turn back to disabled again.
How can I accomplish this with jQuery?
Guess my first instinct would be to run a function whenever the user starts modifying any of the inputs. Something like this:
$('#submitBtn').prop('disabled', true);
$('.requiredInput').change(function() {
inspectAllInputFields();
});
We then would have a function that checks every input and if they're validated then enable the submit button...
function inspectAllInputFields(){
var count = 0;
$('.requiredInput').each(function(i){
if( $(this).val() === '') {
//show a warning?
count++;
}
if(count == 0){
$('#submitBtn').prop('disabled', false);
}else {
$('#submitBtn').prop('disabled', true);
}
});
}
You may also want to add a call to the inspect function on page-load that way if the input values are stored or your other code is populating the data it will still work correctly.
inspectAllInputFields();
Hope this helps,
~Matt
Here's something comprehensive, just because:
$(document).ready(function() {
$form = $('#formid'); // cache
$form.find(':input[type="submit"]').prop('disabled', true); // disable submit btn
$form.find(':input').change(function() { // monitor all inputs for changes
var disable = false;
$form.find(':input').not('[type="submit"]').each(function(i, el) { // test all inputs for values
if ($.trim(el.value) === '') {
disable = true; // disable submit if any of them are still blank
}
});
$form.find(':input[type="submit"]').prop('disabled', disable);
});
});
http://jsfiddle.net/mblase75/xtPhk/1/
Set the disabled attribute on the submit button. Like:
$('input:submit').attr('disabled', 'disabled');
And use the .change() event on your form fields.
Start with the button disabled (obviously). Bind an onkeyup event to each required text input, and an onchange or onclick to the select boxes (and any radio buttons/checkboxes), and when it fires, check whether all required inputs are filled. If so, enable the button. If not, disable it.
There is one loophole here, though. Users can delete the value of a text field without triggering the onkeyup event by using the mouse to "cut" the text out, or by holding down the delete/backspace key once they have deleted it all, and clicking the button before deleting it.
You can get around the second by either
disabling the button with onkeydown and checking if it is ok on onkeyup
checking for validity when the button is clicked
An idea from me:
Define a variable -with global scope- and add the value true- Write a submit function within your check the value above varibale. Evalue the the submit event only, if the value is true.
Write a function which ckecks all value from input fields and select fields. Checking the length of value to zero. if the value length of one field zero then change the value of the global variable to false.
After that, add to all input fields the event 'onKeydown' or 'onKeyUp' and to all select boxes the event 'onChange'.
I recommend taking a slightly different approach and using jquery's validation http://docs.jquery.com/Plugins/validation. The tactic you are suggesting is prone to security holes. The user could easily using firebug enable that button and then submit the form.
Using jquery validation is clean and it allows you to show error messages under the required fields if so desired on submit.

Trouble with executing code if checkbox is unchecked

I need to validate values of a form only if checkbox is unchecked. If it is checked, I will use values added previously. Now the thing is this or any of these code are not working. As I need to validate these values before I redirecting values to another form.
var ui=document.getElementById('same_info').value;
ui.OnChange = valid;
function valid()
{var frmvalidator = new Validator("myform");
frmvalidator.addValidation("shipping_first_name","alpha_s","please enter your First Name or full name");
frmvalidator.addValidation("shipping_first_name","req","Please enter your First Name");
}
2.
if(!document.myform.same_info.checked)
{ alert('infobox is not checked'); }
I am using Javascript to validate form. Script is fine as it is working perfectly with form elements , whose values are not depending on checking/unchecking of checkbox.
Change:
var ui=document.getElementById('same_info').value;
to
var ui=document.getElementById('same_info');
Also, I'm fairly certain it's onchange, not OnChange -- Javascript is case sensitive.
ui.onchange = valid;
Also note that if the user checks it, and unchecks it, it will still have those validation requirements even though it has been unchecked.

Categories