assigning value to hidden field from javascript - javascript

I am trying to do what seems to be simple but am unable to accomplish
I am trying to set the value of a column after a row focus change in a grid to a hidden value in java script.
My imbedded javascript code:
function OnGridFocusedRowChanged() {
grdA.GetRowValues(grdA.GetFocusedRowIndex(), 'ClientID', OnGetRowValues);
}
function OnGetRowValues(values) {
//Set hidden value
document.getElementById('<%=hdnClientID.ClientID%>').value = values[0];
//Fire button click
btnPopulateGrids_Click();
}
where hdnClientID is the name of my hidden field
In GridA I have the setting as such that OnGridFocusedRowChanged gets executed each time a row focus change takes place.
To this point, it works fine, the values[0] in OnGetRowValues() contains the correct value from the corresponding row in GridA.
But in the corresponding code behind, I cannot access the value from hidden field hdnClientID. Always comes up null when accessing
Current_Client_ID = CInt(hdnClientID.Value);
cannot access or convert any value from
hdnClientID.ClientID.
either.
I'm missing something simple.

I had to complete a similar task recently and I too was unable to access the value from codebehind. I researched and found out that it is not that simple and that you can't do it with javascript. What I would recommend is to check if you have jQuery installed and if you do, change your function to this:
function OnGetRowValues(values) {
//Set hidden value
$('#<%=hdnClientID.ClientID%>').val(values[0]);
//Fire button click
btnPopulateGrids_Click();
//If you change your HiddenField to have OnValueChange event, you can trigger it with this
//__doPostBack('<%= CompanyCode.ClientID %>', '');
}
Also, I guess you are firing some function from code behind with btnPopulateGrids_Click();.
I would recommend adding OnValueChanged="hdnClientID_OnValueChanged"/> to your <asp:HiddenField/> and using my supplied function triggering method.

Related

The use of JavaScript onchange("<function>(this.id)") on c# CheckBox vs other c# Controls

I have a web document that has its fields populated dynamically from c# (.aspx.cs).
Many of these fields are TextBox or HtmlTextArea elements, but some are Checkbox elements.
For each of these I have the ID attribute populated on creation of the field, as well as using .Attributes.Add("onchange","markChanged(this.id)")
This works great on all the fields except Checkbox. So I created a markCheckChange as I discovered that the Checkbox won't accept style="backgroundColor:red" or .style.backgroundColor = "red" type arguments.
I also added an alert and found that the Checkbox is not actually passing the this.id into the parameter for markCheckChange(param) function.
As a result I am getting errors of the type:
unable to set property of undefined or null reference
Why and what is the difference between these controls, and is there a better way to handle this?
I just reviewed the inspect element again, and discovered that the Checkbox control is creating more than an input field of the type checkbox, it is also wrapping it in a span tag, and the onchange function is being applied to the span tag (which has no id) and not to the input tag that has the checkbox id. Whereas for TextBox and HtmlTextArea the input tag is put directly within the cell/td tag, no some arbitrary span tag.
So now the question becomes how to get the onchange function to apply to the input tag for the checkbox rather than the span tag encapsulating it?
Per request:
function markChange(param) {
if (userStatus == "readonly") {
document.getElementById("PrintRecButton").style.display = "none";
document.getElementById("PrintPDFButton").style.display = "none";
alert("Please login to make changes.\n\nIf you do not have access and need it,\n contact the administrator");
exit();
}
else {
document.getElementById(param).style.backgroundColor = "teal";
saved = false;
var page = document.getElementById("varCurrentPage").value;
markSaveStatus(page, false);
}
}
So far the markCheckChange is about the same, until I get it to pass the id correctly, I won't be able to figure out the right way to highlight the changed checkboxes.
I found an alternative.
As I mentioned in the edit to the question, the inspect element feature revealed that the CheckBox type control was creating a set of nested elements as follows:
<span onchange="markChange(this.id)">
<input type="checkbox" id="<someValue>">
<label for="<someValue>">
</span>
Thus when the onchange event occurred it happened at the span which has no id and thus no id was benig passed for the document.getElementById() to work.
While searching for why I discovered:
From there I found the following for applying labels to the checkboxes:
https://stackoverflow.com/a/28675013/11035837
So instead of using CheckBox I shall use HtmlInputCheckBox. And I have confirmed that this correctly passes the element ID to the JavaScript function.

Understanding jQuery .change event

I have some issue understanding the jQuery().change() behavior.
The HTML is basically a lot of input elements - checkboxes ( each with ID of id^='o99-post-visible-XXX' - and they are pure CSS images as Checkboxes, but this is irrelevant ) and I have another checkbox ("#o99-check-all") to "check all" and a text input field ('#o99-post-visible-ids') that receives the IDs of the selected boxes.
The jQuery code is as follows:
jQuery(document).ready(function() {
jQuery("#o99-check-all").change(function () {
jQuery("input:checkbox[id^='o99-post-visible-']").prop('checked', jQuery(this).prop("checked")).trigger('change');
});
var checkboxes = jQuery("input.o99-cbvu-posts-checkbox:checkbox");
checkboxes.on('change', function() {
// get IDS from all selected checkboxes and make a comma separated string
var ids = checkboxes.filter(':checked').map(function() {
return this.value;
}).get().join(',');
// put IDS inside a text input field
jQuery('#o99-post-visible-ids').val(ids);
// console.log(ids);
});
});
Now, more or less everything works now, but that is not the issue.
at first , the first chunk of code was:
jQuery("#o99-check-all").change(function () {
// without .trigger('change') chained
jQuery("input:checkbox[id^='o99-post-visible-']").prop('checked', jQuery(this).prop("checked"));
});
and it did not work ( why?? ) - meaning the boxes were selected as expected but the '#o99-post-visible-ids' input field was not receiving the IDs - until I chained a .trigger('change') event - when suddenly it works well.
my confusion is with the following ( which perhaps for my little understanding of jQuery internal works is counter-intuitive )
after chain adding .trigger('change') - isn't it somehow an endless loop where a chain() event is trigger inside a listener of change() ? and if not why?
Why is the code functioning now and did not function correctly before? because again, for my understanding, there was a change, even if not triggered by direct user click. Why would I need to trigger it manually?
I'm not sure I understand what you mean. What is happening now, is that whenever you change the all checkbox, the other checkboxes will be checked/unchecked the same as all, and then the change event is triggered.
Because you added a listener for change, that function will then fire. I.e. this function will run:
function() {
// get IDS from all selected checkboxes and make a comma separated string
var ids = checkboxes.filter(':checked').map(function() {
return this.value;
}).get().join(',');
// put IDS inside a text input field
jQuery('#o99-post-visible-ids').val(ids);
// console.log(ids);
}
Without your .trigger("change") (or .change() in short), you only change a property of the inputs. So the object changes, indeed, but that does not mean the change event is triggered. It does sound counter-intuitive, but events are only triggered by user actions or if you call the event explicitly - in no other way do events get triggered.
its because you have written jQuery('#o99-post-visible-ids').val(ids); inside a function which happens only when the change event done on the inputs, assigning prop directly through .prop does not trigger the change event and so the result handler wont run
Now if I understand you correctly...
...because you're giving every check box the same ID? If you wish to apply it to more than a single element, it is best practice to use a class selector instead.
jQuery(".o99-check-all").change(function () {
// without .trigger('change') chained
jQuery(".o99-check-all").prop('checked', jQuery(this).prop("checked"));
});
See link
https://api.jquery.com/change/

How to make statements effect after a change event was fired?

I have a select element in a form with id of "qlt".
And if I change the value of that selection, other SELECT(#names) element changes its option(s).
However, it seems the change function takes effect at the moment I tick the dropdown, not after the value has changed.
So my jquery code condition below has an opposite effect. If the value of qlt is 14-1, then the selection will have "Hello (90x55mm)" as its option insted of Business Card (90x55mm.
var qlt = (jQuery("#qlt").val()).split(":")[0];
jQuery('#qlt').change(function(){
if(qlt=="14-1"){
ChangeOptions(["Business Card (90x55mm)"],"#names",[1]);
}
else if(qlt=="14-2"){
ChangeOptions(["Hello (90x55mm)"],"#names",[2]);
}
});
jQuery('#names').change(function(){
quantities=[50,100,250,500,1000,2000,5000];
ChangeOptions(quantities,"#qlnt",quantities);
});
If my question is not clear, you can visit the actual site here:
http://210.48.94.218/~printabl/products/labels-stickers/
The two select elements I am referring to are the Quality and Size dropdowns. The form is in the middle.
The actual problem looks like the order of callback execution
The qlt variable is set using the method calculate which is registered using jQuery("select").change(calculate); at line 701.
But the change options callback is registered at line 528 which will get executed before the calculate method is called that is why the value of qlt is not updated until next select.
One solution is to move jQuery("select").change(calculate); before line 528 another one is below
It might be a problem of some script execution, I assume qlt is supposed to be the current selected value in the #qlt input then you can declare a local variable and assign the current value using $(this).val()
jQuery('#qlt').change(function(){
var qlt = $(this).val().split(":")[0];
if(qlt=="14-1"){
ChangeOptions(["Business Card (90x55mm)"],"#names",[1]);
}
else if(qlt=="14-2"){
ChangeOptions(["Hello (90x55mm)"],"#names",[2]);
}
});

Jquery Not able to fetch changed value of input field

I am trying to fetch the changed input filed value using jquery which is getting changed javascript event of drop down select.
I simply am not getting where exactly the things are getting wrong. It is something related to dom tree refresh (.live)? Any help/suggestions would be great. Thanks.
/* adding the value to user_val input field id in javascript onload function based on drop down select event*/
document.getElementById('user_val').Value = "abcd";
/* then trying to get value which changed */
$(document).ready(function() {
$("#submits").click(function() {
alert($("#user_val").val());
});
You haven't closed your click event handler function. Change it to this:
$(document).ready(function() {
$("#submits").click(function() {
alert($("#user_val").val());
});
});
And change Value to value (note the lowercase "v"), and then it should work fine.
Two errors you got there:
You should use document.getElementById('user_val').value = "abcd"; and not document.getElementById('user_val').Value = "abcd"; (lower case value, not Value).
You should also close the ready event after your click event.
Here is the complete working solution:
/* adding the value to user_val input field id in javascript onload function based on drop down select event*/
document.getElementById('user_val').value = "abcd";
/* then trying to get value which changed */
$(document).ready(function() {
$("#submits").click(function() {
alert($("#user_val").val());
});
});

Input hidden control doesn´t keep the his value between postbacks

I'm making an webpage using ASP.NET MVC.
I have the following input hidden definied:
<%=Html.Hidden("inputHiddenSelectedMenuId") %>
And i set its value in this js function:
function SetSelectedMenu(id) {
$('#inputHiddenSelectedMenuId').val(id);
}
After a make a postback in the js init function i want to use the value set in the input hidden but the value is string empty.
$(document).ready(function() {
$('div.nav > a').removeClass('active');
var id = $('#inputHiddenSelectedMenuId').val();
if (id != "") {
$("#" + id).addClass('active');
}
});
Can anyone give a hint why this is happening?
You are trying to read the value of the input in javascript. When you click a button on a form and it does a post back your page is being reloaded and the javascript re-runs every time the page is loaded. If all you are doing is reading the value of an input in javascript you do not need to perform a postback.
$('#inputHiddenSelectedMenuId').bind('click', function ()
{
var id = $('#inputHiddenSelectedMenuId').val();
// do stuff with it.
});
The click function will be performed without a postback.
Now, if you are trying to read the contents of the hidden field from within MVC after a post then this is a different issue. You will have to pull it from the form data through model binding (or reading it directly through the Request.Form[] collection.
public ActionResult SomeActionToPostTo(int inputHiddenSelectedMenuId)
{
//model binding should find the form field called inputHiddenSelectedMenuId and populate the argument in this method with it's value. If it's not an integer then just change the type of the argument to the appropriate type.
}

Categories