JavaScript Function with multi-parameters - javascript

how to send this with eval as paramters for javascript function ?
<asp:RadioButton runat="server" id="rd" ClientIDMode="AutoID" onclick='<%# String.Format("OnCheckChange(\"{0}\", \"{1}\");", this, Eval("BookID"))%>' />
this way doesn't work and here my function which always return
Cannot read property 'parentNode' of undefined
function OnCheckChange(rb,idm ) {
//logic for exclusive setting the radio button that was last clicked.
var table = document.getElementById('ListTable');
var radiobtn = table.getElementsByTagName('input');
for (k = 0; k < radiobtn.length; k++)
{
if ((radiobtn[k].type == 'radio') && (rb.id == radiobtn[k].id))
{
radiobtn[k].checked = true;
}
else
radiobtn[k].checked = false;
}
//Book id against the selected radio button.
var hdfield = rb.parentNode.parentNode.cells[0].getElementsByTagName('input');
if (hdfield[0].type == 'hidden')
document.getElementById("hdnField").value = idm;
//enabling /disabling buttons on the basis of checkin /checkout
if (rb.parentNode.parentNode.cells[6].innerHTML == 'Checked In') {
document.getElementById('btnCheckIn').disabled = false;
document.getElementById('btnCheckOut').disabled = true;
}
else if (rb.parentNode.parentNode.cells[6].innerHTML == 'Checked Out') {
document.getElementById('btnCheckOut').disabled = true;
document.getElementById('btnCheckIn').disabled = false;
}
}
if i send this without eval its work

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;
}
}
});
});
});
}

How should I improve my javascript form validation?

I grabbed the form from some random site because I'm only interested writing the javascript at the moment.
I am trying to check that a user has selected or entered text for all fields. I've made it a long if if-else but that can't be the best/most elegant/easiest solution.
Leaving aside the radio button validation for now, what's the better way to check that the text fields, drop down, and checkboxes all have a value/input?
I'm teaching myself javascript so I'm open to being told the proper way and I'll research it and do it on my own, or updating my fiddle would be fine too. (Be gentle with me. I'm sure this code is janky.)
Any thoughts on this would be appreciated.
Fiddle: https://jsfiddle.net/kiddigit/g0rur21a/
document.getElementById("newForm").addEventListener("submit", enterForm);
function enterForm(event) {
event.preventDefault();
var dropdown = document.getElementById('dropDown');
if (document.getElementById('fname').value === ''){
document.getElementById('fname').focus();
alert('Enter text.');
} else if (document.getElementById('eMail').value === ''){
document.getElementById('eMail').focus();
alert('Enter text.');
} else if (document.getElementById('textArea').value === '') {
document.getElementById('textArea').focus();
alert('Enter text.');
} else if (!dropDown.value) {
document.getElementById('dropDown').focus();
alert('Choose an option.');
} else if ( ( newForm.checkbox[0].checked == false ) && ( newForm.checkbox[1].checked == false ) )
{ alert ( "Please choose a checkbox" );
return false;
}
var radios = document.getElementsByName("radio");
var formValid = false;
var i = 0;
while (!formValid && i < radios.length) {
if (radios[i].checked) formValid = true;
i++;
}
if (!formValid) alert("Please check a radio button.");
return formValid;
return false;
};
If you use HTML5, and assuming you're NOT using jQuery for anything (just native JavaScript), a good convention would be to assign a class to all input elements in the form that you want to validate (or if they all need to be validated, you can get all child elements of the form), and use getElementsByClassName(). With HTML5 data-* attributes, you can assign something like data-invalid-error-message to set the error message for the element itself.
http://www.w3schools.com/jsref/met_document_getelementsbyclassname.asp
From there, you can perform a loop across all elements, check if they're empty, and then grab the data-invalid-error-message attribute and display it to the user without doing nested if statements.
https://developer.mozilla.org/en-US/docs/Web/Guide/HTML/Using_data_attributes
document.getElementById("newForm").addEventListener("submit", function (event) {
event.preventDefault();
if (!document.getElementById('fname').value) {
return alert('Enter text.');
}
if (document.getElementById('eMail').value === '') {
document.getElementById('eMail').focus();
return alert('Enter text.');
}
if (document.getElementById('textArea').value === '') {
document.getElementById('textArea').focus();
return alert('Enter text.');
}
var dropdown = document.getElementById('dropDown');
if (!dropdown || !dropDown.value) {
document.getElementById('dropDown').focus();
return alert('Choose an option.');
}
if (( newForm.checkbox[0].checked == false ) && ( newForm.checkbox[1].checked == false )) {
return alert("Please choose a checkbox");
}
var radios = document.getElementsByName("radio");
var formValid = false;
var i = 0;
while (!formValid && i < radios.length) {
if (radios[i].checked) {
formValid = true;
}
i++;
}
if (!formValid) {
return alert("Please check a radio button.");
}
// Form is valid here
});
Here is some improvements. Updated Fiddle
I would like to validate form with required property, but it does not support validation of group of options and radio groups
If you're OK not supporting IE8, you can use querySelectorAll to dynamically get all the nodes of different types within your form and validate them accordingly. This will work for a form with any number of inputs:
function validateForm(formNode) {
var formValid = true;
var textFlds = formNode.querySelectorAll('input[type="text"],input[type="email"],input[type="password"],textarea');
var dropdowns = formNode.querySelectorAll('select');
var checks = formNode.querySelectorAll('input[type="checkbox"]');
var anyChecked = false;
var radios = formNode.querySelectorAll('input[type="radio"]');
var anyRadios = false;
for (var i = 0, l = textFlds.length; i < l; i++) {
if (!textFlds[i].value) {
textFlds[i].focus();
alert('Please enter text into the ' + textFlds[i].name + ' field.');
formValid = false
break;
}
};
for (var i = 0, l = dropdowns.length; i < l; i++) {
if (formValid && !dropdowns[i].value) {
dropdowns[i].focus();
alert('Please choose an option from the ' + dropdowns[i].name + ' selector.');
formValid = false
break;
}
};
for (var i = 0, l = checks.length; i < l; i++) {
if (checks[i].checked) {
anyChecked = true;
break;
}
};
if (formValid && !anyChecked) {
alert('Please choose at least one of the checkboxes.');
formValid = false;
}
for (var i = 0, l = radios.length; i < l; i++) {
if (radios[i].checked) {
anyRadios = true;
break;
}
};
if (formValid && !anyRadios) {
alert('Please check a radio button.');
formValid = false;
}
return formValid;
}
document.getElementById('newForm').addEventListener('submit', function (evt) {
evt.preventDefault();
validateForm(this);
});
This could be prettied up a bit, but you get the idea. (fiddle here)

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.

CheckBoxList Items using JavaScript

I have a checkoxlist with a couple of items and an all option. The user can select all and I want this to check off all the options and if they uncheck all it will uncheck all options.
I have accomplished this with the following code.
<script language="javascript" type="text/javascript">
function CheckBoxListSelect(cbControl) //, state)
{
var chkBoxList = document.getElementById(cbControl);
var chkBoxCount= chkBoxList.getElementsByTagName("input");
alert(chkBoxCount[0].checked);
for(var i=0;i<chkBoxCount.length;i++)
{
chkBoxCount[i].checked = chkBoxCount[0].checked //state;
}
return false;
}
</script>
cblAffiliation.Attributes.Add("onclick", "javascript: CheckBoxListSelect ('" & cblAffiliation.ClientID & "');")
The issue is that if I select any of the boxes it loops through and then sets them to whatever the all option is. I am having trouble figuring out the best way to get around this.
I want to avoid using a checkbox next to the checkboxlist, then I have to make that line up with the checkboxlist.
Simply check to see if the box clicked was the all option. If it was, then go ahead and change the rest of the boxes. If it isn't, then check all the options to see if they are all checked so you can update the 'All' checkbox.
EDIT
You might want to use onChange, instead of onClick, onClick will probably be called before the value on the given checkbox is changed.
Code not checked, please forgive syntax problems.
<script language="javascript" type="text/javascript">
function CheckBoxListSelect(cbControl) //, state)
{
var chkBoxList = document.getElementById(cbControl);
var chkBoxCount= chkBoxList.getElementsByTagName("input");
var clicked = this;
alert(chkBoxCount[0].checked ? 'All is Checked' : 'All is not Checked');
alert(clicked == chkBoxCount[0] ? 'You Clicked All' : 'You Didn't click All');
var AllChecked = true; // Check the all box if all the options are now checked
for(var i = 1;i < chkBoxCount.length; i++)
{
if(clicked == chkBoxCount[0]) { // Was the 'All' checkbox clicked?
chkBoxCount[i].checked = chkBoxCount[0].checked; // Set if so
}
AllChecked &= chkBoxCount[i].checked; // AllChecked is anded with the current box
}
chkBoxCount[0].checked = AllChecked;
return false;
}
</script>
cblAffiliation.Attributes.Add("onchange", "javascript: CheckBoxListSelect ('" & cblAffiliation.ClientID & "');")
I think this code will help you.
<script type="text/javascript">
function check(checkbox)
{
var cbl = document.getElementById('<%=CheckBoxList2.ClientID %>').getElementsByTagName("input");
for(i = 0; i < cbl.length;i++) cbl[i].checked = checkbox.checked;
}
</script>
<asp:CheckBox ID="CheckBox1" runat="server" onclick="check(this)" />
<asp:CheckBoxList ID="CheckBoxList2" runat="server">
<asp:ListItem>C1</asp:ListItem>
<asp:ListItem>C2</asp:ListItem>
</asp:CheckBoxList>
<asp:CheckBox ID="checkAll" runat="server" Text="Select/Unselect" onclick="CheckAll();" />
<asp:CheckBoxList ID="chkTest" runat="server" onclick="ClearAll();">
<asp:ListItem Text="Test 1" Value="0"></asp:ListItem>
<asp:ListItem Text="Test 2" Value="1"></asp:ListItem>
<asp:ListItem Text="Test 3" Value="2"></asp:ListItem>
</asp:CheckBoxList>
<script type="text/javascript">
function CheckAll() {
var intIndex = 0;
var rowCount=document.getElementById('chkTest').getElementsByTagName("input").length;
for (intIndex = 0; intIndex < rowCount; intIndex++)
{
if (document.getElementById('checkAll').checked == true)
{
if (document.getElementById("chkTest" + "_" + intIndex))
{
if (document.getElementById("chkTest" + "_" + intIndex).disabled != true)
document.getElementById("chkTest" + "_" + intIndex).checked = true;
}
}
else
{
if (document.getElementById("chkTest" + "_" + intIndex))
{
if (document.getElementById("chkTest" + "_" + intIndex).disabled != true)
document.getElementById("chkTest" + "_" + intIndex).checked = false;
}
}
}
}
function ClearAll(){
var intIndex = 0;
var flag = 0;
var rowCount=document.getElementById('chkTest').getElementsByTagName("input").length;
for (intIndex = 0; intIndex < rowCount; intIndex++)
{
if (document.getElementById("chkTest" + "_" + intIndex))
{
if(document.getElementById("chkTest" + "_" + intIndex).checked == true)
{
flag=1;
}
else
{
flag=0;
break;
}
}
}
if(flag==0)
document.getElementById('checkAll').checked = false;
else
document.getElementById('checkAll').checked = true;
}
</script>
function checkparent(id) {
var parentid = id;
var Control = document.getElementById(parentid).getElementsByTagName("input");
if (parentid.indexOf("List") != -1) {
parentid = parentid.replace("List", "");
}
if (eval(Control).length > 0) {
if (eval(Control)) {
for (var i = 0; i < Control.length; i++) {
checkParent = false;
if (Control[i].checked == true) {
checkChild = true;
}
else {
checkChild = false;
break;
}
}
}
}
if (checkParent == true && document.getElementById(parentid).checked == false) {
document.getElementById(parentid).checked = false;
checkParent = true;
}
else if (checkParent == true && document.getElementById(parentid).checked == true) {
document.getElementById(parentid).checked = true;
checkParent = true;
}
if (checkChild == true && checkParent == false) {
document.getElementById(parentid).checked = true;
checkParent = true;
}
else if (checkChild == false && checkParent == false) {
document.getElementById(parentid).checked = false;
checkParent = true;
}
}
function CheckDynamic(chkid) {
id = chkid.id;
var chk = $("#" + id + ":checked").length;
var child = id + "List";
if (chk != 0) {
$("[id*=" + child + "] input").attr("checked", "checked");
}
else {
$("[id*=" + child + "] input").removeAttr("checked");
}
checkparent(id);
}

Categories

Resources