Client side data to server side - javascript

I'm trying to use a JavaScript popup box (prompt) to get some user input on my website, and then do some more actions on the server-side based on what the user does.
The popup box is, for lack of words, popping up.
The following is the code that I have tried to use for this:
<div>
<asp:HiddenField ID="hidden" runat="server" />
</div>
<script>
function userInput() {
var reason = prompt("Enter reason for deleting:", "");
//User pressed okay but didn't type anything
while (reason == "") {
//Keeps cycling until reason given or cancel is hit
reason = prompt("Enter reason for deleting:", "");
}
if (reason != "" && reason != "Code:CancelDelete") {
//User typed something and hit okay
document.getElementById('hidden').innerHTML = reason.toString();
$('#deleteReason').val(reason.toString());
$("#hidden").val(reason.toString());
}
else {
//User hits cancel
document.getElementById('hidden').nodeValue = "Code:CancelDelete";
}
}
</script>
The while loop in the script works for what I need it to do. The problem from what I can tell is trying to set the value of the HiddenField. I have tried the following ways:
innerHTML
innerText
nodeValue
While looking into this, I have seen .value used a lot and have tried it myself but when I go to type document.getElementById('hidden').value =, there is no popup option or description for .value.
I have tested the server side code and so I know that works. It all comes down to getting the user input. Either way, here is an excerpt from the c# code:
string deleteReason = hidden.Value;
//string deleteReason = test.InnerHtml.ToString();
if (deleteReason.Equals("Code:CancelDelete"))
{
}
else if (!deleteReason.Equals("Code:CancelDelete") && !deleteReason.Equals(""))
{
More or less at a loss on this one.
Update 1:
Here is the html code generated on the client side browser(Firefox) for the hidden field:
<input name="ctl00$IndividualPageContent$hidden"
id="IndividualPageContent_hidden" type="hidden">

When you type an element ID on webform, the asp.net gives it a unique ID based on some things (Your form, your repeater, etc...)
If you want to use jQuery with this ID, you can use the ClientId prop.
Something like this:
if (reason != "" && reason != "Code:CancelDelete") {
//If your server id= "hidden"
ele = $("#<%= hidden.ClientID %>");
ele.html() = reason.toString();
...
}
Another option is to add the static ID to your server element, and then your code will work as is. (the html will be rendered with ID = hidden)
ClientIDMode="static"
<div>
<asp:HiddenField ID="hidden" runat="server" ClientIDMode="static"/>
</div>

You are trying to set the value of an element with id 'hidden', but that's not the id of your hidden input.
The correct id is 'IndividualPageContent_hidden'.
Set the value like this instead:
document.getElementById('IndividualPageContent_hidden').value = 'Your value here';

Related

Clear Asp.Net TextBox Control on OnFocus with Jquery or Javascript

I have been scouring the interwebs and stackoverflow, but I have not come across a solution that works. I need to erase the default text from the textbox when onfocus happens. I know it is hitting onfocus because my class for text color is set in there also and the color is changing. Here's my code and what I have tried.
ASP:
<asp:TextBox ID="txtAddEditDel" runat="server" CssClass="txtAddEditDel" ></asp:TextBox>
The default text is some random instructions it populates on Page_Load.
Jquery:
$(".txtAddEditDel").focus(function () {
var selectedRoleText = $(this).find('option:selected').text();
var selectedRoleId = $(this).find('option:selected').val();
var selectedRoleIndex = $(this).find('option:selected').index();
//enable add button
enableDisableLinkButtons(true, true, true);
if (selectedRoleText == 'Create, Edit, or Delete a Role Name.') {
$(".txtAddEditDel:text").val('');
}
$(".txtAddEditDel").removeClass('placeholderText');
});
The removeClass function is hit, but my value is not cleared.
Heres what I have tried:
$(".txtAddEditDel").val('');
$(".txtAddEditDel").val("");
$(".txtAddEditDel").text("");
$(".txtAddEditDel").text == '';
$(".txtAddEditDel").text == "";
$(this).val('');
document.getElementbyId('<%= txtAddEditDel.ClientID %'>.value = "";
$(".txtAddEditDel").val(''); should work, assuming its getting there. Have you put some debugging information to check the if clause is true? It may be a better idea to check against the value of the option rather than the text, as the text could easily be misspelt or changed where as a default value will, in my experience, be '' or 0 in this scenario

Form onsubmit() does not function

I want to control my form for the required input texts, and I have made a function in javascript. But when I click the button, and I havent fill the required field nothing the message do not appear, and I can go to the other page.
the function is:
function Validate(){
// create array containing textbox elements
var inputs = [document.getElementById('firstname1')];
var error;
for(var i = 0; i<inputs.length; i++)
// loop through each element to see if value is empty
{
if(inputs[i].value == '')
{
error = 'Please complete all fields.';
alert(error);
return false;
}
}
}
and the part of form is:
<form name="password" onsubmit="return Validate()" method="post" id="password" action="#">
<input type="submit" value="Proceed" id="submit1" onclick="displayform2()" class="button" style=" margin-top: -40px;margin-left: 60%;width: 25%" disabled>
I have noticethat if I put off the onclick method in the button it works, but I should have this method at the button...How can I solve this?Please help me
function displayform2() {
/*For desktop*/
if (document.getElementById('desktop1').style.display=='block') {
document.getElementById('desktop1').style.display='none';
document.getElementById('desktop2').style.display='block';
document.getElementById('desktop3').style.display='none';
}
/*For mobile*/
if (document.getElementById('mobile1').style.display=='block') {
document.getElementById('mobile1').style.display='none';
document.getElementById('mobile2').style.display='block';
document.getElementById('mobile3').style.display='none';
}}
It opens another form in the page...so when I click the button the first form dissapeared and the second form is displayed
You have this: var inputs = [document.getElementById('firstname1')];
Then you try to loop through that. I'm betting firstname1 is a field, so it's either null (if that field doesn't exist) or an array with only one element (the field). It looks like you are trying to check all required fields, so that won't work.
I'm not 100% what you ultimately want to do, but it will likely be much easier if you use a framework like jQuery; otherwise, you are going to have to do some complicated case-handling for different browsers.
Nowhere in your code do you call submit. That is why the function in the onsubmit handler is not triggered. If you want the button to submit the form, it would need to be a submit button.
Your example is a little unclear. For example, you are trying to validate whether a value has been entered into the input "firstname1", but you don't have markup for that element in your HTML.
I suspect what you are trying to do is to validate whether the form has been filled out or not. Something like the following (which validates input "firstname1") will do the job:
$(document).on("click", "#submit1", function(){
if($("#firstname1").val() == "" || $("#firstname1").val() == null){
alert("Please complete all fields.");
}
});
Working example here
The above requires jQuery, but can also be converted into vanilla JavaScript.
Load the jQuery library in the "head" section of your document by including the following code:
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>

Unable to update the form object which is a part of Arraylist through Javascript

I need to update an attribute in formBean which is part of ArrayList in the formBean when user checks or unchecks a checkBox.
The value of the attribute is by default set to "on" in the formBean before the page loads.
When user unchecks I am trying to make the value as "off".
I am able to see the value changed to "off" using firebug debugger, but in submit the value of the form object is remaining "on" always.
My JSP code is below. Please let me know if I am setting the value in a wrong way.
Struts application
Display Logic in JSP:
<input type="checkbox"
name="importedFiles[<c:out value='${stts.count - 1}'/>].importEnabled"
id="importedFiles[<c:out value='${stts.count - 1}'/>].importEnabled"
onClick="replicateCheckbothis, <c:out value='${stts.count - 1}'/> )"
<c:if test="${importedFiles.importEnabled != null}">checked</c:if> />
We are trying to change the value of importEnabled which is part of arrayList importedFiles in maintainDownloadForm during submit via JS.
Please find below the logic used:
function checkSelectedAndImport()
{
var anyClicked = "none";
for(var i = 0; i < <c:out value='${maintainDownloadForm.importedFileLength}' />; i++)
{
var element = document.getElementById("importedFiles[" + i + "].importEnabled");
if(element != null)
{
if(element.checked)
{
anyClicked = "true";
element.setAttribute('value', 'on'); alert('Selected--->'+element.getAttribute('value'));
}
else
{
element.setAttribute('value', 'off');
alert('Not Selected--->'+document.getElementById("importedFiles[" + i + "].importEnabled").value);
}
}
}
if(anyClicked != "none")
{
submitDGForm(getVMWareForm(),'saveImport');
}
else
{
alert("No rows have been selected for import. Please select data to import. To cancel the import, click on cancel.");
}
}
In the above logic we are able to go into else loop when user unchecks and print the alert as expected but the same is not getting updated with the form attribute importEnabled as it is always remaining "on" as it was the case before the page loaded.
Please let me know if there is any problem with the coding logic and also a fix for the same as it would be very helpful.
Unfortunately I think you can't. The solution I use is to keep an array of Strings (String[]) in the form and use javascript to add (orremove) some hidden inputs to the HTML DOM all with the ame of the Form string array. Those hidden inputs has a value that allows me to uniquely identify which chekboxes are selected by the user.

jsp pass variables between two pages

In my main jsp page, I have something like
<%# include file="../customParametersHorizontal.jsp" %>
<tr>
<td align="center" class="ReportParamsGenerateButtonCell">
<html:submit onclick="if(preGenerateCriteria()){return true;} else {return false;}">Generate</html:submit>
</td>
</tr>
Within customParametersHorizontal.jsp, there is another include for dateSelection1.jsp, which validates date and time set on the form.
<script>
function validateHHMM(inputField, message) {
var isValid = /^(0?[1-9]|1[012])(:[0-5]\d) [APap][mM]$/.test(inputField);
if (isValid) {
}else {
alert("Time must be entered in the format HH:MM AM/PM");
}
return isValid;
}
</script>
So, within dateSelection1.jsp, I tried to disable the button in the main jsp using :
document.form1.ReportParamsGenerateButtonCell.disabled= true;
But, I get an error saying object is null or not defined.
Is there anyway, I can set a var, so that it can be chacked by the main form and disable the button accordingly?
Here's a way to do it, retaining the <html:submit> tag, and without introducing jQuery: First, add the styleId attribute so that your button has an HTML ID you can grab onto:
<html:submit styleId="my_submit" onclick="if(preGenerateCriteria()){return true;} else {return false;}">Generate</html:submit>
Next, use the ID to get the element of the DOM and disable it:
var elt = document.getElementById("my_submit");
elt.disabled = true;
Update
If I understand the original question correctly, main.jsp includes customParametersHorizontal.jsp, whici includes dateSelection1.jsp. So the three scripts are rendering just one HTML page, hence one document object.
I only see (partial) code for one <form> on the HTML page. Even if you do have more than one form, .getElementById() works across all DOM elements in all forms, as opposed to the document.form1 style of accessing elements.
Be sure that you call validateHHMM() at the appropriate point to enable/disable your submit button, and make sure that the button is re-enabled once the user corrects his input to make it valid.
document.form1.ReportParamsGenerateButtonCell will return null or error unless you have the elements with name attribute set to form1 and ReportParamsGenerateButtonCell like the example bellow:
<form name="form1">
<input type="submit" name="ReportParamsGenerateButton" value="Generate" />
</form>
This way you could do document.form1.ReportParamsGenerateButton.disabled = true without problem.

Div is hidden but again showed up

I have a situation where I have no of Divs on my page , based upon the autorization I want to hide show the data in those Divs , Problem is Divs are not Hidden ,this is my client script code.
function ShowDiv(obj, condition) {
var dataDiv = document.getElementById(obj);
//alert(obj);
if (condition == true) {
dataDiv.style.display = "none";
}
else {
dataDiv.style.display = "block";
}
}
this is a sample code, when I call this code on button click
<asp:Button ID="Button1" runat="server" onclick="Button1_Click" OnClientClick="ShowDiv('Div1','True');" Text="Button" />
by this code it does hide the div but gain displays it on postback.
also can I hide no of Div on one go. i.e now I'm using getelementbyid is there any grouping alowed in HTML.
Thanks
If its based on authorization you should do it on server side only. Add runat="server" to make the divs html server controls. Also give them ID. Then in your code behind check for authorization and set the hidden property accordingly.
you pass a string to the function, but "True" != true. you have to send a boolean like so:
OnClientClick="ShowDiv('Div1',true);"

Categories

Resources