javascript error: Cannot read property 'options' of null - javascript

I have a GridView that has a column with a textbox where the user can enter a value and a column with a dropdownlist. If the user enter a values that is not equal to 1 in the textbox, they must select a value from the dropdownlist. The default value in the DDL is "Select" which is just an empty value that was coded in: ddlReasons.Items.Insert(0, new ListItem("Select"));. The DDL is created dynamically but select will always be the default value.
function UpdateSerialQtyRcvd(SerNoID, QtyRcvd) {
if (QtyRcvd != 1) {
var ddl = document.getElementById("ddlReasons");
var selectedValue = ddl.options[ddl.selectedIndex].value;
if (selectedValue == "Select") {
alert("Must select reason");
}
}
else {
PageMethods.UpdateSerialQtyRcvdUserControl(SerNoID, QtyRcvd, OnUpdateSuccess, OnUpdateFail);
}
}
If the user enters a value that is not 1 then I need to check what value is in the DDL. If "Select" is the value I need the user to select something else in the DDL but I am getting this error on the line var selectedValue = ddl.options[ddl.selectedIndex].value;
Uncaught TypeError: Cannot read property 'options' of null
Code for dropdownlist:
<asp:TemplateField HeaderText="Reason">
<ItemTemplate>
<asp:DropDownList ID="ddlReasons" runat="server" class="ReasonDDL" ></asp:DropDownList>
</ItemTemplate>
</asp:TemplateField>

You'll need to get the ClientId...
Javascript:
var ddl = document.getElementById("<%=ddlReasons.ClientID%>");
JQuery:
var ddl = $('#<%=ddlReasons.ClientID%>');
Check out the MSDN documentation on how to access the Client ID and the different settings.

One more way to do it using JQuery :
var ddlReason = $("[id*=ddlReasons]");
var selectedValue = ddlReason.val();

Related

Get checkbox state in array with javascript or jquery

I have on a devexpress grid one column with a checkbox. It is a simple checkbox column, which depends on which checkbox is checked I need to invoke different methods, it is not bind to a property from model.
I need to know which row is selected. I have tried to resolve this with this javascript code:
if (document.getElementById('selectDamage').checked) {
alert("checked");
var checkedValues = $('input:checkbox:checked').map(function () {
return this.value;
}).get();
console.log(checkedValues);
} else {
alert("You didn't check it! Let me check it for you.");
}
This returns only the checked values. I need to return something like Array{on, off, on}, the first is checked, the second one is unchecked and the last is checked. Is there a way in javascript or jquery to do that?
first add checkbox in grid then take a button and set onclick function of this button , then all checked data will go through array and finally split the array value and do your further job.(array value are saved into hidden field, i used hidden field and set the id lblarr )
<dx:GridViewDataColumn >
<HeaderTemplate>
</HeaderTemplate>
<DataItemTemplate>
<input type="checkbox" class="case" id="chkchild" name="checkboxModel" value='<%#Eval("SALE_DOC_#") %>' />
</DataItemTemplate>
</dx:GridViewDataColumn>
<script>
$('#btn1').click(function () {
var CheckCount =$('input:checkbox[name="checkboxModel"]:checked').length;
if (CheckCount > 0)
{
var valuesArray =
$('input:checkbox[name="checkboxModel"]:checked').map(function () {
return this.value;
}).get().join(",");
$('#<%=lblarr.ClientID%>').val(valuesArray);
}
else {
alert('Please check at least one data!')
}
})
</script>
Depending on the layout of your html, you could do something like this to get an updated array of indexed checked states
var els = $("table#gvDamages3_DXMainTable input[type=checkbox]");
els.on("change", function(){
var vals = [];
els.each(function() {
vals.push(this.checked);
});
console.log(vals);
});

Issue in changing textbox background color by using javascript

I want to pass the texttbox id to javascript function and change the color of the textbox if the value is null.
function fnOnUpdateValidatorsNewChangeChange(txtid) {
var txt1 = document.getElementById(txtid);
var Value = document.getElementById(txtid).value
if (Value == "") {
txt1.style.background = "#FFF000";
}
}
<asp:TextBox runat="server" ID="txtlabelID" class="textbox" TextMode="SingleLine"
onchange="fnOnUpdateValidatorsNewChangeChange('<%= txtlabelID.ClientID %>')"
But it's getting Null error.
you not need to pass ID of textbox and find textbox using the same id ..
You just pass this as a textbox in argument for E.g.
<asp:TextBox runat="server" ID="txtlabelID" class="textbox" TextMode="SingleLine"
onchange="fnOnUpdateValidatorsNewChangeChange(this)"
function fnOnUpdateValidatorsNewChangeChange(txtbox) {
if (txtbox.value == "") {
txtbox.style.background = "#FFF000";
}
else
txtbox.style.background = "";
}
Is it more Simple ??

Ajax autocomplete Extender prevent to type invalid value in text box

am using Ajax AutoCompleteExtender in asp textbox as below.
it's working fine but,
Problem: when user type text which is invalid or not match from the database value, it should show a message to user like "keyword not matched..."
Code
<asp:HiddenField id ="hdnFieldValue" runat="server"/>
<asp:TextBox ID="txtContactsSearch" runat="server"></asp:TextBox>
<cc1:AutoCompleteExtender ServiceMethod="SearchCustomers"
MinimumPrefixLength="2"
CompletionInterval="100" OnClientItemSelected="ClientItemSelected" UseContextKey="true" EnableCaching="false" CompletionSetCount="10"
TargetControlID="txtContactsSearch"
ID="AutoCompleteExtender1" runat="server" FirstRowSelected = "false">
</cc1:AutoCompleteExtender>
Java Script Code
<script type="text/javascript">
function ClientItemSelected(sender, e) {
$get(e.get_value());
$get("<%=hdnFieldValue.ClientID %>").value = e.get_value();
}
</script>
I am get value using above javascript method into asp hidden field. But I want to set Empty into hidden field when user type invalid text
Please give me suggestions.
Thanks.
ADD IN YOUR AUTOEXTENDER :
<cc1:AutoCompleteExtender ServiceMethod="SearchCustomers" OnClientPopulated="ClientPopulated"
</cc1:AutoCompleteExtender>
JS : From below you can highlight your Text with result,same way you can check for text
<script type="text/javascript">
function ClientPopulated(source, args) {
if (source._currentPrefix != null) {
var list = source.get_completionList();
var search = source._currentPrefix.toLowerCase();
for (var i = 0; i < list.childNodes.length; i++) {
var text = list.childNodes[i].innerHTML;
var index = text.toLowerCase().indexOf(search);
if (index != -1) {
var value = text.substring(0, index);
</script>

how to set button to be visible only after i made changes in 2 dropdownlists in javascript

in aspx file I have
<asp:DropDownList ID="DropDownList1" runat="server" >
</asp:DropDownList>
<asp:DropDownList ID="DropDownList2" runat="server">
</asp:DropDownList>
<asp:Button ID="load_data" runat="server" Text="<%$ Resources : load_data %>"
onclick="load_data_class_Click" Visible="False"/>
Now I want to set button to be visible only after i made changes in 2 dropdownlists in javascript
how to do this?
Markup will not be generated for ASP.NET controls whose Visible property is set to False. You need to apply CSS (display:none or visibility) via JavaScript code.
The first problem is that you can't use Visible="false", you need to use CSS and set visibility: hidden;, or display:none.
Once you've done that, you can do the following ->
Get the ID's of the lists:
//id #1
var ddl1 = document.getElementById("DropDownList1");
//id #2
var ddl2 = document.getElementById("DropDownList2");
Now, we need to create an onChange function to grab the values, and test if they're empty, if not, then we'll show the button.
function showButton(){
//out of <option value="3"> This is 3rd </option> you get:
var selected1text = ddl1.option[ddl.selectedIndex].text; // returns: This is 3rd
var selected1value = ddl1.option[ddl.selectedIndex].val; // returns: 3
//out of <option value="75"> This is 75th </option> you get:
var selected2text = ddl2.option[dd2.selectedIndex].text; // returns: This is 75th
var selected2value = ddl2.option[dd2.selectedIndex].val; // returns: 75
if(
selected1text != "" &&
selected1value != "" &&
selected2text != "" &&
selected2value != ""
){
//Our select lists all have values. We can show our button now.
//if you use visibility:hidden;
document.getElementById('load_data').style.visibility='visible';
//if you use display:none;
document.getElementById('load_data').style.display='block';
}else{
//don't do anything.
}
}
Then, in your dropdown list, you can add the onChange=showButton();
Should work.
You can take one hidden element with value 0 and whenever someone change the dropdown, increment the value of this hidden element and when it reaches equal to 2 then show the button.
Basically you need to call a function on change event of both drop-down which will do the above thing.
I solved the problem with jquery
$(document).ready(function () {
$('#load_data').live('click', function () {
var result;
if (($('#DropDownList1 option:selected').val() != '') &&
($('#DropDownList2 option:selected').val() != '') &&
($('#DropDownList3 option:selected').val() != '')) {
//result = true;
alert("true");
result = true;
} else {
// result= false;
alert("false");
result = false;
}
return result;
});
});

How to enable and disable CheckBox in the GridView using JavaScript?

I have a GridView "gvpodetails". In that I have two checkboxes one in the first column of the GridView and another one in the last column of the GridView.
I want to enable the second checkbox when the first checkbox is checked.
And I want to disable the second checkbox when the first checkbox is unchecked.
I have wirtten the following JavaScript.
var grid = document.getElementById('<%=gvPODetails.ClientID %>');
var PlannedQty = 0*1;
if(grid != null)
{
var Inputs = grid.getElementsByTagName('input');
for(i = 0;i < Inputs.length;i++)
{
var id=String(Inputs[i].id);
if(Inputs[i].type == 'text' && id.indexOf("txtPlannedQuantity")!=-1)
{
if(Inputs[i-2].type == 'checkbox')
{
if(Inputs[i-2].checked)
{
if(Inputs[i+2].value == "0.000")
Inputs[i+2].value = (parseFloat(Inputs[i].value) - parseFloat(Inputs[i+1].value))
else
Inputs[i+2].value = Inputs[i+2].value;
Inputs[i+2].disabled = false;
Inputs[i+3].disabled = false;
Inputs[i-1].disabled = false;
Inputs[i+6].disabled = false;// This is for Second CheckBox
}
else
{
Inputs[i+4].value="0.00";
Inputs[i+5].value="0.00";
Inputs[0].checked = false;
Inputs[i+2].disabled = true;
Inputs[i+3].disabled = true;
Inputs[i-1].disabled = true;
Inputs[i+6].disabled = true;// This is for Second CheckBox
}
}
}
}
}
<Columns>
<asp:TemplateField>
<ItemTemplate>
<asp:CheckBox ID="chkSelect" runat="server" Checked='<%#Bind("Select") %>' onClick="CheckedTotal();" /></ItemTemplate>
<HeaderTemplate>
<asp:CheckBox ID="chkSelectAll" runat="server" onclick="CheckAll();" /></HeaderTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="ED_f">
<ItemTemplate>
<asp:CheckBox ID="chkEDInclusive" runat="server" Checked = '<%#Bind("EDInclusive_f") %>' Enabled="false" />
</ItemTemplate>
</asp:TemplateField>
</Columns>
These are my javascript and GridView source code.
I also has some textboxes in the template field columns. This condition is applicable to all the textboxes in the GridView.
But the TextBoxes are enabled and disabled properly except the last CheckBox.
I have given only the Source code for the two Checkboxes only.
How to enable and disable the last checkbox in the GridView when the first the CheckBox is checked and Unchecked?
I need all your suggestions please..
You should probably use event delegation. on the grid to do this.
This javascript assumes that your row tag name is 'tr' and that your second checkbox is input[1] when selecting all inputs of that particular row. If you need IE support you'd need to use your favorite event handling wrapper.
window.onload = function () {
var rowNodeName = 'tr',
firstInputClassName = 'foo';
document.getElementById('<%=gvPODetails.ClientID %>').addEventListener('change', function (e) {
if (e.target.type === 'checkbox' && e.target.className.match(firstInputClassName)) {
// Find parent row
var row = e.target.parentNode;
while (row.nodeName !== rowNodeName.toUpperCase()) {
row = row.parentNode;
if (!row) {
break; // In case we hit document
}
}
if (row) {
var inputs = row.getElementsByTagName('input');
inputs[1].disabled = !e.target.checked;
}
}
}, false);
}
This will handle change events on any input in the grid with a className of 'foo' as defined in the firstInputClassName variable. When triggered will walk up the dom tree to a node with a tagname equalling rowNodeName, select the inputs in that row and set the disabled status of the second input in that row opposite of the checked state of the input that triggered the event.

Categories

Resources