In my aspx page i am having a checkbox list ..It has binded values from a table..
I need to validate the checkbox list ..I tried the following script
var checkBoxCount = 0;
var elements = document.getElementById('<%=ChkBoxList.ClientID%>');
for(i=0; i<elements.length;i++)
{
if(elements[i].checked)
checkBoxCount++;
}
if (checkBoxCount == 0)
{
alert("Please choose atleast one");
return false;
}
But I can't get the required output, it requires to select all the values in the checkbox list ..My need is atleast only one item must be selected from the checkbox list.. Using javascript
Thanks in advance...
function readListControl()
{
var tableBody = document.getElementById('CheckBoxList1').childNodes[0];
for (var i=0;i<tableBody.childNodes.length; i++)
{
var currentTd = tableBody.childNodes[i].childNodes[0];
var listControl = currentTd.childNodes[0];
if ( listControl.checked == true )
alert('#' + i + ': is checked');
}
}
document.getElementById returns an element, not an array.
One way to do this would be to get the container and iterate through the inputs, like so:
var container = document.getElementById('<%=ChkBoxList.ClientID%>').parentNode;
var inputs = container.getElementsByTagName('input');
for (var i=0; i<inputs.length; i++) {
if (typeof inputs[i] = "checkbox") {
// statements
}
}
You may also want to qualify the inputs with more conditional statements. This just gives you the broad brush strokes.
You will have to show us your generated html.
However, here is a working example:
<html>
<body><form name="myform" method="POST" action="" onsubmit="return validate();">
<input type="checkbox" name="mybox" value="1" /> 1
<input type="checkbox" name="mybox" value="2" /> 2
<input type="checkbox" name="mybox" value="3" /> 3
<input type="checkbox" name="mybox" value="4" /> 4
<input type="checkbox" name="mybox" value="5" /> 5
<input type="submit" value="Submit Form" />
</form>
<script type = "text/javascript">
function validate() {
var checkBoxCount = 0;
for (var i = 0; i< 5; i++) {
if(document.myform["mybox"][i].checked){
checkBoxCount ++;
}
}
if (checkBoxCount == 0) {
alert ("Tick a box!");
return false;
}
return true;
}
</script>
</body>
</html>
var k=0;
var ControlRef = document.getElementById('ChkBoxList');
var CheckBoxListArray = ControlRef.getElementsByTagName('input');
for (var i=0; i
Related
I got this structure in my ViewModel
public Dictionary<string, string> Answers { get; set; }
public List<KeyValuePair<Question, List<string>>> QuestionsAndOptions { get; set; }
public TestVM()
{
Answers = new Dictionary<string, string>();
QuestionsAndOptions = new List<KeyValuePair<Question, List<string>>>();
}
QuestionsAndOptions contains Questions and its options for my Test Page im passing to VIew.
I got different question types in my project and questions with multiple answer options is one of them.
Answers contains <string,string> pairs of question IDs and user Answer for it
I got this code in my View:
#for (int i = 0; i < Model.QuestionsAndOptions.Count; i++)
{
var question = Model.QuestionsAndOptions[i];
<tr>
<td>
<b>#question.Key.Text</b>
#if (question.Key.TypeId == 1) /*single, radiobuttons*/
{
foreach (var answer in question.Value)
{
<input type="hidden" name="testVM.Answers[#question.Key.Id].Key" value="#question.Key.Id" />
<input type="hidden" name="testVM.Answers.Index" value="#question.Key.Id" />
<input type="hidden" name="testId" value="#Model.Test.Id" />
#Html.RadioButton("testVM.Answers[" + question.Key.Id + "].Value", answer, false) #answer
}
}
#if (question.Key.TypeId == 2) /*multiple, checkboxes*/
{
foreach (var answer in question.Value)
{
<input type="hidden" name="testVM.Answers[#question.Key.Id].Key" value="#question.Key.Id" />
<input type="hidden" name="testVM.Answers.Index" value="#question.Key.Id" />
<input type="hidden" name="testId" value="#Model.Test.Id" />
#Html.CheckBox("testVM.Answers[" + question.Key.Id + "].Value", answer) #answer
}
}
#if (question.Key.TypeId == 3) /*string text, textbox*/
{
foreach (var answer in question.Value)
{
<input type="hidden" name="testVM.Answers[#question.Key.Id].Key" value="#question.Key.Id" />
<input type="hidden" name="testVM.Answers.Index" value="#question.Key.Id" />
<input type="hidden" name="testId" value="#Model.Test.Id" />
#Html.TextBox("testVM.Answers[" + question.Key.Id + "].Value")
}
}
First and third If(){...} works fine and i getting what i need after submit, but for checkboxes i'm obviously geting true/false
I want checkboxes to pass strings (checked values) to Answer dictionary
If you want to bind value to checkbox,you can try to set value in checkbox,try to use the following code:
<input type="checkbox" value=#answer name="testVM.Answers[" + question.Key.Id + "].Value" />#answer
When the checkbox is checked the value of the checkbox(#answer) will be passed to action.
Long shot here, but I don't even know where to start. I maintain an MVC site. The form features several dozen drop menus. Rather than type them all out manually in the view, I'm generating them in loops.
Drop Menu options:
List<string> menuList = new List<string>() { "Correct", "Incorrect", "N/A" };
Drop Menu names (one of several lists on the page):
List<string> auditList1 = new List<string>() { "AE_FIRST","AE_SECOND","AE_THIRD", ... ,"AE_NTH"};
And here's the code to generate the drop menus:
#foreach (string audElement in auditList1)
{
string selected = "";
dropMenuCount = 0;
bool menuItemMatched = false;
<tr>
<td>#audElement: </td>
<td>
<select name="#audElement">
#foreach (string menuElement in menuList)
{
selected = "";
if (Model.AuditFound == true
&& auditElementCount < 45
&& menuElement == auditArray[auditElementCount].ToString()
&& menuItemMatched == false)
{
selected = "selected";
auditElementCount++;
menuItemMatched = true;
}
if (menuElement == null)
{
auditElementCount++;
}
if (dropMenuCount == 2 && menuItemMatched == false)
{
selected = "selected";
}
dropMenuCount++;
<option value=#menuElement #selected>#menuElement</option>
}
</select>
</td>
</tr>
}
So that's the setup. I did it this way because I'm working with an old, flat Oracle table that has 64 columns that I'm not allowed to change. Works as intended. They use the same form to enter a new audit or to review an existing audit, so that's the reason for the #selected logic.
The business unit is asking me to make a comments box mandatory if the user selects "Incorrect" for ANY of the drop menus.
<textarea name="AUDIT_COMMENTS" cols="66" rows="6">#audit_comments</textarea>
Best way to go about this?
Here is a demo,when one of the dropdownlists' values is incorrect,add required to textarea,otherwise,remove required.
View:
<form id="myform" method="post">
#foreach (string audElement in Model.auditList1)
{
<div>
<label>#audElement</label>
<select>
<option value="Correct">Correct</option>
<option value="Incorrect">Incorrect</option>
<option value="N/A"></option>
</select>
</div>
}
<textarea id="audit_comments" name="AUDIT_COMMENTS" cols="66" rows="6"></textarea>
<input type="submit" value="submit" />
</form>
<style>
.error {
color:red;
}
</style>
js:
<script src="~/lib/jquery-validation/dist/jquery.validate.min.js"></script>
<script src="~/lib/jquery-validation-unobtrusive/jquery.validate.unobtrusive.min.js"></script>
<script>
$(function () {
check();
})
$("#myform").validate();
$("select").change(function () {
check();
});
function check() {
var required = false;
$("select").each(function () {
if ($(this).val() == "Incorrect") {
required = true;
}
})
$('#audit_comments').attr('required', required);
}
</script>
result:
I'm doing a course on PluralSight but the code in the course is not complete and there is a quickedit IActionResult that I can't seem to figure out.
In my View I have the code below:
#model IList<string>
#if (Model.Count > 0)
{
<form asp-action="QuickEdit" method="post">
#for (var i = 0; i < Model.Count; i++)
{
<div class="form-group">
<label>Soup name #(i + 1);</label>
<input id="soupNames" name="soupNames" asp-for="#Model[i]" class="form-control"/>
</div>
}
<button type="submit" class="btn btn-primary">Update</button>
</form>
}
else
{
<h2>No Soups in the system</h2>
}
The Controller:
public IActionResult QuickEdit()
{
var soupNames = _soupRepository.AllSoups.Select(s => s.SoupName).ToList();
return View(soupNames);
}
[HttpPost]
public IActionResult QuickEdit(List<string> soups)
{
var soupNames = _soupRepository.AllSoups.Select(s => s.SoupName).ToList();
for (var i = 0; i < soupNames.Count; i++)
{
soupNames[i] = soups[i];
}
return View(soups);
}
Could someone help me out?
I want the values passed through replace the original values when I click the update button.
this line
<input id="soupNames" name="soupNames" asp-for="#Model[i]" class="form-control"/>
need to change to something like
<input id="#(i)_soups" name="[#(i)].soups" asp-for="#Model[i]" class="form-control"/>
you need to google model binding lists
try , it may show you the raw syntax so you can change to just input
#Html.TextBoxFor(m => #Model[i] )
this is my first post on Stackoverflow so I apologize for any errors on this post (And sorry for my English too).
I'm having a problem using C# functions on Razor. I have a form with some textboxes to fill them with data from a SQL Server database. I also have some buttons to move across the elements on the DB table (like previous, next, first...).
I'll show you the code:
#{ var codcur = "";
var descripcion = "";
var horas = "";
var tutor = "";
int pos = 0;
if(IsPost) {
pos = Convert.ToInt32(Session["position"]);
}
else {
pos = 0;
}
using(PracticaRazor2.ModeloOcupacional Contexto = new PracticaRazor2.ModeloOcupacional()) {
var registro = (from cur in Contexto.CURSOS orderby cur.COD_CUR select cur).Skip(pos).First();
codcur = registro.COD_CUR;
descripcion = registro.DESCRIPCION;
horas = registro.HORAS.ToString();
tutor = registro.TUTOR;
}
<h1>Mantenimiento cursos</h1>
<form action="~/Cursos.cshtml" method="post">
<label>Código curso:</label>
<input type="text" name="cod_cur" id="cod_cur" value="#codcur" /><br />
<label>Descripción:</label>
<input type="text" name="descripcion" id="descripcion" value="#descripcion" /><br />
<label>Horas:</label>
<input type="text" name="horas" id="horas" value="#horas" /><br />
<label>Tutor:</label>
<input type="text" name="tutor" id="tutor" value="#tutor" /><br />
<br /><br />
<input type="submit" name="first" id="first" value="|<" onclick="#first(pos)"/>
<input type="submit" name="prev" id="prev" value="<<" onclick="#prev(pos)"/>
<input type="submit" name="next" id="next" value=">>" onclick="#next(pos)"/>
<input type="submit" name="last" id="last" value=">|" />
<input type="submit" name="borra" id="borra" value="Borrar" />
<input type="submit" name="Modifica" id="mod" value="Modifica" />
<input type="submit" name="Nuevo" id="new" value="Nuevo" />
</form>
#functions{
int next(int pos) {
if(IsPost) {
pos++;
Session["position"] = pos.ToString();
}
return pos;
}
int prev(int pos) {
if(IsPost) {
pos--;
Session["position"] = pos.ToString();
}
return pos;
}
int first(int pos) {
if(IsPost) {
pos = 0;
Session["position"] = pos.ToString();
}
return pos;
}
}
}
</body>
My problem is when I click on the buttons with the onclick events, all the methods declared in "#functions" are called in reverse order, even when the page is loaded for the first time. I tried to separate them on diferent #functions, use #helper on each method instead of #functions and nothing works.
Anyone have any idea of why is this happening or knows any way to do this propely?
Thanks in advance.
Best regards.
You need to create a postback method with your controller
so lets say this is your controller you would do something like this
public ActionResult YourPageName(string NextAction)
{
if(NextAction == "next")
{
Session["position"] = (int)Session["position"] + 1;
}
elseif(NextAction == "prev")
{
Session["position"] = (int)Session["position"] - 1;
}
else
{
Session["position"] = 0;
}
return View();
}
And change your View to send the right text with your button value when its clicked on
For a project I created a new custom field type, called RadioList. This RadioList class extends the RadioButtonList class. I use repeatlayout UnorderedList.
I want to add a classname to the input tag, for example:
<input type="radio" name="rating" value="2" class="class-on-inputfield" />
The classname is added to the span arround the input tag now. I don't like it.
<span class="class-on-inputfield"><input type="radio" name="rating" value="2" class="" /></span>
The C# programcode.
List<ListItem> list = new List<ListItem>();
for (int i = 1; i <= 10; i++)
{
ListItem listItem = new ListItem()
{
Text = i.ToString(),
Value = i.ToString()
};
listItem.Attributes.Add("class", "class-on-inputfield");
list.Add(listItem);
}
this.RepeatLayout = RepeatLayout.UnorderedList;
this.items = list;
this.DataBind();
Does anyone know how I could solve this?
Thanks a lot.
Jordy
//Default.aspx
<asp:RadioButtonList ID="rbListTest" runat="server">
</asp:RadioButtonList>
//Default.aspx.cs
var liItem = new ListItem("Test", "Val1");
//Add class name to span element
liItem.Attributes.Add("class", "spanClassNameHere");
rbListTest.Items.Add(liItem);
Then add the following before the closing /asp:content tag
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<script>
$(document).ready(function () {
$('.spanClassNameHere').find('input[type=radio]').addClass('myNewInputTagClassNameHere');
});
</script>
The output should look like this:
<span class="spanClassNameHere">
<input name="ctl00$MainContent$rbListTest" class="myNewInputTagClassNameHere" id="MainContent_rbListTest_0" type="radio" value="Val1" />
<label for="MainContent_rbListTest_0">Test</label>
</span>