Trouble with executing code if checkbox is unchecked - javascript

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.

Related

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.

Form validation causing wrong input in database from form field

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

JS and jQuery - loop through textboxes and store value

Here's the function that checks if the form is complete.
So, what I'm trying to do:
If radio is not selected, throw a message.
If radio is "yes", but text is not entered, throw error.
If radio is "no" but text is entered, make the text empty.
If all is good, add stuff into `allResponses
The form was displayed 5 times, and input was as follows:
Yes a1
No
Yes a3
No
Yes
Now, this input should display an error since in 5th case, "yes" is selected but nothing is entered in the textbox.
However, I get this:
http://i.imgur.com/ya2CUp0.png
Also, the text is not being updated as in 1st and 3rd cases.
I don't know a lot about JS, so please provide me with as explained responses as you can.
EDIT: Complete code: http://pastebin.com/scNSNM2H
Thanks
You have this in a loop:
var exaggerationPart = document.getElementById('exaggeration').value
And then you check to make sure it has a value for each item. But you will get the same value each time.
You are creating multiple inputs with the same id, "exaggeration". This is invalid HTML. Id's must be unique. To correct this, you can increment the id the same as you are doing with other elements (such as, input[name='response"+thisJokeIndex+"']).
var exaggerationPart = document.getElementById('exaggeration' + thisJokeIndex).value
tipTD2.append("<input type='text' name='exaggeration' id='exaggeration" + tipIndex + "' size='70'>")
Working demo: jsfiddle.net/svvge/2
Edit: To clear the value of the text box, you must change the value property of the text box element. Right now you are just changing the value of a variable.
var exaggerationInput = document.getElementById('exaggeration' + thisJokeIndex).value;
var exaggerationPart = exaggerationInput.value;
exaggerationInput.value = '';

How can I tell if the checkboxes are checked?

I need to be able to tell if the checkboxes are checked to do some basic validation. Problem: I don't have access to the PHP generating this. There is no class added, or the basic checked=checked that most forms have. What's the easiest way to target the checked boxes?
http://www.inpresence.in/event-registration?ee=4
EDIT: freak out!! here's the code, i just need to target the checked boxes, everything else is working. the :checked method of jquery uses checked=checked within the checkbox, which isn't there.
$(document).ready(function(){
//when the submit button is clicked...
$("input.btn_event_form_submit").click(function(){
//find the value of the drop down with one evening or four evenings
var priceOption = $("#price_option-4").val();
//match a string ending with "one evening" as the first numbers will be randomly generated by php
var oneEvening = /^\d{2}\|One Evening$/.test(priceOption);
//match a string ending with "four evenings" as the first numbers will be randomly generated by php
var fourEvenings = /^\d{2}\|Four Evenings$/.test(priceOption);
//HOW DO I GET THE CHECKED BOXES?!
var checkedBoxCount = $('#dates-1351733097 .valid').is(':checked').length;
//if one evening is selected make sure the checked boxes count does in fact equal one
if(oneEvening && checkedBoxCount != 1){
//if it doesn't alert the user and return false
alert('You must select one date');
return false;
}
//if one evening isn't selected, four is. make sure the count does indeed in 4
else if (fourEvenings && checkedBoxCount != 4){
//if it doesnt alert the user and return to the form
alert('You must select four dates');
return false;
}
//else, everything checks out!
else {
return;
}
});
});
Using this JavaScript code you can check if a checkbox is checked:
var isChecked = document.getElementById("my-checkbox").checked;
Or using jQuery:
var isChecked = $('#my-checkbox').is(':checked');
EDIT: Try this and tell me if it works:
var checkedBoxCount = $('#dates-1351733097 .valid:checked').length;
Have you tried using jquery to resolve this?
http://jquery-howto.blogspot.co.uk/2008/12/how-to-check-if-checkbox-is-checked.html
$('#edit-checkbox-id').is(':checked');
use the jquery :checked selector. http://api.jquery.com/checked-selector/
This will give you a boolean in javascript of what you want:
document.getElementById("Nov.12-4_1").checked
You can view source and find the elements to view whatever id's they have.
Other answers: the OP didn't specify that he wanted a jquery answer. If he hasn't used jquery for anything up to this point. I think adding it just for this would be a tad overkill.

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.

Categories