I need to validate a form with jQuery. I can check whether my form is empty or not.In my form i can have input elements of different types: Textarea, Radio button etc
And i have save button
form can't submit with empty values.but if any one of textarea or anyone of check box is checked (not compulsory to check all values and fill all text area but form can't be empty)
Very new to jquery and its very complicated for me :( I tried
function checkValues() {
if ($.trim($(this).val()) == '') {
alert('not okay');
return false;
} else {
alert('okay');
}
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button type="submit" name="save" value="Open" onClick="checkValues()" class="btn btn-primary">Save</button>
Any help would be appreciated.
I suggest you use the form's submit event:
Here is testing empty - it will allow submission if ANYTHING is filled/checked/selected
$("#form1").on("submit", function(e) {
var empty = true;
$(":input").each(function() { // all types of form fields
if (this.type.indexOf("text") == 0 || this.type == "password") { // text, textarea and password
empty = $.trim(this.value) == "";
if (!empty) return false; // leave the each
} else if (this.type.indexOf("select") == 0) { // select-one/multiple
empty = this.value == "";
if (!empty) return false; // leave the each
} else if (this.type == "checkbox") {
empty = !this.checked
if (!empty) return false; // leave the each
}
});
// radios are a special case
if (empty) { // only bother testing if nothing is filled
var $radios = $("[type=radio]",this); // all radios in the form
if ($radios.length > 0) { // any radios?
empty = $("[type=radio]:checked", this).length==0; // any checked?
}
}
if (empty) {
console.log("All fields are empty")
e.preventDefault(); // cancels the submission
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form id="form1">
<input type="text" value="" /><br/>
<textarea></textarea><br/>
<label>OK? <input type="checkbox" value="OK"/></label><br/>
<label>Yes <input type="radio" name="rad" value="yes"/></label>
<label>No <input type="radio" name="rad" value="no"/><br/></label>
<select>
<option value="">Please select</option>
<option>1</option>
<option>2</option>
<option>3</option>
</select><br/>
<input type="submit" />
</form>
Alternatively try this, which is counting filled values instead
$("#form1").on("submit", function(e) {
var values = [],
val = "";
$(":input").each(function() { // all types of form fields
if (this.type.indexOf("text") == 0 || this.type == "password") { // text, textarea and password
val = $.trim(this.value);
if (val !== "") values.push(val);
} else if (this.type.indexOf("select") == 0) { // select-one/multiple
if (this.value !== "") values.push(this.value);
} else if (this.type == "checkbox") {
if (this.checked) values.push(this.value);
}
});
var $radios = $("[type=radio]", this); // all radios in the form
if ($radios.length > 0) { // any radios?
var $checked = $("[type=radio]:checked", this);
if ($checked.length > 0) { // any checked?
$checked.each(function() { values.push(this.value); })
}
}
if (values.length > 0) {
console.log(values);
e.preventDefault(); // cancels the submission
} else {
console.log("All fields are empty")
e.preventDefault(); // cancels the submission
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form id="form1">
<input type="text" value="" /><br/>
<textarea></textarea><br/>
<label>OK? <input type="checkbox" value="OK"/></label><br/>
<label>Yes <input type="radio" name="really" value="yes"/></label>
<label>No <input type="radio" name="really" value="no"/><br/></label>
<select>
<option value="">Please select</option>
<option>1</option>
<option>2</option>
<option>3</option>
</select><br/>
<label>Left <input type="radio" name="direction" value="left"/></label>
<label>Right <input type="radio" name="direction" value="right"/><br/></label>
<input type="submit" />
</form>
here is example how you can have checks for textarea, checkbox and textbox.
try this.
function checkValues() {
if ($("#textarea1").val()) {
console.log("text area has value")
} else {
console.log("text area doesn't have value")
}
if ($("#checkbox1").prop("checked")) {
console.log("chack box is checked")
} else {
console.log("chack box is not checked")
}
if ($("#text1").val()) {
console.log("text box has value")
} else {
console.log("text box doesn't have value")
}
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<textarea id="textarea1" cols=20 rows=10></textarea>
<br/>
<input type="checkbox" id="checkbox1" value="chk_val" /> check me
<br/>
<input type="text" id="text1" placeholder="enter something" />
<br/>
<button type="submit" name="save" value="Open" onClick="checkValues()" class="btn btn-primary">Save</button>
Get your textarea value val() function pass field's id (i have used as txt)
for radio button $('radio button id').is(':checked') will give you true or false.
Try with the following code if it helps
function checkValues()
{
var textarea = $('#txt').val();
var isChecked = $('#rdSelect').is(':checked');
if(textarea == "")
{
alert ("textarea required");
}
if(isChecked == "false")
{
alert ("radio button should be checked");
}
}
Related
I have a form with the action set to "/resutls". But i have a txt input and i want to check if that is not empty to redirect to another location than "/results". Is this possible?
Code example as below:
<form id="results" action="/results" method="get">
<select id="country" name="country">
....
</select>
<input type="text" name="id">
<input type="submit" class="form-submit" value="Apply Search" name="submit">
</form>
Any ideas? Can this be done with jquery?
Sure you can do that in the submit handler. Warning: I wouldn't give a form control a name of id. It does cause confusion: if this refers to the form, should this.id refer to the id of the form or the text field with name="id"?
if( !!this.somefield.value ) { //did not want to write this.id.value !!!!
this.action = '/other-url';
} else {
this.action = '/results';
}
$(function() {
$('#results').on('submit', function(e) {
e.preventDefault(); // just so we can see that form action changes
if( !!this.somefield.value ) {
this.action = '/other-url';
} else {
this.action = '/results';
}
alert( this.action );
//$(this)[0].submit(); //now submit the form
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form id="results" action="/results" method="get">
<select id="country" name="country">
</select>
<input type="text" name="somefield">
<input type="submit" class="form-submit" value="Apply Search" name="submit">
</form>
Yes it is possible. Just set the form element's action property using jQuery .prop().
As a simple example:
var valid = false;
// go though validation here
if (false === valid) {
$('#results').prop('action', '/some/url/to/redirect/to');
}
HTML5 provides the "required" attribute wich will prevent the form for being posted, use it like this
<input type="text" name="id" required="required">
or, if you prefer to redirect to other page instead, you can do this
<script src="js/jquery-1.11.1.min.js" type="text/javascript"></script>
<script>
$("#results").submit(function (e){
e.preventDefault();
if($("#results input[name='id']").length < 1){
window.location.href = "your detiny url";
}
else{
this.submit();
}
});
</script>
I'm having two pages with similar textboxes when user inserts data into first page and goes to next page, if he need to give same data am adding a checkbox, when user clicks it same data which is in session from before page has to be get into the second page variables through ajax. can someone help me please. thanks
Response for the Comment
I made sample code which will give you idea about how to can do this.
jQuery Code for checkbox change event
$(function(){
$('input:checkbox').change(function(){
if($(this).is(':checked'))
{
$.ajax({
url : 'script.php',
success : function(session)
{
$('input:text').val(session);
}
});
}
});
});
HTML
<input type="text" />
<input type="checkbox" />
script.php
<?php
session_start();
echo $_SESSION['name_of_the_session_variable'];
exit;
?>
EDIT
$("#checked").click(function()
{
if ($(this).is(':checked'))
{
$('#provisional_total_public_funding').val(<?php echo empty($this->session->store['actual_info']['actual_total_public_funding']) ? '' : $this->session->store['actual_info']['actual_total_public_funding']; ?>);
}
});
Ajax Request Response
<select name="fin_year" id="fin_year">
<option value="" >Please select an year</option>
<option value="<?= $actFinYr; ?>"><?= $actFinYr; ?></option>
</select>
<script type="text/javascript">
$(function(){
$('#fin_year').change(function()
{
var options = $(this);
if(options.val() != '')
{
$.ajax(
{
url : 'CODEIGNITER_HTTP_URL/'+options.val(),
beforeSend : function()
{
//show loading
},
success : function(response)
{
//play with the response from server.
}
});
}
});
});
</script>
I'd use jQuery like this:
HTML 1st page:
input1 <input type="text" id="input1" name="input1"/>
input2 <input type="text" id="input2" name="input2"/>
jQuery 1st page:
$input1 = $("#input1");
$input2 = $("#input2");
$input1.keydown(function(){
$.post("yourPHP.php", {input1: $input1.val()});
});
$input2.keydown(function(){
$.post("yourPHP.php", {input1: $input1.val()});
});
PHP 1st page:
if(session_id() == '') {
session_start();
}
if(isset($_POST['input1'])){
$_SESSION['input1'] = $_POST['input1'];
}
if(isset($_POST['input2'])){
$_SESSION['input2'] = $_POST['input2'];
}
HTML 2nd page:
input1 <input type="text" id="input1" name="input1"/>
input2 <input type="text" id="input2" name="input2"/>
<br/>
radio1 <input type="radio" id="radio1" name="radio"/>
radio2 <input type="radio" id="radio2" name="radio"/>
jQuery second page:
$input1 = $("#input1");
$input2 = $("#input2");
$radio1 = $("#radio1");
$radio2 = $("#radio2");
$radio.click(function(){
$.post("yourPHP.php", {request: "input1"}, function(data){
$input1.val(data);
});
});
$input2.keydown(function(){
$.post("yourPHP.php", {request: "input2"}, function(data){
$input2.val(data);
});
});
PHP 2nd page:
if(session_id() == '') {
session_start();
}
if(isset($_POST['request'])){
switch($POST['request']){
case 'input1':
echo $_SESSION['input1'];
break;
case 'input2':
echo $_SESSION['input2'];
break;
}
}
I hope it works.
I want to hide and show input field on radio button click event my HTML is
<input type="radio" id="abc" name="abc1" checked = "checked" value="Experienced" />
<label> Experienced </label>
<input type="radio" id="xyz" name="xyz1" checked = "checked" value="Fresher" />
<label>Fresher</label>
<input type="text" name="cardno" id="tyx" /><br />
<p > Number</p>
What I want is when radio button with value="Fresher" is clicked the input box name="cardno" should be hidden.
I tried to solve this by using jQuery but it is not working.
$(document).ready(function () {
$("input[name$='abc1']").click(function () {
var value = $(this).val();
if (value == 'Experianced') {
$("#tyx").show();
} else if (value == 'Fresher') {
$("#tyx").hide();
}
});
Can any body help me how to solve this?
name of your radio button should be same to check on click event or make array name of your radio button
like below code
<input type="radio" id="abc" name="abc1" checked = "checked" value="Experienced" />
<label> Experienced </label>
<input type="radio" id="xyz" name="abc1" checked = "checked" value="Fresher" />
<label>Fresher</label>
<input type="text" name="cardno" id="tyx" /><br />
<p > Number</p>
and then create function like
$(document).ready(function () {
$("input[name$='abc1']").click(function () {
var value = $(this).val();
if (value == 'Experianced') {
$("#tyx").show();
} else if (value == 'Fresher') {
$("#tyx").hide();
}
});
please reply if i can help you more..
change the spelling to Experienced
you used
if (value == 'Experianced')
Besides the typo in Experienced, try setting up a click event for each radio button:
$(document).ready(function() {
$('input[name="abc1"][value="Experienced"]').click(function() {
$("#tyx").show();
});
$('input[name="xyz1"][value="Fresher"]').click(function() {
$("#tyx").hide();
});
});
Note:
You can simplify your selectors to use ids with:
$('#abc')
and
$('#xyz')
Fix with:
$(document).ready(function () {
$("input[type='radio']").click(function () {
var value = $(this).val();
if (value == 'Experianced') {
$("#tyx").show();
} else if (value == 'Fresher') {
$("#tyx").hide();
}
});
});
Html:
<input type="radio" id="abc" name="jobtype" checked = "checked" value="Experienced" />
<label> Experienced </label>
<input type="radio" id="xyz" name="jobtype" checked = "checked" value="Fresher" />
<label>Fresher</label>
<input type="text" name="cardno" id="tyx" /><br />
<p > Number</p>
Radio buttons of same group should have same name
Js:
$(document).ready(function () {
$("input[name='jobtype']").click(function () {
var value = this.value;
if (value == 'Experienced') {
$("#tyx").show();
}
else{
$("#tyx").hide();
}
});
});
I have a simple focus / blur. 'Name of Venue' is shown by default since it's the value of the input type. on 'focus' it hides and on 'blur' is shows again if there's no text.
Here's the input field
<input type="text" name="name" id="search_name" value="Name of Venue" maxlength="100" />
Here's the jQuery
$('#search_name').focus(function() {
if($(this).val() == 'Name of Venue') {
$(this).val('');
}
});
$('#search_name').blur(function() {
if($(this).val() == '') {
$(this).val('Name of Venue');
}
});
On submit I don't want 'Name of Venue' to be stored as the get variable for $_GET['name']. So, I'm doing <br /><br /> PHP
if($_GET['name'] === 'Name of Venue') {
$_GET['name'] = '';
}
But, this doesn't work. How can I make it so the get variable will be empty on submit if it's the default value?
Consider using the HTML5 placeholder attribute if possible. The value will be blank if nothing was entered.
<input type="text" name="search_name" id="search_name" placeholder="Name of Venue" maxlength="100" />
It will appear/disappear automatically, so you won't need the focus/blur code. Also, "name" is a bad name for name, I'd use something more unique (usually the id will do).
As an alternative, you could do this:
<form id="myform" method="get" action="">
<input type="text" name="search_name" id="search_name" value="Name of Venue" maxlength="100" />
<input type="submit" id="submit_button" value="Submit" />
</form>
<script src="jquery-1.7.1.min.js"></script>
<script>
// ready() not need if <script> follows content, but best to put this in a .js file and link in <head>
$(document).ready(function() {
// Define once and you're good
var search_name = $('#search_name');
var submit_button = $('#submit_button');
var search_default = 'Name of Venue';
search_name.focus(function() {
if($(this).val() == search_default) {
$(this).val('');
}
});
search_name.blur(function() {
if($(this).val() == '') {
$(this).val(search_default);
}
});
$("#myform").submit(function(event) {
if (search_name.val() == '' || search_name.val() == search_default) {
event.preventDefault();
} else {
return true;
}
});
});
</script>
<?php
var_dump($_GET);
$name = '';
if (isset($_GET['search_name'])) {
// Without the check, we might run query when none exists
$name = $_GET['search_name'];
$name = $name != 'Name of Venue' ? $name : '';
}
var_dump($name);
?>
This will prevent a submit with a blank or default name. It's probably handy to put any repeated logic in a function and call those when handling the GET in PHP with any extra search variables.
You can control the value on client side and if it's a required field don't let the form to be submitted. If it's not required, just set the value to "" if it is "Name of Venue".
I think you have to make the field value blank before submitting the form if value is Name of Venue.
$('#frName').submit(function() { if($('#search_name').val() == 'Name of Venue' ){ $('#search_name').val('') } return false;});
You can remove return false if you want to submit the value. Hope its helps you
I want to alert user if they haven't checked any checkbox, and return to the form
After they checked at least one checkbox, proceed into the next page
How can I do that ?
<input type="checkbox" name="pay[]" value="
<?php
echo $DateArr[$record_count].";";
echo $invoiceArr[$record_count].";";
echo $TotalArr[$record_count].";";
echo $amount_dueArr[$record_count];
?>
" onClick="checkTotal()"/>
<td ALIGN="right" ><input type="submit" name="submit" value="Continue" onMouseOver="CheckBoxStatus()"></td>
javascript :
function CheckBoxStatus()
{
var checkbox_status = document.getElementsByName("pay[]").value;
if (checkbox_status = ";;;")
{
alert("Please select at least one to proceed!");
return false;
}
else
{
alert("Continue!");
return true;
}
}
If user hasn't checked, at least one checkbox, alert the message and return to form
Then
<form name="payform" method="POST" action="payment.php" onSubmit=" CheckBoxStatus()">
How can I stay in the form if user is not checking any checkboxes ?
May be like this :
function CheckBoxStatus()
{
if (document.getElementsByName("pay[]").checked == true)
{
document.forms["payform"].submit();
return true;
}
else
{
alert("Please select at least one invoice to proceed!");
document.forms["payform"].reset();
return false;
}
}
can i do like this :
`
function CheckBoxStatus()
{
var status=$("pay[]").attr('checked');
if (status=true)
{
//if(document.getElementsByName("pay[]").checked) {
return true;
}
else {
alert("Please select at least one to proceed!");
return false;
}
}`
With jQuery
var $checked = $("input:checked");
if($checked.length == 0) {
alert("Please select at least one to proceed!");
}
That HTML is a bit of a mess. A couple of things...
Get rid of the <td> tag containing the button. It doesn't look like it has a purpose.
To call the JavaScript you need to use onsubmit not onMouseOver.
To check if the checkbox is checked change your function to the following.
function checkBoxStatus {
if(document.getElementsByName("pay[]").checked) {
return true;
}
else {
alert("Please select at least one to proceed!");
return false;
}
}
EDIT; forgot the alert
Check if you have included jquery. :|
Try this:
<input id="ipay" type="checkbox" name="pay[]" value="
<?php
echo $DateArr[$record_count].";";
echo $invoiceArr[$record_count].";";
echo $TotalArr[$record_count].";";
echo $amount_dueArr[$record_count];
?>"
/>
<td ALIGN="right" ><input type="submit" name="submit" value="Continue"></td>
<form id="pform" name="payform" method="POST" action="payment.php">
Javascript:
$(document).ready(function() {
$('#pform').submit(function(e) {
var paycheck = $('#ipay').attr('checked');
if(paycheck != true or paycheck != 'checked') {
alert('Please check at least one option.');
e.preventDefault();
}
});
});
You can do something like this:
<html>
<head>
<title>Verify Checkbox</title>
<script type="text/javascript">
function verifyCheckboxSelected(form) {
var theForm = document.forms[form];
var valid = false;
for( var i=0; i < theForm.length; i++ ) {
if(theForm.elements[i].checked) {
valid = true;
}
}
if (!valid) {
alert('You must select at least one checkbox')
return false;
}
}
</script>
</head>
<body>
<form name="myForm" onSubmit="return verifyCheckboxSelected(this.name)">
<input type="checkbox" name="myCheckBoxes[]"/>Checkbox A</br>
<input type="checkbox" name="myCheckBoxes[]"/>Checkbox B</br>
<input type="checkbox" name="myCheckBoxes[]"/>Checkbox C</br>
<input type="submit" value="submit" />
</form>
</body>
</html>