Disable submit until form is filled javascript - javascript

I need to disable the submit button until all fields are filled with the rules any tips?
window.onload = $("input[type=submit]").attr("disabled", "disabled");
$(function(){
$("input[type=submit]").attr("disabled", "disabled");
var total = document.getElementById('valor_total'),
descontado = document.getElementById('valor_descontado'),
valor_final = document.getElementById('valor_final'),
vendedor = document.getElementById('vendedor'),
cliente = document.getElementById('cliente'),
no_contrato = document.getElementById('contrato'),
validation;
var f_total = total.value;
var f_descontado = descontado.value;
var f_final = valor_final.value;
var f_vendedor = vendedor.value;
var f_cliente = cliente.value;
var f_no_contrato = no_contrato.value;
$("#numero_contrato").blur(function() {
if ( f_vendedor == "0" || f_cliente == "0" || f_no_contrato == "" || f_total == "0,00" || f_final == "0,00") {
validation = false;
} else {
validation = true;
}
if (validation = true) {
$("input[type=submit]").removeAttr("disabled");
} else {
$("input[type=submit]").attr("disabled", "disabled");
}
});
});
what i'm doin wrong?
I want that user type in the field with id numero_contrato the function runs and enable or not the submit

For starters, try fixing this conditional:
if (validation === true) {
$('input[type=submit]').removeAttr('disabled');
} else {
$('input[type=submit]').attr('disabled', 'disabled');
}
You had a single equals which is used for assignment. You want double or preferably, triple equals. But you can drop those entirely since you're using a boolean: if (validation) { ... }

Related

Disable an asp net Button with javascript

I have a partial view where I would like to disable a button under certain conditions.
<td style="padding-left: 30px;">
<asp:Button ID="AddProdCostLine" runat="server" CausesValidation="False" Text="Add Line" CssClass="buttonBlue"></asp:Button>
</td>
In my javascript, I needed to check that some textboxes were filled, If not the user shouldn't be able to trigger the button (by disabling it)
In fact I need to set a textbox mandatory under the same conditions. That was my idea.
I can't find a way to disable my button here is the code :
function LoadComponentProdCost() {
$(function () {
$('input[id*="ProductionCostLineField"]').blur(function () {
var amount = this.value;
var textInInvoice = 'Mandatory';
$('input[id*="ProductionCostInvoiceToLineField"]').each(function () {
if (amount == '' || amount == '0') {
textInInvoice = '';
} else {
textInInvoice = 'Mandatory';
alert("You must inform the field 'Invoiced By'");
//doesn't work I need here to disable the button
document.getElementById("<%=AddProdCostLine.ClientID%>").disabled = "disabled";
document.getElementById('<%= AddProdCostLine.ClientID %>').disabled = true;
document.getElementById("<%=AddProdCostLine.ClientID%>").setAttribute("disabled", "disabled");
}
});
$('input[id*="ProductionCostInvoiceToLineField"]').val(textInInvoice);
});
});
My Javascript is in the partial view file .ascx
The rendered HTML for the component is like so :
<input name="ProdCostControl$ProdCostGrid$ctl02$ProductionCostInvoiceToLineField" type="text" maxlength="100" id="ProdCostControl_ProdCostGrid_ctl02_ProductionCostInvoiceToLineField" tabindex="25" style="width:269px;">
By using alert() function I managed to debug/check if my component was null so here is the solution to the code I post above :
function LoadComponentProdCost() {
$(function () {
$('input[id*="ProductionCostLineField"]').blur(function () {
var amount = this.value;
$('input[id*="ProductionCostInvoiceToLineField"]').each(function () {
var textInvoicedBy = this.value;
if (amount == '' || amount == '0') {
document.getElementById("<%=AddProdCostLine.ClientID%>").className = 'buttonBlue';
} else {
if (this.value != '' || amount == '' || amount == '0') {
document.getElementById("<%=AddProdCostLine.ClientID%>").className = 'buttonBlue';
document.getElementById('<%= AddProdCostLine.ClientID %>').disabled = false;
}
if ((amount != '' || amount != '0') && textInvoicedBy == '') {
alert("You must inform the field 'Invoiced By'");
document.getElementById("<%=AddProdCostLine.ClientID%>").className = 'buttonLightGray3';
document.getElementById('<%= AddProdCostLine.ClientID %>').disabled = true;
}
}
});
});
});
}

Javascript password validation skip if fields are empty

This works great, but I need it to do is also ignore it if the password field is left blank.
I want the user to be able to update their information without having to change their password. So if they leave the password fields blank, their password remain the same.
document.addEventListener("DOMContentLoaded", function() {
// JavaScript form validation
var checkPassword = function(str)
{
var re = /^(?=.*\d)(?=.*[a-z])(?=.*[A-Z]).{6,}$/;
return re.test(str);
};
var checkForm = function(e)
{
if(this.pwd1.value != "" && this.pwd1.value == this.pwd2.value) {
if(!checkPassword(this.pwd1.value)) {
alert("The password you have entered is not valid!");
this.pwd1.focus();
e.preventDefault();
return;
}
} else {
alert("Error: Please check that you've entered and confirmed your password!");
this.pwd1.focus();
e.preventDefault();
return;
}
};
var add_employee_form = document.getElementById("add_employee_form");
add_employee_form.addEventListener("submit", checkForm, true);
// HTML5 form validation
var supports_input_validity = function()
{
var i = document.createElement("input");
return "setCustomValidity" in i;
}
if(supports_input_validity()) {
var pwd1Input = document.getElementById("field_pwd1");
var pwd1Rule = "Password must contain at least 6 characters, including UPPER/lowercase and numbers.";
pwd1Input.setCustomValidity(pwd1Rule);
var pwd2Input = document.getElementById("field_pwd2");
var pwd2Rule = "Please enter the same Password as above.";
// input onchange event handlers
pwd1Input.addEventListener("change", function() {
this.setCustomValidity(this.validity.patternMismatch ? pwd1Rule : "");
if(this.checkValidity()) {
pwd2Input.pattern = this.value;
pwd2Input.setCustomValidity(pwd2Rule);
} else {
pwd2Input.pattern = this.pattern;
pwd2Input.setCustomValidity("");
}
}, false);
pwd2Input.addEventListener("change", function() {
this.setCustomValidity(this.validity.patternMismatch ? pwd2Rule : "");
}, false);
}
}, false);
</script>
Change your function to have this at the top:
if(!this.pwd1.value) return;
javascript will return false for values of null or blank so this says return if false.
Full function:
var checkForm = function(e)
{
if(!this.pwd1.value) return;
if(this.pwd1.value != "" && this.pwd1.value == this.pwd2.value) {
if(!checkPassword(this.pwd1.value)) {
alert("The password you have entered is not valid!");
this.pwd1.focus();
e.preventDefault();
return;
}
} else {
alert("Error: Please check that you've entered and confirmed your password!");
this.pwd1.focus();
e.preventDefault();
return;
}
};

jQuery: Compact way to fetch values of all input fields?

I have a form with five input fields and a register button ('.register').
I want to enable the register button ONLY IF all fields have at least one character.
Here comes my code:
$(document).ready(function() {
// when page loads
$('.register').addClass('a_unclickable');
// Input validation
// Are all fields filled out?
$('input').on('keyup', function() {
var un_value = $('#username_operators').val();
var fn_value = $('#first_name_operators').val();
var ln_value = $('#last_name_operators').val();
var e_value = $('#email_operators').val();
var pw_value = $('#password_operators').val();
var pw_r_value = $('#password_repeat_operators').val();
if ((un_value.length > 0) && (fn_value.length > 0) && (ln_value.length > 0) && (e_value.length > 0) && (e_value.indexOf('#') !== -1) && (pw_value.length > 0) && (pw_r_value.length > 0)) {
$('.register').removeClass('a_unclickable');
} else {
$('.register').addClass('a_unclickable');
}
})
});
I have the feeling that there is a much easier way to achieve the same result. Does anyone of you have a compact suggestion?
That's quiet compact:
$(document).ready(function() {
// when page loads
$('.register').addClass('a_unclickable');
// Input validation
// Are all fields filled out?
$('input').on('keyup', function() {
$('.register').removeClass('a_unclickable');
$('input').each(function() {
if ($(this).val() === '') {
$('.register').addClass('a_unclickable');
}
});
})
});
A couple of things come to mind. First:
$('input').on('keyup', function() {
var valid = true;
$('#username_operators, #first_name_operators, #last_name_operators, #email_operators, #password_operators, #password_repeat_operators').each(function() {
if (/^\s*$/.test(this.value)) {
valid = false;
}
});
if (valid) {
$('.register').removeClass('a_unclickable');
}
else {
$('.register').addClass('a_unclickable');
}
});
You can combine all the Ids into one CSS selector. Really the cleanest way is to add a class name to each required input, then utilize event.target.form to find all required fields inside the form.
$('input').on('keyup', function(event) {
var valid = true;
$(event.target.form).find(".required").each(function() {
if (/^\s*$/.test(this.value)) {
valid = false;
}
});
if (valid) {
$('.register').removeClass('a_unclickable');
}
else {
$('.register').addClass('a_unclickable');
}
});
Wrap the inputs in a <div class="verifyLength" ></div>
Add the a_unclickable class to the register field by default.
Then jquery:
$('input').on('keyup', function() {
var emptyField = false;
$(".verfyLength").find("input").each(function()
{
if((this).val().length() <=0)
emptyField = true;
});
if(emptyField)
$('.register').addClass('a_unclickable');
else
$('.register').removeClass('a_unclickable');
});
Here you go JSFiddle
var arr = [un_value, fn_value, ln_value, e_value, pw_value, pw_r_value];
$.each(arr,function(i,item){ if(item.length > 0){
$('.register').removeClass('a_unclickable');
} else {
$('.register').addClass('a_unclickable');
}})
if you are able to read all the values with selector you could pass them
like:
$.each($('input'),function(i,item){ if($(item).val().length > 0){
$('.register').removeClass('a_unclickable');
} else {
$('.register').addClass('a_unclickable');
}})
Have a look at this jsfiddle:
var i = 0, count = 0;
$.each($( ":input" ), function( index, value ) {
if(value.value.length > 0) {
count++;
}
});
if(count === 6) {
console.log(true);
} else {
console.log(false)
}

Error: '0.type' is null or not an object in javascript

I am getting the error below when I click the button that calls the JavaScript to do the validation. The strange thing is that everything was working before but I am not what happened now. If I select to ignore this error:
Error: '0.type' is null or not an object
then the code works fine but I get the error first then it asks me if i want to debug it, if i select No then the code works fine. Please help. thanks
it seems the code stops at this line:
if (areas[0].type == "textarea") {
but here is my entire code:
<script type ="text/javascript">
function Validate_1() {
var flag = false;
var gridView = document.getElementById('<%= GridView1.ClientID %>');
for (var i = 1; i < gridView.rows.length; i++) {
var selects = gridView.rows[i].getElementsByTagName('select');
//var inputs = gridView.rows[i].getElementsByTagName('input');
var areas = gridView.rows[i].getElementsByTagName('textarea');
if (selects != null && areas != null) {
if (areas[0].type == "textarea") {
var txtval = areas[0].value;
var selectval = selects[0].value;
if (selectval == "No" && (txtval == "" || txtval == null)) {
flag = false;
break;
}
else {
flag = true;
document.getElementById('<%=btnSubmit.ClientID%>').style.visibility = 'visible';
}
}
}
}
if (!flag) {
alert('Please note that comments are required if you select "No" from the dropdown box. Thanks');
document.getElementById('<%=btnSubmit.ClientID%>').style.visibility = 'hidden';
// areas[i].focus();
// areas.[i].style.backgroundColor = "red";
}
return flag;
}
// document.getElementById('<%=btnSubmit.ClientID%>').style.visibility = 'visible';
</script>
var areas = gridView.rows[i].getElementsByTagName('textarea');
getElementsByTagNane does not return null, the length would be zero
So your if check needs to change.
if (selects != null && areas != null)
should be
if (selects.length && areas.length)

form validation with radio buttons and specific errors

I am trying to make a form validate where there are radio buttons and textarea. I want nothing to be left empty i.e the form should be completely filled. I have done the radio buttons part of validation where if a user does not select a radio button he will get an error for that particular question. you can see the code here for detailed code.
Please help me out. I am not getting error for textarea.
Just add another check for textarea
function RadioValidator() {
var ShowAlert = '';
var AllFormElements = window.document.getElementById("FormID").elements;
for (i = 0; i < AllFormElements.length; i++) {
var name = AllFormElements[i].name;
if (AllFormElements[i].type == 'radio') {
....
} else if (AllFormElements[i].type == 'textarea') {
if (AllFormElements[i].value == '') {
ShowAlert += name + ' textarea must be filled\n';
}
}
}
if (ShowAlert !== '') {
alert(ShowAlert);
return false;
} else {
return true;
}
}
you didn't write any validation for 'textarea' block. I have updated it with one textarea... add rest validations.
function RadioValidator()
{
var ShowAlert = '';
var AllFormElements = window.document.getElementById("FormID").elements;
for (i = 0; i < AllFormElements.length; i++)
{
if (AllFormElements[i].type == 'radio')
{
var ThisRadio = AllFormElements[i].name;
var ThisChecked = 'No';
var AllRadioOptions = document.getElementsByName(ThisRadio);
var problem_desc = document.getElementById("problem_desc");
for (x = 0; x < AllRadioOptions.length; x++)
{
if (AllRadioOptions[x].checked && ThisChecked === 'No' && problem_desc.value === "")
{
ThisChecked = 'Yes';
break;
}
}
var AlreadySearched = ShowAlert.indexOf(ThisRadio);
if (ThisChecked == 'No' && AlreadySearched == -1 && problem_desc.value === "")
{
ShowAlert = ShowAlert + ThisRadio + ' option must be selected\n';
}
}else if(AllFormElements[i].type =='textarea')
{
// add your rest of text area validations here
var problem_desc_1 = document.getElementById("problem_desc");
if(problem_desc_1.value === "")
{
ShowAlert = ShowAlert + '"Services (Please Specify)" can not be blank. \n';
}
}
}
if (ShowAlert !== '')
{
alert(ShowAlert);
return false;
}
else
{
return true;
}
}
You need to add a check for textarea as well
In your javascript check you have only added a condition for type radio.
check for textarea type as well and add error if the value is blank.

Categories

Resources