how can I check if the user filled some textboxes upon submit? My textboxes have different id and name.
If the user did not fill the required like password the form is not continued.
Thank you.
You can do this using JavaScript or within the script itself.
If using javascript, you simply check the form fields against your requirements before allowing the form to submit. However, you may still need to implement this in the script in case ofr some reason they have javascript turned off.
Basically, in the script, you check the values of the form when they submit:
if($_GET['field_name']) !== 'the value I expect') {
// show the form again with errors
}
// continue
Hope that helps.
Try the below. Naturally you can tweak the form and id's and such, but the basic principle should work. also shown here: http://jsfiddle.net/j3nSB/2/
<form>
<input type="text" id="username" value=""/>
<input type="password" id="password" value="" />
<input type="submit" id="submitButt" value="Go" />
</form>
document.getElementById("submitButt").onclick = function () {
if(document.getElementById("username").value.length == 0 |document.getElementById("password").value.length == 0) {
return false;
}
}
Assuming you have one form, here is the most simple/generic way I can think of, using plain JavaScript.
<script type="text/javascript">
var arrRequiredFields = [ "txtPassword", "txtEmail" ];
window.onload = function() {
document.forms[0].onsubmit = function() {
for (var i = 0; i < arrRequiredFields.length; i++) {
var field = document.forms[0].elements[arrRequiredFields[i]];
if (field && field.value.length == 0) {
alert("Missing required value");
field.focus();
return false;
}
}
return true;
};
};
</script>
Just put the names (not ID) of the required elements, put the code in your page and you're all set.
Live test case: http://jsfiddle.net/kf7pL/
use this:
http://bassistance.de/jquery-plugins/jquery-plugin-validation/
Its very easy to use, and you can just add a class of 'required' to each required input field.
its as easy as $('#form').validate();
It also supports things like integer and date. Highly recommend it to anyone
Related
I have the following code to check for form data and I can't figure out why its not working.
<script type="text/javascript">
function checkStuff() {
// By default, we plan to submit the form.
var formOkay = 1;
// Check to see if field_1 has a value. If not, we note that by changing our variable.
if(document.getElementById('requestorfirstname').value == '')
formOkay = 0;
// Let the user know something is wrong somehow. An alert is easiest.
alert('Requestor Name Required!');
// If you return true the form will submit. If you return false it will not.
if(formOkay == 1) {
return true;
} else {
return false;
}
}
</script>
Now here is the html form piece its checking onsubmit.
<input type="text" name="requestorfirstname" />
Thanks for the help!
document.getElementById looks for elements by ID. Your field doesn't have an ID, it has a NAME.
document.getElementById selects an element by id, not by name.
Some ways to solve the problem:
Add id="requestorfirstname" to the input element.
Use document.getElementsByName('requestorfirstname')[0]. getElementsByName returns a list, hence [0].
Use the document.querySelector('[name="requestorfirstname"]') method.
Get a reference to the form, and access the element using the .elements collection.For example, if your page has only one form:
document.forms[0].elements['requestorfirstname']
A name attribute on an HTML element is NOT the same as an id. You have no id on your input field, so there's no way for getElementById to find it. Change the element to:
<input type="text" name="requestorfirstname" id="requestorfirstname" />
^^^^^^^^^^^^^^^^^^^^^^^^ - add this
How can I check a input field exists in the form when I submit it to the server?
For instance, I want to check whether a check box named 'mem_follow' exists or not in the form.
Or do I have to use javascript (jquery)?
I'm guessing you need to check on the server side after the form is submitted. If that's the case, you can check like so...
<?php
if (isset($_POST['mem_follow']))
{
// Work your server side magic here
} else {
// The field was not present, so react accordingly
}
?>
Hope this helps!
It'd HAVE to be Javascript. PHP can't reach out from the server into the browser's guts and check for you. It could only check if the fieldname is present in the submitted data.
In jquery it's trivial:
if ($('input[name="nameoffield"]')) { ... field exists ... }
Of course, this raises the question... why do you need to know if a field exists or not? Presumably you're the one who's built the form. You should know already if the field exists or not.
In the following script the form will not submit unless the checkbox is ticked. And If you do try, the hidden div with an error message is shown, to let you know why.
<form action="test.php" method="post" id="myform">
<input type="checkbox" name="checkbox" id="checkbox" value="YES" />
<input type="submit" name="submit" value="submit" />
</form>
<div id="error_message_div" style="display:none">You must tick the checkbox</div>
<script>
$('#myform').submit(function() {
if($('#checkbox').attr('checked')) {
return true;
} else {
$("#error_message_div").show();
return false;
}
});
</script>
Cheers
Matt
you can do this in two way:
By Server Side: In php
<?php
if (isset($_POST['mem_follow'])
{
// Work your server side magic here
} else {
// The field was not present, so react accordingly
}
?>
By Client side: In Jquery
$('#submit_button').click(function() {
if ($('input[name="box_name"]')) {
if($('input[name="box_name"]').attr('checked')) {
return true;
} else {
return false;
}
}
});
You can use jQuery and do something like this:
$('#myForm').submit(function (e) {
if($(this).children(':checkbox[name=mem_follow]').length > 0)
//exists
else
//doesn't exist
});
Or use php and check if there is any variable named 'mem_follow': (this is for POST, although it doesn't matter if it's GET or POST)
if(isset($_POST['mem_follow']))
//exists
else
//doesn't exist
You can try this code in the form submit event handler
if($("input[name=mem_follow]").length > 0){
//It exists
}
The other answers here are correct: you'd have to do that on the client side. In the case of a checkbox input field, if the box is not checked there is no guarantee the browser will include a POST parameter for that field.
For example, if you submit this form without checking the checkbox:
<form action="test.php" method="post">
<input type="checkbox" name="checkbox" value="YES" />
<input type="submit" name="submit" value="submit" />
</form>
only the submit=submit parameter will be submitted.
So, no, you cannot guarantee that a given checkbox exists in a form on the server side.
well for all elements try this
number = document.form_name.elements.length;
else for a specific name of input use this
number = document.form_name.getElementsBYName('Name of Input').length;
Thats it
enjoy
I suggest you to use Jquery
$.fn.Exists = function() {
return $(this).length>0;
}
if ($("here are your selector to check").Exists()) {
...
}
Simple and useful!
And you can use this Exists method everywhere))))
You can use javascript (or jQuery) to do that :
<script>
$('#myform').submit(function() {
if($('#yourFieldId').val()=='') {
alert('the field ' + $('#yourformField').name() + ' is empty !');
return false;
} else {
return true;
}
});
</script>
you can do this for all your fields one by one, or by putting all conditions in the if statement.
I've referred to this post:
Post array of multiple checkbox values
And this jQuery forum post:
http://forum.jquery.com/topic/checkbox-names-aggregate-as-array-in-a-hidden-input-value
I am trying to collect an array (or concatenated string with commas, whatever) of checkbox values in a hidden input field using jQuery. Here's the script code I'm using:
<script type="text/javascript">
$("#advancedSearchForm").submit(function() {
var form = this;
$(form).find("input[name=specialty]").val(function() {
return $("input:checkbox",form).map(function() {
return $(this).attr("name");
}).get().join();
});
});
</script>
A snippet of the relevant HTML:
<form id="advancedSearchForm" name="advancedSearchForm" method="post" action="<?php echo site_url('/magcm/advancedSearch#results'); ?>">
<input type="checkbox" name="FCM" id="FCM" class="chk" value="FCM" <?php echo set_checkbox('FCM', 'FCM'); ?>/>
<input type="hidden" name="specialty" id="specialty" value="" />
<input class="button" name="submit3" id="submit3" type="submit" value="Search" />
I've tried changing "submit" to "submit3" in the jQuery, which breaks (obviously). When I print_r($_POST), the checkboxes POST correctly but the condensed hidden variable does not. (It posts, but a blank value.) The checkboxes persist correctly using CI's hacked set_value() function (Derek needs to implement this in the main trunk... but that's another story)
I'm sure I'm doing something that is wrong and easy to point out. I've just been banging my head against the wall for the past 2 hours on it, trying various functions and changing a ton of things and analyzing it in Chrome dev tools (which don't show any errors).
Help is appreciated. :)
Let's say you applied an class, maybe "tehAwesomeCheckboxen" to every checkbox. Then
<script>
$("#advancedSearchForm").submit(function() {
var chkbxValues = $(".tehAwesomeCheckboxen").val();
$("#specialty").val( chkbxValues.join(",") );
});
</script>
EDIT:
I don't think the $_POST array is getting populated, since the submit is being handled locally by the JavaScript engine. SO... let's try this:
<script>
var chkbxValues = new Array();
$(".tehAwesomeCheckboxen").live("change", function(e){
var val = $(this).val();
if( $(this).is(":checked") ) {
if( chkbxValues.length == 0 || chkbxValues.indexOf(val) == -1){
// Add the value
chkbxValues.push(val);
}
}
else {
// remove the value
chkbxValues.splice( chkbxValues.indexOf(val), 1 );
}
$("#specialty").val( chkbxValues.join(",") );
});
</script>
This adds an event handler the checkboxes themselves, such that checking/unchecking the box alters the hidden element. Then your form handles its submission as normal.
Is this more in line with what you're trying to do?
P.S. Those who upvoted this, please note I have modified my answer. Please verify whether you still find it useful and adjust your vote accordingly.
I ended up solving it using PHP arrays rather than jQuery:
<input type="checkbox" name="chk[]" id="RET" class="chk" value="RET" <?php echo set_checkbox('chk', 'RET'); ?>/>
I changed the name to an array and POSTed it to my script, where I looped through the array and handled it there. Still not sure what the problem was with the jQuery-based solutions, but I figured I'd post this for everyone to refer to in the future.
You've got lots of nested functions() in your JavaScript, makes it hard to follow what you're doing.
However, it seems that you're just passing a function to .val() rather than an actual value. Try this instead:
<script type="text/javascript">
$("#advancedSearchForm").submit(function() {
var form = this;
$(form).find("input[name=specialty]").val((function() {
return $("input:checkbox",form).map(function() {
return $(this).attr("name");
}).get().join();
})());
});
</script>
Or even better, calculate the value first:
<script type="text/javascript">
$("#advancedSearchForm").submit(function() {
var form = this;
var value = $("input:checkbox",form).map(function() {
return $(this).attr("name");
}).get().join();
$(form).find("input[name=specialty]").val(value);
});
</script>
I'm trying to implement a page with a choice of user's preferences in an HTML form where if the checkbox ALL is selected then all sub-checkbox base1, base2 and base3 are checked automatically, and if any of sub-checkboxes is un-selected then the checkbox ALL must be unchecked. I used a javascript function which works but when I submit the form only the last variable in the array of checkboxes is sent.
<SCRIPT LANGUAGE="JavaScript">
function checkChoice(field, i) {
if (i == 0) { // "All" checkbox selected.
if(field[0].checked==true) {
for (i = 1; i < field.length; i++)
field[i].checked = true;
}
}
else {
if (field[i].checked == false) {
field[0].checked = false;
}
}
}
<form name="form" method = "POST" action="preferences.php">
<input type=checkbox name=classes1 value="allbases" onclick="checkChoice(document.form.classes1, 0)">All bases
</td><td>
<input type=checkbox name=classes1 value="base1" onclick="checkChoice(document.form.classes1, 1)">Base1
<br>
<input type=checkbox name=classes1 value="base2" onclick="checkChoice(document.form.classes1, 2)">Base2
<br>
<input type=checkbox name=classes1 value="base3" onclick="checkChoice(document.form.classes1, 3)">Base3
<input type="submit" value="Set preferences" >
If I call the checkboxes'names in "classes1[]" all the values are submited but the javascript function doesn't work anymore. Is there a way of fixing this?
Thanks for any help.
For an alternative of checkChoice: check this SO question and the jsfiddle I presented there.
[edit] concerning your comment: a bit of extra thinking would have brought you to this solution
All of the values actually ARE submitted but PHP will overwrite $_POST['classes1'] each time until you are just left with the last value. If however you add '[]' to your input names then they are added to an array.
Since the latter causes a problem with javascript, can you not just either
a) iterate all of the form elements from the form.elements array,
or b) give each input a unique id and use document.getElementById() to find it?
how can i prevent a form to be submitted when it only contains a space? for example a user presses the space bar on a field, the space will be considered as a character so the forms submits. how can i prevent that in php?
For PHP - Server-side validation (After the form is submitted)
A combination of trim() and empty() will return true if passed a string with only a space.
$a = ' ';
$a = trim($a);
if (empty($a)) print 'Empty!'; // Empty!
Sidenote: Under normal circumstances, it's always a good idea to trim() user-input.
For Javascript - Client-side validation (Before the form is submitted)
Use the onSubmit event to fire a validate function:
<form onSubmit="validate()">
<input type="text" id="myInput" />
<input type="submit" value="submit" />
</form>
<script type="text/javascript">
function validate() {
myInput = document.getElementById('myInput');
if (myInput.value.match(/^s+$/) || myInput.value == '') {
alert('No Empty Values!');
return false;
}
}
</script>
Use trim() and then test against null values.
Mike B presents a good point. You could prevent the form from actually being submitted with Javascript. If you rely on PHP, the form will be submitted, but you could present the same form to the user with an error message.
HTML:
<form onsubmit="return validate(this);">
Javascript:
function validate(form) {
ok = true;
for (var i = 0, il = form.elements.length; i < il; ++i) {
form.elements[i].value = form.elements[i].value
.replace(/^\s\s*/, '')
.replace(/\s\s*$/, '');
ok &= !!form.elements[i].value;
}
if (!ok) alert("Oh hey - type something in these boxes, k?");
return ok;
}
PHP:
$myVar = trim($_POST['myFormVariable']);
if (!$myVar) {
echo "Oh hey, you should type something.";
} else {
doStuff();
}
Once your forms get more complex Jquery has a wonderful plugin for this called validate that provides extensive form validation.
+1 to Plan B. Always validate the same input again in php as there is nothing stopping a user from just creating his own form and submitting it to your page.