Check if the button has changed in Javascript? - c#

I'm trying to figure out how to get my Javascript code to check whether or not a button has been chosen. If it has, I would like to display the button's value.
I have the following HTML:
<li class="control-group">
<label for="amount" class="control-label">Select an amount</label>
<div class="controls">
<div class="btn-group radioButtons amountButtons" data-toggle="buttons-radio">
#if (Model.PresetValues.Count > 0){
foreach (int value in Model.PresetValues) {
<button type="button" data-value="#value" class="btn #(Model.chargeViewModel.ChargeAmount == value ? "active" : "")">$#value</button>
}
}
<button type="button" data-value="other" class="btn toggleDiv toggleOnce" data-toggle-id="#manualAmount">Other</button>
</div>
<input type="hidden" class="radioHidden validate required validateAmount" value="" id="amount" name="ChargeAmount">
</div>
<div class="controls hide resize" id="manualAmount">
<div class="input-prepend input-append">
<button class="btn minus" type="button"><i class="icon-minus"></i></button>
<input class="span2 plusminus" data-max="100" data-min="10" data-increment="5" data-value="25" id="manualAmountInput" type="text" value="$25" disabled>
<button class="btn plus" type="button"><i class="icon-plus"></i></button>
</div>
</div>
</li>
Those are my two options for the button and I would like to edit the following span
<span class="help-block">Your card will automatically reload $<span id="autoAmount">0</span> when your balance is lower than your reload threshold.</span>
I have the following script which I was led to believe will change the value of the span as it is clicked, but I am having a difficult time connecting them together.
<script>
javascript: void (document.getElementById("autoAmount").innerHTML = amount);
</script>
if anyone has any suggestions or ideas, it would be greatly appreciated.
Thanks!

To expand on kyllo's answer a little bit...
First you would need to bind a click event to your button. You can set it as an onClick attribute:
<input type="button" onClick="captureAmount(e); return false;">
Including the 'e' inside captureAmount will pass the click event itself over to our function, which we can use to figure out which button was clicked (if you are using this function in more than one place).
You can also use jQuery if you've included that library, to attach the function to every button on the page at once.
$('input[type=button]').click(captureAmount(e));
Or, specify buttons with a particular class..
$('input.amountBtns').click(captureAmount(e));
And your function could look a little something like this:
function captureAmount(e){
var clicked = e.target
, clickedAmount = clicked.value
, display = document.getElementById("autoAmount")
;
display.innerHTML = clickedAmount;
}

If you want the innerHTML of the autoAmount span to change when you click a button, then you would need to bind an onclick event to that button, and then when the onClick event fires, you would do document.getElementById("autoAmount").innerHTML = amount.value
for example, in the button declaration you can add
onclick="updateAmount()"
and then inside the script tags you would declare a javascript function that is called by the onclick event:
function updateAmount(){
document.getElementById("autoAmount").innerHTML = document.getElementById("amount").value
}
(Keep in mind that your "amount" input box is hidden, though.)

Related

The text displayed on my HTML button is including more than it should

Here is a reference Image
For a little bit more context I am operating in a C# ASP.NET MVC environment and I am trying to pass a value to a form via button click. For my other two values that are being assigned on the form I am using #Html.EditorFor() and #Html.RadioButtonFor() for a text box and radio button selection respectively. However since there is no #Html.ButtonFor() I am instead trying to assign the value to the form with #Html.HiddenFor() inside of an onclick. This works in terms of the functionality I want from it, but there is a weird visual issue where the symbols following the onclick are also used in the text displayed on the button, so while the button should display the text:
Save Notification
It actually displays
"> Save Notification
Here is the relevant code (with specifically the button markup at the bottom where the issue is taking place). I feel like I am missing something very obvious here and I am very new to HTML and Kendo so I am really lost as to why this is happening.
<div class="row">
<div class="col-sm-6 ref-bottom-margin">
#Html.EditorFor(model => model.SystemStatus.UniversalNotification.SystemNotification, new { htmlAttributes = new { #class = "form-control" } })
</div>
<div class="col-sm-4">
#Html.RadioButtonFor(model => model.SystemStatus.UniversalNotification.BannerSeverity, "Alert")
Alert
#Html.RadioButtonFor(model => model.SystemStatus.UniversalNotification.BannerSeverity, "Warning")
Warning
#Html.RadioButtonFor(model => model.SystemStatus.UniversalNotification.BannerSeverity, "Notification")
Notification
</div>
<div class="col-sm-2">
<button class="btn btn-primary" type="submit" value="Universal" onclick="#Html.HiddenFor(model => model.SystemStatus.UniversalNotification.BannerScope)"> Save Notification </button>
</div>
</div>
#Html.HiddenFor will generate " inside onclick attribute, and causing wrong text display
Rendered source code of the button:
<button class="btn btn-primary" type="submit" value="Universal" onclick="<input id="SystemStatus_UniversalNotification_BannerScope" name="SystemStatus.UniversalNotification.BannerScope" type="hidden" value="" />"> Save Notification </button>
Instead of using #Html.HiddenFor, you can get the value from model using #(Model.fieldname). And maybe you will want to pass the value directly into JavaScript function, like below
onclick="someFunction('#(Model.SystemStatus.UniversalNotification.BannerScope)')"

How to keep radio buttons populated after postback

I have a page that has dynamic rows that show and hide based on radio button selection. There is also validation making sure that each field (that is shown) is populated and has a valid value. When the user submits the page it validates the fields and posts back and while the text box values are stored all the radio buttons become deselected and the dynamic rows are all hidden.
I was wondering how to maintain the selection of the radio buttons and the visible/hidden fields after a postback.
<div class="form-group">
<label asp-for="HaveYouEnteredTheProperty">Have you entered the property?</label>
<div asp-for="HaveYouEnteredTheProperty" class="btn-group btn-group-toggle" data-toggle="buttons" style="width:100%">
<label style="width:50%" class="btn btn-success">
<input type="radio" name="VisitDetailsRadio" id="propYes" value="Yes"/> Yes
</label>
<label style="width:50%" class="btn btn-danger">
<input type="radio" name="VisitDetailsRadio" id="propNo" value="No" /> No
</label>
</div>
<span asp-validation-for="HaveYouEnteredTheProperty" class="text-danger"></span>
</div>
this is one of my radio buttons on the cshtml page
$("input[name=VisitDetailsRadio]").change(function () {
if ($(this).val() == "No") {
$(".VisitDetailsExpandedYes").hide();
$(".VisitDetailsExpandedNo").show();
$(".EnteredProperty").hide();
}
else {
$(".VisitDetailsExpandedYes").show();
$(".VisitDetailsExpandedNo").hide();
$(".EnteredProperty").show();
}
});
This is the jquery that shows and hides fields based on the radio button selection
if (results.IsValid)
{
_context.Results.Add(model);
_context.SaveChanges();
ModelState.Clear();
return View();
}
else
{
results.AddToModelState(ModelState, null);
return View(model);
}
and this is the validation after pressing the submit button at the end of the form.
Any help would be appreciated.
On a high level, what you need to do is the following:
Treat your CREATE view the same you would do an UPDATE view. You should add Razor syntax for any radiobuttons that should be clicked.
You should use either Razor or Javascript to figure out which dynamic contents to show or hide based on the selected radio buttons.

FormCollection missing submit button values [duplicate]

This question already has answers here:
How do you handle multiple submit buttons in ASP.NET MVC Framework?
(35 answers)
Closed 9 years ago.
This code was working at one point. I'm not sure what broke it, but basically on postback I'm looking for the existence of a submit button key in the FormsCollection. Depending on the existence, I perform different operations. The custom attribute to handle this is getting hit. When I step through it and look at the FormsCollection, I can see all key/values from the form except for the submit button which submitted the form.
Looking at the submission via Fiddler2, it doesn't even look like the submit button is being sent to the server with the rest of the values. If I put in a hidden field with the same name I am looking for (and hard coded value) I can successfully hit the "if exists" logic branch because the hidden field's value is sent to the server.
Here's my form:
#using (Html.BeginForm("Respond", "AccountInvitations", new {id = Model.Invitation.InvitationCode, ReturnUrl = Request.QueryString["ReturnUrl"] ?? string.Empty}, FormMethod.Post, new {#class = "invitation-details-form"}))
{
<div class="modal-body">
<div class="status-message info">
<i></i>
You have been invited to join <strong>#Model.Invitation.AccountName</strong>.
Create your profile below to join this account.
</div>
#Html.AntiForgeryToken()
#Html.ServerValidationSummary()
#Html.EditorFor(model => model.InvitationResponse, "InvitationResponseDto", "")
</div>
<div class="modal-footer">
<div class="button-container clearfix">
<input type="submit" name="accept" value="Accept Invitation" class="btn btn-secondary" />
<input type="submit" name="decline" value="Decline Invitation" class="btn btn-link cancel" />
</div>
</div>
}
Neither "accept" nor "decline" shows up in the FormsCollection when I press on either (the form is submitted and all fields from the editor template show, but not the submit inputs).
I do not want to handle this with javascript setting a hidden field value.
Wow, it's been a long couple nights coding. This post led me to the answer. A couple weeks back a script was added to prevent double clicking on some form entries. The form disabled the inputs immediately upon form submission. A simple setTimeout() to delay the disabling did the trick.
OR you can using
<div class="modal-footer">
<div class="button-container clearfix">
#using (Html.BeginForm("Your_ActionResult", "Your_controller"}, FormMethod.Get/Post))
{
#Html.AntiForgeryToken()
<input type="submit" name="accept" value="Accept Invitation" class="btn btn-secondary" />
}
#using (Html.BeginForm("Your_ActionResult", "Your_controller"}, FormMethod.Get/Post))
{
#Html.AntiForgeryToken()
<input type="submit" name="decline" value="Decline Invitation" class="btn btn-link cancel" />
}
</div>
</div>
you must specify the submit button that call the ActionResul method in your Controller is

C# Form Webbrowser click div

My webbrowser connects to a page, then I want it to click a div.
<div class="acceptButton state1">
<a class="buttonGreen">
<span>${$item.getAddressButtonText( $data.messageType )}</span>
</a>
</div>
The page uses jquery or something to do it all. :( and most help I found required an id, which these only have a class
<script id='messageListItem' type='text/x-jquery-template'>
<li data-messagetype="${messageType}" class="${messageType}" data-messageid="${messageId}">
<div class="messageItem">
<div class="closeButton">
<a><span>X</span></a>
</div>
<img class="friendImage" src="${senderImgUrl}" alt="${senderName}" />
<div class="messageBubble">
<div class="messageBubbleTop"></div>
<div class="messageBubbleBody">
<div class="messageBubbleContent">
{{if $data.messageImgUrl != null}}
<img class="giftImage messageImage" alt="${messageImgAltText}" src="${messageImgUrl}">
{{/if}}
<h5 class="friendName">${senderName}:</h5>
<p class="requestMessage">${message}</p>
<span class="requestDate">${timestampStr}</span>
<div class="clearFloat"></div>
</div>
</div>
<div class="messageBubbleBottom"></div>
</div>
<div class="acceptButton state1">
<a class="buttonGreen"><span>${$item.getAddressButtonText( $data.messageType )}</span></a>
</div>
<div class="clearFloat"></div>
</div>
</li>
To click the div you can run JavaScript code in the WebBrowser's DocumentCompleted event handler using Navigate():
webBrowser1.Navigate("javascript: /* your javascript code */ void(0);");
So if you have a div:
<div class="myDivClass">
...
</div>
You can trigger a click on it using:
webBrowser1.Navigate("javascript: document.getElementsByClassName('myDivClass')[0].click();void(0);"); //assuming it's first and/or only div with that class
As far as I remember, it is not possible to click a DIV. In that, if you try, the event in the DIV will not trigger. Say, if the DIVhas an onclick event, it will not trigger.
So, what you have to do, in order to get the onclick event in the DIV to trigger, is to click anything (any of the other elements) in the DIV. Let's say the DIV has an IMG element/tag: Perform a .click on that and the DIV's onclick event will be triggered. Does this make sense? So any DIV's onclick triggering is only possible through onclick event bubbling - by using the method I described above.
I am just telling you this in case you we're expecting an onclick event to run that is attached directly to the DIV. Just in case you add it in the future or you run into it later, it is important for you to understand this (even though I didn't see an onclick in your DIVtag at the moment, it's an important information to have).
Hope this helps and if you have any further questions, let me know.
I only found this through testing and it isn't really written anywhere, the same thing applies to the span tag if I remember correctly.

HTML form submit button doesn't sent data form

I use DNN and C#. I've got a form with a lot of input and select HTML tag. At the end of form there is a . When I click on it, the page is reload but when I try catch data of form (with Request.Form['formName'] or Request['form']) I've got only empty field (and if I check the value of IsPostback, it's always false). But in the form tag there is value.
FILE View.ascx
<div class="row">
<div class="col-sm-2"> </div>
<div class="col-sm-4">
<label for="formCodiceCanile">Codice Canile</label>
</div>
<div class="col-sm-4">
<input type="text" name="formCodiceCanile" ID="formCodiceCanile" value="<%=InfoScheda.CodiceCanile %>" />
</div>
<div class="col-sm-2"> </div>
</div>
OTHER FIELD (such as input text, select and radio button)
<input type="submit" name="formRegistraScheda" id="formRegistraScheda" value="Registra scheda" />
I know that I can use (and if I use it, there isn't problem because catch the value in the asp:Textbox it's a joke) but in this case I can't use them.
How can I resolve this problem?
PROBLEM SOLVED: the button doesn't do the POST because I use a field's form in the URL to observe the page status. Now I remove this control and I use the IsPostback native variable of C# and the form work!

Categories