How to restrict button unless text boxes have text - javascript

I am wanting to prevent my submit buttons from being selected untill the user has entered text into my text box feilds.. I have looked into Jquery but am not sure how to apply it to my situations.
if you look at the code below I have a table, this is a section where I can add values to a table in my BD I have 3 other different tables similar but not the same each with their own submit buttons i want to restrict also but off their own text boxes not the others from the different tables...
how could I achive this?
heres one of the tables I have created.
<table width="600">
<tr>
<td width="15%">
<b>name:</b>
<div class="qlabs_tooltip_bottom qlabs_tooltip_style_7">
<input type="text" name="5050gdproductname" />
<span>Enter Text </br>i.e. <i>Super Small</i></span>
</div>
</td>
<td width="15%">
<b>width:</b>
<div class="qlabs_tooltip_bottom qlabs_tooltip_style_7">
<input type="text" name="5050gdproductwidth" />
<span>Enter a Number </br>i.e. <i>1000</i></span>
</div>
</td>
<td width="15%">
<b>height:</b>
<div class="qlabs_tooltip_bottom qlabs_tooltip_style_7">
<input type="text" name="5050gdproductheight" />
<span>Enter a Number </br>i.e. <i>1000</i></span>
</div>
</td>
<td width="15%">
<b>normal fill:</b>
<div class="qlabs_tooltip_bottom qlabs_tooltip_style_7">
<input type="text" name="5050gdnormalfill" />
<span>Enter a Number </br>i.e. <i>1000</i></span>
</div>
</td>
<td width="15%">
<b>our fill:</b>
<div class="qlabs_tooltip_bottom qlabs_tooltip_style_7">
<input type="text" name="5050gdourfill" />
<span>Enter a Number </br>i.e. <i>1000</i></span>
</div>
</td>
<td width="15%">
<b>old price:</b>
<div class="qlabs_tooltip_bottom qlabs_tooltip_style_7">
<input type="text" name="5050gdoldprice" />
<span>Enter Dollar Amount </br>i.e. <i>150.99</i></br>no dollar sign requiered</span>
</div>
</td>
<td width="15%">
<b>new price:</b>
<div class="qlabs_tooltip_bottom qlabs_tooltip_style_7">
<input type="text" name="5050gdnewprice" />
<span>Enter Dollar Amount </br>i.e. <i>150.99</i></br>no dollar sign requiered</span>
</div>
</td>
<td>
</br><input type="submit" name="submit5050gd" value="Submit 5050gd" id="5050gdmyButton" />
</td>
</tr>
</table>
any help would be appreciated

Here is the fiddle link for your assistance:
http://jsfiddle.net/4JyLk/
handle in Button click event
If all text boxes are given values, proceed with submission else don't.
Use the link provided for live demo.
Note: You can edit this code, to disable/enable.

$('input[type=text]')​.keyup(function(){
if(($('input[name=5050gdproductname]').val()=="")||($('input[name=5050gdproductwidth]').val()=="")||($('input[name=5050gdproductheight]').val()=="")||($('input[name=5050gdnormalfill]').val()=="")||($('input[name=5050gdourfill]').val()=="")||($('input[name=5050gdoldprice]').val()=="")||($('input[name=5050gdnewprice]').val()==""))
{
$('input[name=submit5050gd]').attr('disabled', 'disabled');
}else{
$('input[name=submit5050gd]').removeAttr('disabled');
}
});​​​​
<input type="submit" name="submit5050gd" value="Submit 5050gd" id="5050gdmyButton" disabled="disabled"/>
jsFiddle

Try the following code
//On document load
$(function(){
//Set button disabled
$("input[type=submit]").attr("disabled", "disabled");
//Append a change event listener to you inputs
$('input').change(function(){
//Validate your form here, example:
var validated = true;
if($('#5050gdnormalfill').val().length === 0) validated = false;
//do validation for all field as above, add id field for every element
//If form is validated enable form
if(validated) $("input[type=submit]").removeAttr("disabled");
});
})

Lots of answers, all confusing to me. Far better to validate the form when it's sumbitted and don't do things like disable the submit button. If you want all the text inputs to have text, then:
function validate(form) {
var el, elements = form.elements;
for (var i=0, iLen=elements.length; i<iLen; i++) {
el = elements[i];
if (el.tagName.toLowerCase == 'input' && el.type == 'text') {
if (el.value == '') {
// Deal with error, e.g. show message
// Stop form submitting
return false;
}
}
}
}
And in the form:
<form ... onsubmit="return validate(this);" ...>
You can also put a listener for change or keyup events on every text input, then run the above code and disable the submit button, so instead of return false you'd do:
form.submit5050gd.disabled = true;
to disable the button or:
form.submit5050gd.disabled = false;
to enable it. But that's a bit tiresom and users tend to not understand disabled controls. Much better to just let them know they have to put something in each input and validate when they submit the form.

Do this.
<input type="submit" name="submit5050gd" value="Submit 5050gd" id="5050gdmyButton" disabled='disabled" />
On the last text box use the blur event of javascript to validate your condition.
Try this.
var isBlank = false;
$('input[type="text"]').blur(function(){
$("#YourTableID").find('input[type="text"]').each(function(){
if($(this).val() != ''){
isBlank = true;
return false;
}
});
if(!isBlank){
$('input[type="submit"]').removeAttr('disabled');
}
});

Related

Default OnChange Event JavaScript function to check input field is Number or Letter for all the input number fields

I have around 30 input fields which take a number as input. Is there any way to write a single default OnChange event JavaScript function for all the number input fields instead of writing 30 JavaScript functions to check whether the entered input is a number or text? and If the input is NaN I need to add the red colored border to that input field. Thank you. Sorry for not adding the code for the first time.
HTML Code
<tr>
<td>
Fund1:<input type="text" class="" name="FundAmount1" id="Fund1" onchange="ValidateIsNaN()" />
</td>
<td>
Fund2:<input type="text" class="" name="FundAmount2" id="Fund2" />
</td>
<td>
Fund3:<input type="text" class="" name="FundAmount3" id="Fund3"/>
</td>
<td>
Fund4:<input type="text" class="" name="FundAmount4" id="Fund4"/>
</td>
<td>
Fund5:<input type="text" class="" name="FundAmount5" id="Fund5" />
</td>
.
.
.
Total:<input type="text" class="" name="Total" id="TotalId" />
</tr>
JavaScript Code
<script type="text/javascript">
function ValidateIsNaN(){
var inputValue = document.getElementByName('Fund1').value;
if (isNaN(inputValue ))
{
$("Fund1").addClass("redColorBorderCSS");
alert("Enter number only")
return false;
}
}
</script>
You can certainly test for numbers in a lot of different ways.
Use the <input type="number"> HTML element
In your onChange event you can var result = parseInt(value, 10) or var result = parseFloat(value, 10) and test with isNaN(result)
You can write a regular expression to validate the input value /^[0-9]+$/ or /^[0-9]+(\.[0-9]+)?$/

How to get alert when checkboxes in the table are not clicked and try to submit form

I am trying to send checkbox values to other page to delete the selected rows with checkbox but when there is no checkbox clicked and try to send it should give alert for checkbox is empty and if the form is submitting after the checkbox is clicked then it should give alert whether to proceed or not this is my form
<form action="deleteselectedhr" name="deleteFiles" method="post" onsubmit="checkForm()">
<table id="mytable" border=3 >
<c:forEach items="${users}" var="user">
<tr>
<td>
<input type="checkbox" id="saif" name="<c:out value="${user.hrid}" />"
value="<c:out value="${user.hrid}" />" />
</td>
</tr>
</c:forEach>
</table>
<input TYPE="SUBMIT" value="Delete Selected HRs"/>
</form>
Javascript:
<script type="text/javascript">
function checkForm(){
var checkt = document.getElementsById('saif');
var chekSelect = false;
for (var i = 0; i < checkt.length; i++) {
var myElement = checkt[i];
if (myElement.type === "checkbox" && myElement.checked) {
if (myElement.checked) {
chekSelect = true;
break;
}
}
}
if(!chekSelect) {
alert('Please Check Atleast one record to print cheque!!!');
return false;
} else {
return true;
}
}
</script>`
Few things you can modify here like:
Add return to onsubmit like onsubmit="return checkForm()"
Use class instead of id like for this demo we have used class="item"
And finally use document.querySelector to get only checked checkbox.
DEMO:
function checkForm() {
if (document.querySelector('.item:checked')) {
alert('Checkbox is checked');
return true;
} else {
alert('Please Check Atleast one record to print cheque!!!');
return false;
}
}
<form action="deleteselectedhr" name="deleteFiles" method="post" onsubmit="return checkForm()">
<table id="mytable" border=1>
<tr>
<td>
<input type="checkbox" class="item" value="1" />
</td>
</tr>
<tr>
<td>
<input type="checkbox" class="item" value="2" />
</td>
</tr>
<tr>
<td>
<input type="checkbox" class="item" value="3" />
</td>
</tr>
</table>
<input TYPE="SUBMIT" value="Delete Selected HRs" />
</form>
function checkForm(e){
event.preventDefault()
var a = document.querySelectorAll('#saif');
if(a[0].checked || a[1].checked || a[2].checked == true){
alert('Checkbox checked')
}else{
alert('Please Check Atleast one record to print cheque!!!')
}
}
<form action="deleteselectedhr" name="deleteFiles" method="post" onsubmit="return checkForm()">
<table id="mytable" border=3 >
<tr>
<td>
<input type="checkbox" id="saif" value="1" /><br/>
<input type="checkbox" id="saif" value="2" /><br/>
<input type="checkbox" id="saif" value="3" />
</td>
</tr>
</table>
<input TYPE="SUBMIT" value="Delete Selected HRs"/>
</form>
I hope you are using a framework of any particular language.
In MVC structure, you can validate the presence of the checkbox.
For example, I am using Ruby on Rails and I have my checkbox field
<%= f.label :active %>
<%= f.check_box :active %>
I then validate the checkbox as
validates :active, presence: true
I can also print a flash message via my controller to show the error. Eg:-
flash.now[:danger] = 'Invalid email/password combination'

HTML checkbox validation breaks when there are multiple checkboxes in the form

In the form below, how to ignore the disabled checkbox. The expected behavior in the form is that if the user does not check the Model check box and click on the submit button, form should be submitted. If the Model checkbox is checked, user must enter data. This behavior works as long as there is no other checkbox on the page. If there is another checkbox, and the submit button is clicked without checking the Model checkbox, alert is thrown. How can I ignore the other checkboxes in the form to achieve the desired behavior? Thanks!
$(document).ready(function () {
$('#checkModelBtn').click(function() {
var isCheckboxChecked = $("input[type=checkbox]:checked").length;
var isTextEntered = $("input.childModel").val().length;
if ( isTextEntered || !isCheckboxChecked ) {
//alert("validation passed!");
} else {
alert("Please enter the Model Number");
}
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js"></script>
<table>
<tr>
<td>
<p><h2>MODEL:</h2></p>
<input type="checkbox"> Model #
<input type="text" size="12" class="childModel"><BR>
</td>
<td>
THIS CHECKBOX BREAKS THE FUNCTIONALITY<p>
<input type="checkbox" checked disabled> Some text here</td>
</tr>
</table>
<hr>
<input type="submit" name="submit" value="submit" id="checkModelBtn"/>
The checkbox needs to have a unique selector.
$(document).ready(function () {
$('#checkModelBtn').click(function() {
var isCheckboxChecked = $("input[name='model_number']:checked").length;
var isTextEntered = $("input.childModel").val().length;
if ( isTextEntered || !isCheckboxChecked ) {
//alert("validation passed!");
} else {
alert("Please enter the Model Number");
}
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js"></script>
<table>
<tr>
<td>
<p><h2>MODEL:</h2></p>
<input type="checkbox" name="model_number"> Model #
<input type="text" size="12" class="childModel"><BR>
</td>
<td>
THIS CHECKBOX BREAKS THE FUNCTIONALITY<p>
<input type="checkbox" checked disabled> Some text here</td>
</tr>
</table>
<hr>
<input type="submit" name="submit" value="submit" id="checkModelBtn"/>
To ignore the checkbox you don't want to validate you need a way to ignore it in your validation, and you can do that by using the input field. Change the selector for your checkbox from $("input[type=checkbox]:checked") to $(".childModel").prev("input[type=checkbox]:checked")
Example:
$(document).ready(function() {
$('#checkModelBtn').click(function() {
var isCheckboxChecked = $(".childModel").prev("input[type=checkbox]:checked").length;
var isTextEntered = $("input.childModel").val().length;
if (isTextEntered || !isCheckboxChecked) {
//alert("validation passed!");
} else {
alert("Please enter the Model Number");
}
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js"></script>
<table>
<tr>
<td>
<p>
<h2>MODEL:</h2>
</p>
<input type="checkbox"> Model #
<input type="text" size="12" class="childModel">
<BR>
</td>
<td>
THIS CHECKBOX BREAKS THE FUNCTIONALITY
<p>
<input type="checkbox" checked disabled> Some text here</td>
</tr>
</table>
<hr>
<input type="submit" name="submit" value="submit" id="checkModelBtn" />

My html form clears when I hit submit and try to check for form validation

When I run my code on chrome and try and enter each input one at a time, when I hit submit, all of my input clears! Help me please
Javascript code :
function data_validation()
{
var sfn = form1.sfn.value;
var sln = form1.sln.value;
var sid = form1.sid.value;
var grad = form1.grad.value;
var RegExpText = /^[A-Z a-z]+$/;
var RegExpId = /^[0-9]{6}$/;
if (!RegExpText.test(sfn))
{
alert("Please enter your first name");
document.form.sfn.focus();
document.form.sfn.select();
return false;
}
else if(!RegExpText.test(sln))
{
alert("Please enter your last name");
document.form.sln.focus();
document.form.sln.select();
return false;
}
else if(!RegExpId.test(sid))
{
alert("Please enter a 6-digit Student ID");
document.form.sid.focus();
document.form.sid.select();
return false;
}
grad = -1;
for(i=0;i<document.client.grad.length; i++)
if(document.client.grad[i].checked)
{
grad = i;
var gradYear = document.client.grad[i].value;
}
if(grad == -1)
{
alert("Please select a grade level.");
return false;
}
else if ((form1.php.checked == "") && (document.client.js.checked == "") && (document.client.c.checked == ""))
{
alert("Please select at least one programming language.");
form1.php.focus();
return false;
}
else
{
alert("Thank you for submitting!");
return true;
}
}
Here is the HTML: I have tried adding return false to onSubmit and I have also tried many other things. My teacher never taught this and I can't find another answer online that works for me.
<!DOCTYPE html>
<html>
<head>
<link href="../common/stylesheet.css" type="text/css" rel="stylesheet">
<script type = "text/javascript" src="../common/validate.js"> </script>
<meta charset="utf-8">
<title>Form Validation</title>
</head>
<body>
<div id="container"><!-- Start wrapper -->
<div id="form_data">
<form name = "form1" id = "form1" onsubmit = "return data_validation();" method="post">
<table id="tbl_form_input">
<tr>
<td colspan="2">
<h1 style="text-align:center;">Student Skills Form</h1>
</td>
</tr>
<tr>
<td class="label">Student First Name:</td>
<td><input name="sfn" size="20" ></td>
</tr>
<tr>
<td class="label">Student Last Name:</td>
<td><input name="sln" size="20" ></td>
</tr>
<tr>
<td class="label">Student ID:</td>
<td><input name="sid" size="6" maxlength="6"></td>
</tr>
<tr>
<td class="label">Programming Languages</td>
<td>
<input type="checkbox" value="PHP" name="php">PHP<br />
<input type="checkbox" value="JS" name="js">JavaScript<br />
<input type="checkbox" value="C++" name="c">C++
</td>
</tr>
<tr>
<td class="label">Expected Date of Graduation:</td>
<td>
<input type="radio" name="grad" value="2015">2015<br />
<input type="radio" name="grad" value="2016">2016<br />
<input type="radio" name="grad" value="2017">2017<br />
<input type="radio" name="grad" value="2018">2018</td>
</tr>
<tr>
<td colspan="2" style="text-align:center;">
<input type="submit" name="s" value="Send Data">
<input type="reset" name="r" value="Clear Data">
</td>
</tr>
</table>
</form>
</div><!-- End form_data id formats -->
</div> <!-- end wrapper -->
</body>
</html>
It is always good to separate the process of validating form data and the submitting.
In your code, you do them together. The default behavior of submit button is to upload all your form data and clean all the input data, so it behaves correctly as it is meant to be.
What you need to do to make it work is to add event onto those fields.
You can use jQuery .blur() to do that.
.blur() method will be triggered when the field lost focus. So here is where you should trigger your validation process.
I hope it helps.
Cheers,
Update:
Add events to the fields which you need to validate.
For example, you need to do some validation on the sln textbox.
$('input[name="sln"]').on("blur", function(){
.....Your validation here...........
});
By the way, where are the IDs for those input components???(they only have names....)

Validate a text field only if display:block

I have 2 text fields that need to be validated.
Merge/Reason field needs to be validated
Barcode needs to be validated only if it is displayed, i.e. if checkbox is checked.
What I am trying to do is pop-up an alert box for merge-reason (regardless) and add a validation message for barcode in alert if not hidden
Here is the code:
<tr><td>
<input type="checkbox" name="createCharge" id="createCharge" onClick="checkBox('Barcode', 'CreateCharge');" value="1"/>
<lable>Charge</label>
</td></tr>
<tr id="Barcode" style="display:none;">
<td>
<label>Barcode</label>
<input type="text" name="Barcode" id="Barcode"/>
</td>
</tr>
<tr>
<td>
<label>Merge:</label>
<input type="text" name="Reason" id="Reason"/>
</td>
</tr>
You can simply check like this:-
if($(x).is(":visible"))
{
//your element is visible
}
JAVASCRIPT
var display= document.getElementById('x').style.display;
if(display=='block')
{
//do validation here.
}
if( $('#Barcode').is(':visible') ){
// Perform code here
}
How do I check if an element is hidden in jQuery?
if( $('#Barcode').is(':visible') && $('#Reason').val().length!==0 ){
// Barcode is visible and reason has a value more then 0 chars long
}

Categories

Resources