Get Checked RadioButtons using JavaScript - c#

so I’m trying to build a win 8 app, which includes a WebView. The WebView contains the HTML code (+JavaScript) below.
<!DOCTYPE HTML PUBLIC " -//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<?xml version='1.0' encoding='UTF-8' standalone='yes'?>
<html>
<head>
<meta http-equiv='Content-Type' content='text/html; charset=utf-8' >
<script type='text/javascript'>
function get_radio_value()
{
for (var i=0; i < document.myForm.frage1.length; i++)
{
if (document.orderform.frage1[i].checked)
{
var rad_val = document.myForm.frage1[i].value;
return rad_val;
}
}
}
</script>
<title>Kundenfragebogen</title>
</head>
<body>
<h1>Kundenfragebogen</h1>
<div id='myDiv'>Hello</div>
<form name='myForm' action=''>
<table border='2'>
<tr>
<td></td>
<td>sehr gut</td>
<td>gut</td>
<td>schlecht</td>
</tr>
<tr>
<td>Wie geht es Ihnen?</td>
<td><input type='radio' name="frage1" value='1'/>Mir ging es noch nie besser!</td>
<td><input type='radio' name="frage1" value='2'/>Es geht mir so wie immer.</td>
<td><input type='radio' name="frage1" value='3'/>Heute geht einfach gar nichts…</td>
</tr>
<tr>
<td>Können Sie Auto fahren?</td>
<td><input type='radio' name="frage2" value='1'/>Ja</td>
<td></td>
<td><input type='radio' name="frage2" value='3'/>Nein</td>
</tr>
<tr>
<td>Möchten Sie unseren Newsletter abonnieren?</td>
<td><input type='radio' name="frage3" value='1'/>Ja</td>
<td></td>
<td></td>
</tr>
</table>
<input type='button' value='Formular absenden' onclick="return get_radio_value()"/>
</form>
</body>
</html>
So the html contains some radio buttons and a button. I’ve used JavaScript ~2 years ago (just a little), so I don’t really know how to write the exact code. I’ve found something on the internet, but it doesn’t do what I want. I want to have the following:
The user can check the RadioButtons. When the user clicks the Button, the JavaScript function should return all the checked radio buttons (I only need to know which RadioButton is checked).
Since I know the name of the RadioButtons in my Windows 8 App, I can do the following:
var object = WebView.InvokeScript("JavaScriptFunctionNAME", NameOfRadiobutton);
So the WebView invokes the script and should get as a return the VALUE of the RadioButton, which is checked.
“JavaScriptFunctionNAME” = name of the function in Javascript
NameOfRadiobutton = the name of the RadioButton as a parameter (for example “frage1”).
Currently I’m returning the value of the radiobutton, which is checked in the RadioGroup “frage1”. How can I check every RadioButton by it’s parameter? By this I mean I have a parameter “frage1” and return the value of the checked RadioButton. After this, I call the function again with the parameter “frage2” and return the checked RadioButtons value. Could anyone help me out with the JavaScript-function?

Radiobuttons are grouped by their name property. You can get a collection of radiobuttons using document.getElementsByName and look at the checked status of each, for example: -
function FindChecked() {
var elements = document.getElementsByName("frage1")
for (var i = 0; i < elements.length; i++) {
if (elements[i].checked) {
return elements[i].value;
}
}
}
Will return the value of the checked radiobutton within its group.
jsfiddle example
Edit: To pass the group name from your C# code to this function you could do: -
public class YourClass
{
public string GroupName { get { return "frage1"; } }
}
And then the javascript function would become:
function FindChecked() {
var elements = document.getElementsByName('<%= this.GroupName %>')
for (var i = 0; i < elements.length; i++) {
if (elements[i].checked) {
return elements[i].value;
}
}
}

try this , This will return the checked name of radio buttons
<script type='text/javascript'>
function get_radio_value()
{
var nameArry = [];
var allInputs = document.myForm.getElementsByTagName('input');
for (i = 0; i < allInputs.length; i++) {
if (allInputs[i].type == 'radio' && allInputs[i].checked ) {
nameArry.push(allInputs[i].name);
}
}
alert(nameArry)
}
</script>

Related

Why is my Blazor input field saying index out of bounds when I have for loop ensuring not out of bounds? [duplicate]

This question already has an answer here:
Calling function from generated button in Blazor [duplicate]
(1 answer)
Closed 2 years ago.
I try to create the user management in blazor.
The check box is check/uncheck when I click on it. but when It showed index out of bound. I don't know what went wrong. just try with blazor wasb. please help check this. it is just a basic component but somehow I don't get used to its usage yet.
I try to create the user management in blazor.
The check box is check/uncheck when I click on it. but when It showed index out of bound. I don't know what went wrong. just try with blazor wasb. please help check this. it is just a basic component but somehow I don't get used to its usage yet.
#page "/manageuserrole/{userId}"
#inject HttpClient client
#inject IJSRuntime js
#inject NavigationManager uriHelper
<h3>User Roles</h3>
#if (manageUserRolesDto == null)
{
<text>Loading...</text>
}
#*else if (manageUserRolesDto.Length == 0)
{
<text>No Records Found.</text>
}*#
else
{
<EditForm Model="#manageUserRolesDto" OnValidSubmit="#UpdateUserRoles">
<table class="table table-striped">
<thead>
<tr>
<th>Role</th>
<th>Status</th>
</tr>
</thead>
<tbody>
#for (int i = 0; i < manageUserRolesDto.UserRoles.Count(); i++)
{
<tr>
<td>#manageUserRolesDto.UserRoles[i].RoleName</td>
<td>
<div class="form-check m-1">
<input type="checkbox"
#bind="#manageUserRolesDto.UserRoles[i].Selected"
/>
</div>
</td>
</tr>
}
</tbody>
</table>
<button type="submit" class="btn btn-success">
Submit
</button>
</EditForm>
}
#code {
[Parameter]
public string userId { get; set; }
ManageUserRolesDto manageUserRolesDto { get; set; }
protected override async Task OnInitializedAsync()
{
manageUserRolesDto = await client.GetFromJsonAsync<ManageUserRolesDto>("api/userroles/" + userId);
}
private void checkUserRole(int i)
{
manageUserRolesDto.UserRoles[i].Selected = !manageUserRolesDto.UserRoles[i].Selected;
}
async Task UpdateUserRoles()
{
await client.PutAsJsonAsync("api/userroles/" + userId, manageUserRolesDto);
uriHelper.NavigateTo("user");
}
async Task ManagePermission(string roleId)
{
}
}
#for (int i = 0; i < manageUserRolesDto.UserRoles.Count(); i++)
{
int copy = i;
<tr>
<td>#manageUserRolesDto.UserRoles[i].RoleName</td> <-- this 'i' is OK
<td><div class="form-check m-1">
<input type="checkbox"
#bind="#manageUserRolesDto.UserRoles[copy].Selected" <-- i is not OK
/>
</div></td>
</tr>
}
The #bind is compiled to a lambda function that captures the variable.
Another option is to use a foreach() { } instead of a for() { }

Calling jquery in default.aspx

I am new to asp.net, I am trying to add a field "Experience", when user adds company name, from date and to date. for that I am using a , now for that I am using jQuery. to add new columns dynamically i have written the jQuery function, but i am not getting where to add those function, when i run only single column is coming.Please help out how to add jQuery code into ASP.NET below is my function
var $lastChar =1, $newRow;
$get_lastID = function(){
var $id = $('#experience_table tr:last-child td:first-child input').attr("name");
$lastChar = parseInt($id.substr($id.length - 2), 10);
$lastChar = $lastChar + 1;
$newRow = "<tr> \
<td><input type='text' name='company_name_0"+$lastChar+"' maxlength='255' /></td> \
<td><input type='text' name='from_0"+$lastChar+"' /></td> \
<td><input type='text' name='to_0"+$lastChar+"' /></td> \
<td><input type='number' name='Total_exp_0"+$lastChar+"' maxlength='11' /></td> \
<td><input type='text' name='edit_0"+$lastChar+"' maxlength='255' /></td> \
<td><input type='button' value='Delete' class='del_ExperienceRow' /></td> \
</tr>"
return $newRow;
}
}
$('#add_ExperienceRow').live("click", function(){
if($('#experience_table tr').size() <= 9){
$get_lastID();
$('#experience_table tbody').append($newRow);
} else {
alert("Reached Maximum Rows!");
};
});
$(".del_ExperienceRow").live("click", function(){
$(this).closest('tr').remove();
$lastChar = $lastChar-2;
});
Wrap your code into this function and script tag
<script src="Script/jquery-version.js" type="text/javascript"></script>
<script type="text/javascript">
$(document).ready(function() {
//Your code goes here
});
</script>
You should also change that .live event handler to .on if you are using recent jQuery version.

How to handle checkbox item when using FormCollection using same name in asp.net mvc?

I have to get the checkbox form collection as bool value array to insert into bit datatype column in SQL Server. I tried the below thing with partial luck.
If all the checkboxes are checked, It is working fine. But If some left as unchecked only the checked items are in array. So the index varies and could not identify which belongs to which record?
Please help me.
string[] names = Students["name"].Split(char.Parse(","));
string[] dnos = Students["dno"].Split(char.Parse(","));
string[] adds = Students["address"].Split(char.Parse(","));
string[] actives = Students["active"].Split(char.Parse(","));
for (var i = 0; i < names.Length; i++)
{
student stds = new student();
stds.name = names[i];
stds.dno = dnos[i];
stds.address = adds[i];
if (actives[i] == "on")
stds.active = true;
else
stds.active = false;
db.students.AddObject(stds);
}
db.SaveChanges();
HTML:
#model DynamicAddition.DAL.student
#{
ViewBag.Title = "Create";
}
<h3>Create</h3>
<script src="#Url.Content("~/Scripts/jquery.validate.min.js")" type="text/javascript"></script>
<script src="#Url.Content("~/Scripts/jquery.validate.unobtrusive.min.js")" type="text/javascript"></script>
<form id="formstudent" method="post">
<table id="formTable">
<thead>
<tr><th>Name</th><th>D. No</th><th>Address</th><th>Active</th><th>Add New</th></tr>
</thead>
<tbody>
<tr>
<td><input type="text" name="name" /></td>
<td><input type="text" name="dno" /></td>
<td><input type="text" name="address" /></td>
<td><input type="checkbox" name="active" /></td>
<td><b>Add new</b></td>
</tr>
</tbody>
</table>
<p><input type="submit" value="Create" /></p>
</form>
<div>
#Html.ActionLink("Back to List", "Index")
</div>
<script src="../../Scripts/jquery-1.5.1.js"></script>
<script language="javascript" type="text/javascript">
function addRow() {
$('#formstudent tbody tr:first').clone().find("input").each(
function () {
$(this).val = '';
}).end().appendTo("#formTable");
}
</script>
i stumbled to the same problem while creating a dynamic form.
going by the html standards there are some controls that are posted back and some that are not. So a checkbox that is not checked or an input that is disabled isnt posted back to the server on a form postback.
The normal practive to handle these situations is to make a hidden input with the default value in you case since the default value is false make a input
#Html.Hidden("name1",..)
and set the value as false
then using the same name as of this input make a checkbox
#Html.Checkbox("name1", ..)
by doing this even if the checkbox isnt checked the value of the hidden input will be posted back to the server and you will get a valid false value.
**Note :- Asp.net MVC uses same trick whenever is needs a value postback.
**Note:- there is already an answer depicting this nicely how to POST/Submit an Input Checkbox that is disabled?

Validating a .NET 2.0 form with JQuery Validate() issues

I am trying to validate a form in .NET 2.0 using the JQuery Validate() plug-in and it’s not working. I know my Jquery code is working as I set up functions to clear the default text of a text field on focus() and that works as expected.
The form.validate() method never seems to get called as I have alert() calls in a custom validation method that work in a separate HTML test page but never fire when integrated into the .NET page.
Could this be because the whole page is treated like a form in .NET? If I want to override the default submit action and add some client side validation, how can I do this or can I only validate the form in the code behind? Thanks.
my script:
<script src="js/jquery.validate.min.js" type="text/javascript"></script>
<script src="js/additional-methods.js" type="text/javascript"></script>
<script src="js/jquery.maskedinput.js" type="text/javascript"></script>
<script type="text/javascript">
$(document).ready(function() {
jQuery.validator.addMethod("checkfields", function(value, element) {
if ($("#from_date").val() == "" && $("#to_date").val() == "" && $("#last_name").val() == "") {
return false;
}
}, "Please enter either a last name, from date or to date.");
$("input.from_date").mask("99/99/9999");
$("input.to_date").mask("99/99/9999");
$("#searchForm").validate({
errorElement: "span",
errorContainer: $("#error"),
errorPlacement: function(error, element) {
error.appendTo(document.getElementById("error"));
},
success: function(label) {
$("#searchForm").submit();
},
rules: {
last_name: "checkfields"
}
});
$("#from_date").focus(function() {
if ($("#from_date").val() == "mm/dd/yyyy") {
$("#from_date").val("");
}
});
$("#from_date").blur(function() {
if ($("#from_date").val() == "") {
$("#from_date").val("mm/dd/yyyy");
}
});
$("#to_date").focus(function() {
if ($("#to_date").val() == "mm/dd/yyyy") {
$("#to_date").val("");
}
});
$("#to_date").blur(function() {
if ($("#to_date").val() == "") {
$("#to_date").val("mm/dd/yyyy");
}
});
});
</script>
And the form:
<form action="search.spax" id="searchForm" name="searchForm" method="post">
<div id="error" style="display:none;">
<span></span>.<br clear="all"/>
</div>
<table width="520" border="0" cellspacing="0" cellpadding="0" class="obit_form">
<tr align="left">
<th><label for="last_name">Last Name</label></th>
<th></th>
<th><label for="from_date">From</label></th>
<th><label for="to_date">To</label></th>
<th></th>
</tr>
<tr align="left">
<td><input type="text" id="last_name" class="required date" name="last_name" value="" style="width:135px;" /></td>
<td>and/or</td>
<td><input type="text" id="from_date" class="required date" name="from_date" value="mm/dd/yyyy" style="width:75px;" /></td>
<td><input type="text" id="to_date" class="required date" name="to_date" value="mm/dd/yyyy" style="width:75px;" /></td>
<td><input type="submit alt="Search" title="Search" value="Search" name="submitButton" id="Submit2" /></td>
</tr>
</table>
</form>
You're doing something like this?
$(document).ready(function() {
$('#aspnetForm').validate({
rules: {
ctl00$chMain$tbLoginEmail: {
required: true,
email: true
},
...
I know hard-coding the id isn't ideal, but you get the picture.

Can I make one row show at a time in a table?

I have a javascript function that toggles the display for rows in a table. The dilemma is that I would like to display one row at a time. What is a neat way to do this?
function optionSelected() {
var optionSelect = document.getElementById('ddlSelect');
var strTest = optionSelect.options[optionSelect.selectedIndex].value;
var rowHeader = document.getElementById(strTest);
var row = document.getElementById(strTest);
if (rowHeader.style.display == '') {
rowHeader.style.display = 'none';
row.style.display = 'none';
}
else {
rowHeader.style.display = '';
row.style.display = '';
}
}
<select id="ddlSelect" onchange="optionSelected()">
<option value="optionA">A</option>
<option value="optionB">B</option>
<option value="optionC">C</option>
<option value="optionD">D</option>
</select>
<table id="tableList">
<tr id="optionA"><td>DisplayA</td></tr>
<tr id="optionB"><td>DisplayB</td></tr>
<tr id="optionC"><td>DisplayC</td></tr>
<tr id="optionD"><td>DisplayD</td></tr>
</table>
simple with jquery
$('tr').hide();
$('#'+strTest).show();
This is your vanilla Javascript solution (although I'd rather go with jQuery):
function optionSelected() {
var sel = document.getElementById('ddlSelect');
for (var i=0; i<sel.options.length; i++) {
document.getElementById(sel.options[i].value)
.style.display = sel.options[i].selected ? '' : 'none';
}
}​
Also, if you want to initialize your display, you should call optionSelected() once in an onLoad handler.
Instead of looping on DOM nodes, you can change style rules and use the speed of the CSS selectors instead.
Here is an example to show one line at a time and stay.If you want to remove them at each selection you can clear the style each time you make a selection.
<body>
<style id="styles">
table tr{
display:none;
}
</style>
<select id="ddlSelect" onchange="optionSelected()">
<option value="optionA">A</option>
<option value="optionB">B</option>
<option value="optionC">C</option>
<option value="optionD">D</option>
</select>
<table>
<tr id="optionA"><td>DisplayA</td></tr>
<tr id="optionB"><td>DisplayB</td></tr>
<tr id="optionC"><td>DisplayC</td></tr>
<tr id="optionD"><td>DisplayD</td></tr>
</table>
<script>
function optionSelected() {
var optionSelect = document.getElementById('ddlSelect'),
styles = document.getElementById('styles'),
selector = '#' + optionSelect.options[optionSelect.selectedIndex].value,
rule = 'display:block';
if(styles.styleSheet){
styles.styleSheet.cssText = selector + '{' + rule + '}';
}else{
styles.appendChild(document.createTextNode(selector + '{' + rule + '}'));
}
}
</script>
</body>

Categories