Setting the value of an input through javascript - javascript

What I'm trying to do is to change a behind-the-code C# veriable's value through javascript. My code:
HTML & JS -
function SetPostbackValues() {
document.getElementById("hiddenControl").value = "Employer";
}
function SetPostbackValues2() {
document.getElementById("hiddenControl").value = "Employee";
}
<!-- it's all inaide a form tag -->
<div id="left">
<div id="background" style="background: url(paper.gif); background-size: cover;" onclick="chg();SetPostbackValues();"><img id="man" style="right:16px;" src="https://www.watertankfactory.com.au/wp-content/uploads/2015/08/Smiling-young-casual-man-2.png" /> <div id="desc">employer</div>
</div>
<div id="trying"></div>
</div>
<div id="right">
<div id="background2" style="background: url(paper.gif); background-size: cover;" onclick="chg();SetPostbackValues2();"><img id="man2" style="right:16px;" src="https://www.watertankfactory.com.au/wp-content/uploads/2015/08/Smiling-young-casual-man-2.png" /><div id="desc2">employee</div>
</div>
</div>
<input id="hiddenControl" type="hidden" runat="server" />
C# -
protected void RegisterUser()
{
//this will run when the client presses on the 'register' button
ScriptManager.RegisterClientScriptBlock(this, this.GetType(), "alertMessage", "alert('Record Inserted Successfully')", true);
u.Email = Email.Text;
u.Password = Password.Text;
u.Firstname = Firstname.Text;
u.Lastname = Lastname.Text;
u.Gender = Gender.SelectedItem.Text;
//relevant bit:
u.Type = hiddenControl.Value;
u.Birthday = Birthday.SelectedDate.ToString("dd/MM/yyyy");
u.Country = Country.Text;
u.City = City.Text;
u.Address = Address.Text;
if (Pfp.HasFile)
{
string path = Server.MapPath("pics/");
Pfp.SaveAs(path + Pfp.FileName);
u.Pfp = Pfp.FileName;
}
s.AddClient(u);
}
So when the client first enters the site, they'll press on either background or background2 which are supposed to set a value to the hidden input, which will be used in the registration function behind the code. When I set a breakpoint, I saw the value always was just an empty string - "" throughout all my iterations (tried setting a To.String() to it in C#, and removing the "" around the value in javascript, and nothing worked). I can't figure out why it won't set a value...
Thanks for any help!

Maybe your error is in the chg() function, check it.
On the other hand you must add "" to values like this:
function SetPostbackValues() {
document.getElementById("hiddenControl").value = "Employer";
}
function SetPostbackValues2() {
document.getElementById("hiddenControl").value = "Employee";
}

Found the solution, it was the ID...
In your code, the ASP elements' ID is server-side. But when you run the code, the ASP element's ID in the client-side is different. In the javascript script, the functions are looking for an element matching the server-side ID, which they will never find, hence why the hidden element's value will stay an empty string.
TLDR - write it like this to prevent the script from detecting a (seemingly) nonexistent element in the client-side's code:
function SetPostbackValues() {
document.getElementById('<%= hiddenControl.ClientID %>').value = "Employer";
}
function SetPostbackValues2() {
document.getElementById('<%= hiddenControl.ClientID %>').value = "Employee";
}

Related

Problem showing table with Javascript condition

I have a Sprinv MVC Controller, when I submit a form I return the same page but with some objects and a String called hidden that has the value False. When I submit the form I have a window.onload function that gets the value of the this string and checks if it has the string value "false" to display 3 divs that were hidden but they didn't.
I'm struggling where is the problem because I tried a lot of things.
This is my HTML Form.
<form class="forms-sample" action="Buscar.do" method="POST" >
<div class="form-group">
<label>client:</label>
<input type="text" class="form-control" id="id" name="identificador" placeholder="DNI/NIF">
</div>
<button type="submit" class="btn btn-gradient-primary btn-gradient-aj mr-2">Obtenir Autoritzacions</button>
</form>
And here's the javascript code.
<script>
window.onload = function showTable() {
var z = ${hidden}
if(z.localeCompare("false") == 0){
var x = document.getElementById("Prueba");
var x2 = document.getElementById("Prueba2");
var x3 = document.getElementById("Prueba3");
x.style.display = "block";
x2.style.display = "block";
x3.style.display = "block";
}
}
</script>
I checked with innerHTML and the value Im getting is false so they localeCompare should do the If condition, I think the problem is in the if because i tried withouth the if and it works. Also I didnt post the divs Prueba/Prueba2/Prueba3 becasue they're not important, i mean they could be only a text.
SOLVED
I created a input type hidden with that the MVC controller returns and get it by javascript with z = document.getElementById('form1').elements[1].value . Thanks to #kemicofa for the tip.
I'm not familiar with Spring, but from the syntax in your js code, I'm assuming it replaces things with ${} with their Spring variables. I know with PHP or Handlebars, you need to provide the quotes yourself, so try replacing ${hidden} with "${hidden}".
The spring expression needs to be within single quotes;
var z = '${hidden}';

Asp radio buttons is not calling javascript function

I am working on using asp :radio buttons. I am trying to use 2 radio buttons so that if any one of them is selected then other will be unchecked. I am calling JavaScript function on change event of these buttons. That function will add some values and return the out put in the textboxes.I tried to use normal asp buttons then switch to radio button groups and now trying radio button list. need to call javascript function on radio button change event.These buttons will checked and unchecked but java script function is not returning correct values. I guess there are some naming conventions which are not correct or something is not working . looking forward for help to fix this. Neither one of these 3 way is working.
My test.aspx file contains
<asp:UpdatePanel ID="UpdatePanel1" runat="server">
<ContentTemplate>
<div class="span2">Test Career:</div>
<div class="span8">
<asp:RadioButton ID="TestCareerList" runat="server" clientmode=Static Text="MasterDegree">
</div>
</ContentTemplate>
</asp:UpdatePanel>
Document.ready function in aspx page
$(document).ready(function () {
$("input:radio").click(function ()
{
updateYears();
}
}
javascript function is:
function updateYears() {
var yrsDocTemp = parseFloat(yrsDoc);
var yrsMastTemp = parseFloat(yrsMast);
if ($("ContentPlaceHolder2_drpEmplClass").val() != "" && $("#ContentPlaceHolder2_StudentCareerList]").SelectedValue!= "") {
var updateValue = 0;
//Get EmplCalss
if ($("#ContentPlaceHolder2_drpEmplClass").val() == "GA") {
updateValue = updateValue + 1;
}
else if ($("#ContentPlaceHolder2_drpEmplClass").val() == "GAF" || $("#ContentPlaceHolder2_drpEmplClass").val() == "GAP") {
updateValue = updateValue + .5;
}
if ($("#ContentPlaceHolder2_Career").Text =="DoctoralDegree")
{
yrsDocTemp = yrsDocTemp + updateValue;
}
else if ($("#ContentPlaceHolder2_Career").Text == "MastersDegree") {
yrsMastTemp = yrsMastTemp + updateValue;
}
}
//Update the fields
$("#ContentPlaceHolder2_drpYearsDoctoral").val(yrsDocTemp);
$("#ContentPlaceHolder2_drpYearsMasters").val(yrsMastTemp);
}
I am calling this function under document.ready function like this-
$("input:RadioButtonList[ID=^TestCareerList").change(function(){
updateYears();
});
$("#ContentPlaceHolder2_drpEmplClass").change(function () {
updateYears();
});
When I debug the javascript code I see the names of buttons have been changed.
<tr>
<td>
<input id="ContentPlaceHolder2_TestCareerList_0" type="radio" name="ctl00$ContentPlaceHolder2$TestCareerList" value="MastersDegree" />
<label for="ContentPlaceHolder2_TestCareerList_0">Master</label>
</td>
<td><input id="ContentPlaceHolder2_TestCareerList_1" type="radio" name="ctl00$ContentPlaceHolder2$TestCareerList" value="DoctoralDegree" />
<label for="ContentPlaceHolder2_TestCareerList_1">Doctoral</label>
</td>
</tr>
Kindly looking for help.
This is trying to bind to your server-side elements:
$("input:RadioButtonList[ID=^TestCareerList")
But JavaScript has no knowledge of the server-side code. It only operates on the client-side code. And, as you've noticed, your client-side HTML is different. So your JavaScript needs to target that code. Something like this:
$("input:radio[ID=*TestCareerList")
The same would be true for any other selectors you have. As you're discovering, WebForms controls are famously not great for finely controlling your client-side code. ASP.NET MVC makes this a lot easier, but may be a pretty fundamental shift for what you're doing.
One thing that may help is setting your ClientID property on some controls to Static. Take care when doing this however and debug your HTML accordingly, because if you end up with repeated id values in your HTML then it's invalid and the behavior of the JavaScript when selecting on that id would be undefined.

How to invoke a onclick event on specific dynamic button on javascript

I am working on a usercontrol file which contains a textbox and a button.
The control renders multiple records on one page and hence creating and rendering the textboxes and buttons dynamically.
I am trying to invoke a javascript function to validate whether the textbox has value. My problem is I am not able to determine which button is being clicked as it is dynamically created. (As I am integrating this control in parent page gridview and hence it becomes dynamic.)
Please advise community. What I am assuming is I am not able to set the index to the button Id I am retrieving before calling the closure.
I tried following few links available on this website but finally I have post my issue here to seek specific answer.
Below is my code snipeet.
HTML:
function validateSubmit() {
var btn = document.getElementsByClassName('frmBtn').length;
var btnId = document.getElementById('<%=commentSubmitButton.ClientID%>').id;
for (var j = 1; j <= btn; j++) {
(function(j){
btnId[j].onclick = function(){
alert('INSIDE CLICK');
var e = document.getElementsByClassName('frmTextBox')[j].value;
if (e == '') {
document.getElementsByClassName('lbl')[j].style.display = 'block';
}
}
})(j);
}
}
<div class="frmContent">
<p style="float: right; padding-top: 2em;">
<asp:Button ID="commentSubmitButton" runat="server" Text="Submit" CssClass="frmBtn" OnClientClick="validateSubmit(this);" />
</p>
<p>
<label for="txtComment" class="frmLabels">
Type Comment Here
<label id="lblStar" class="lbl" style="display:none;color:red;">*</label>
</label>
<asp:TextBox ID="txtComment" runat="server" Height="60" Width="75%" TextMode="MultiLine" CssClass="frmTextBox" ></asp:TextBox>
</p>
</div>
JAVASCRIPT:
Finally I figured it out.
I wonder why I kept inclining toward conventional JavaScript approach when such things can be achieved easily with so nice and so advanced jquery. I observed few concepts on jquery and it helped me made this little thing work in very few lines. Here is the relevant code I wrote with jquery.
It is working now satisfactorily. Thank you all.
jquery code
function validateSubmit(btnid)
{
//debugger;
var txtbox = $(btnid).parent().parent().find('.frmTextBox')[0];
var lblRequired = $(btnid).parent().parent().find('.lbl')[0];
if (txtbox.value == '') {
lblRequired.style.display = 'block';
event.preventDefault();
} else {
lblRequired.style.display = 'none';
}
}

Javascript is not working innerhtml

I have simple javascript. I just need to get a date from a textbox and pass to label for other purpose. But here is the problems. I able to alert the that get from textbox but when i try to load it into label. It show empty.
function get_WlcData() {
if ($('#DropDownList1').val() == 'Required') {
document.getElementById("wlcboard").style.display = '';
} else {
document.getElementById("wlcboard").style.display = 'none';
}
var x = document.getElementById("reservation").value;
alert(x);
document.getElementById("lblreserve").innerHTML = "testing";
document.getElementById("lblreserve1").innerHTML = "testasdad";
}
Here is the HTML
<input type="text" name="reservation" id="lblreserve" class="form-control col-md-7 col-xs-12" />
<asp:Label ID="lblreserve1" runat="server" CssClass="labelForm" Visible="False"></asp:Label>
The only thing that comes to mind is that your referencing an ID that doesn't exist
var x = document.getElementById("reservation").value;
In this code you're looking for the value of something with id="reservation" but that element does not exist in the HTML you have provided. Would that not be getElementById("lblreserve") - as this is the ID of the input element?
It also may not be showing because your label is set to Visible="False", meaning the value might be setting but it doesn't appear because it's hidden from view.
first you have to show the hidden label and then write text to that label
document.getElementById("lblreserve").style.display= "inline";
document.getElementById("lblreserve").innerHTML = "testing";
writing to textbox value using
document.getElementById('lblreserve').value='new value';

How to return a variable from a javascript function into html body

I am still new to javascript, and I am trying to get a function to return a variable using html & javascript. Basically the function should just return whichever radio button that the user clicks on, although at the moment I don't see anything being returned at all.
The function is here:
<script type="text/javascript">
function GetSelectedItem() {
var chosen = ""
len = document.f1.r1.length
for (i = 0; i <len; i++) {
if (document.f1.r1[i].checked) {
chosen = document.f1.r1[i].value
}
}
}
return chosen
</script>
And then in the html section I have these radio buttons, and my attempt to get the variable "chosen" output to the screen.
<form name = f1><Input type = radio Name = r1 Value = "ON" onClick=GetSelectedItem()>On
<Input type = radio Name = r1 Value = "OFF" onClick =GetSelectedItem()>Off</form>
<script type ="text/javascript">document.write(chosen)</script>
At the moment nothing seems to be getting returned from the function (although if I output the variable 'chosen' inside the function then it is working correctly.
Thanks in advance!
Here's a little simpler approach.
First, make a few corrections to your HTML, and create a container to display the output:
<form name = "f1"> <!-- the "this" in GetSelectedItem(this) is the input -->
<input type = "radio" Name = "r1" Value = "ON" onClick="GetSelectedItem(this)">On
<input type = "radio" Name = "r1" Value = "OFF" onClick ="GetSelectedItem(this)">Off
</form>
<div id="output"></div>
Then change your script to this:
<script type="text/javascript">
// Grab the output eleent
var output = document.getElementById('output');
// "el" is the parameter that references the "this" argument that was passed
function GetSelectedItem(el) {
output.innerHTML = el.value; // set its content to the value of the "el"
}
</script>
...and place it just inside the closing </body> tag.
Click here to test a working example. (jsFiddle)
document.write takes a string, and outputs it as part of the HTML. This is not a live value that updates when the variable pointing at the string is updated.
For that, you will need to perform DOM manipulation.
Change your JavaScript function to something like that:
<script type="text/javascript">
function GetSelectedItem() {
len = document.f1.r1.length;
for (i = 0; i <len; i++) {
if (document.f1.r1[i].checked) {
document.getElementById('test').textContent = document.f1.r1[i].value;
}
}
}
</script>
And then in the body:
<div id="test"></div>
As I put in the post. Using JQuery would make your life easy for this kind of task (and many others for the matter). The really nice thing about JQuery is that it often makes your JavaScript syntax much easier then you can learn the nitty gritty details of javascript as you go.
First, add the following script tag into your html page
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.4.4/jquery.min.js" type="text/javascript"></script>
Now you have the JQuery API
Then you could rewrite the function like this.
function GetSelectedItem(btnRadio)
{
var jqElem = $(btnRadio);
$('#output').html(jqElem.attr('value')); //attr('<name of attributre'>) gets the value of the selected attribute
}
Your html would look like this
<form name = "f1">
<input type = "radio" name = "r1" value = "On" onclick="GetSelectedItem(this)">On
<input type = "radio" name = "r1" value = "Off" onclick ="GetSelectedItem(this)">Off
</form>
<div id="output">
</div>
More or less, the .html() can both get and set the html of the selected element. So we are just simply inserting the value into the div tag.

Categories

Resources