validation for drop down select in mvc - c#

In MVC form I have a drop down list which has 3 hard coded options.
<select name="ComparisonType">
<option>select ..</option>
<option>Life</option>
<option>Income</option>
</select>
On form submit values will be saved but there need to add validation for First option. If user submit form he should see message.
Please advice how to handle it. I'm not using Model here.

Modify your html as shown:
<select name="ComparisonType">
<option value="0">select ..</option>
<option value="Life">Life</option>
<option value="Income">Income</option>
</select>
Jquery :
$('form').submit(function(e){
if($('select[name=ComparisonType]').val() == "0")
{
alert("Please select any value from dropdown");
e.preventDefault(); //or return false;
}
});
Edit :-
DEMO Link

You will have to use Javascript/Jquery to achieve this functionality as you are not using a model here. So you can work around with this code which will validate your dropdown on submitting your form. Here goes :
<script type="text/javascript">
$(document).ready(function () {
$('#submitButtonId').click(function (){
var period = $("#dropdownId option:selected").text();
if (period == "select") {
//means first option is selected.
}
else {
//some other option is selected.
}
});
});

Related

DropDownListFor onchange but for same value

I'm trying to trigger an onchange event, even if the value they select is the same as before. I have tried onselect, but it does not trigger at all. And onchange does not trigger if value is the same. Is there any other patterns I could use to make this possible?
#Html.DropDownListFor(m => m.SelectedMarkdownDate, Model.ValidDatesSelectList, new{onchange = "LoadGridData(this);" })
Ended up using JQuery:
var go = false;
$('#SelectedMarkdownDate').on('click',function() {//on click
if (go) {//if go
var date = $('#SelectedMarkdownDate option:selected').text();
LoadGridData(date);
go = false;//switch off
} else { go = true; }//if !go, switch on
}).on('blur', function () { go = false; });
It looks like you answered your question, however I already made a fiddle so here it is.
you can use the onClick event with blur to tell whether or not the dropdown is open, when you select the same item it gives you an alert just to demonstrate that it recognizes the event.
https://jsfiddle.net/Anon_E_Mustard/yoxs0gk8/
<script>
var dropboxOpen = false,
oldItem = null;
counter = 0;
function onClick(e) {
if (dropboxOpen) {
if (oldItem && oldItem === e.target.value) {
alert("same selected")
}
oldItem = e.target.value;
dropboxOpen = false;
}else{
dropboxOpen = true;
}
}
function onBlur(e){
dropboxOpen = false;
}
</script>
<select onclick="onClick(event)" onblur="onBlur(event)">
<option value="volvo">volvo</option>
<option value="saab">saab</option>
<option value="opel">opel</option>
<option value="audi">audi</option>
</select>

Hide multiple Dropdown boxs using CSS for printing

On my c# mvc page, I have several dropdown boxs displayed on the page, I'm using media query to render the view differently for print and screen.
My question is that is there a way (using CSS) to hide ALL the dropdown boxs if the selected option value is "". (the text for that value is '< Select >').
So that when printing, the following will be printed:
Title
Instead of:
Title < Select >
Just want to make it more clear,
if the selected option is not "" then I do need to display it when printing,
so the following:
Title Mr
will display as the same when printing as:
Title Mr
Here is one of my dropdown:
<select id="Alias_Title" name="Alias.Title">
<option value="">< Select ></option>
<option value="1">Mr</option>
<option value="2">Mrs</option>
<option value="3">Ms</option>
</select>
Don't know whether this is achievable or not with CSS, if not, can it be done by Jquery?
Thanks
You can use $.fn.filter() to find all the select whose value is "" then add a hidden class
$(function () {
$('select').filter(function () {
return $(this).val() == "";
}).addClass('hidden');
});
Add a CSS class
.hidden{
display: none !important;
}
CSS for print (from BootStrap)
#media print {
.visible-print-block {
display: block !important;
}
}
#media print {
.hidden-print {
display: none !important;
}
}
Elements with hidden-print CSS class are not visible for printing.
Code:
<select id="Alias_Title" name="Alias.Title" class="hidden-print">
<option value="">< Select ></option>
<option value="1">Mr</option>
<option value="2">Mrs</option>
<option value="3">Ms</option>
</select>
<script type="text/javascript">
$(function () {
$('select').change(function () {
if (!$(this).val()) {
$(this).addClass('hidden-print');
} else {
$(this).removeClass('hidden-print');
}
});
});
</script>
Using jquery, you can write like this.
if($('#Alias_Title').val().length == 0) { // int value
$('#Alias_Title').hide();
}
The following solution is a combination of #Satpal and #General-Doomer 's answer to the question.
Script
<script type="text/javascript">
$(function () {
$('select').filter(function () {
return $(this).val() == "";
}).addClass('hidden-print');
$('select').change(function () {
if ($(this).val() == "") {
$(this).addClass('hidden-print');
} else {
$(this).removeClass('hidden-print');
}
});
});
</script>
CSS class:
.hidden-print{
display: none !important;
}
The filter() function works for when user try to print the page without touch any of the dropdown boxs.
The change() function works for when user try to print the page after changing the value of dropdown box.

javascript enable textbox on dropdown change event

i have five dropdown and five texbox and I'm checking on click of any of the dropdown the corresponding texbox should get enabled/disabled through javascript am using master page in asp.net
e.g: if am selecting dropdownlist1 then texbox1 should get enabled,for one textbox its working how to make it work for five textbox
function HideTextBox(ddlId) {
var ControlName = document.getElementById(ddlId.id);
if (ControlName.value == 0)
{
document.getElementById('<%=txtComment1.ClientID%>').disabled = true;
}
else {
document.getElementById('<%=txtComment1.ClientID%>').disabled = false;
}
}
You can use JQuery, it is better way. Set two class to each textBox, first .textBox1 .myTexts,
the first class must include an id for text boxes. Such as .textBox1, .textBox2 ect. And your dropbox value must include just text box's id.
$(document).ready(function(){
$("#dropBoxID").change(function(){
$(".myTexts").attr('disabled','disabled');
$(".textBox"+$(this).val()).removeAttr("disabled")
});
});
try this
http://jsfiddle.net/3WJtM/
function HideTextBox(ddlId) {
var ControlName = document.getElementById(ddlId.getAttribute("id"));
var idTxt = ControlName.getAttribute("txt");
if (ControlName.value == 0)
{
document.getElementById(idTxt).disabled = true;
}
else {
document.getElementById(idTxt).disabled = false;
}
}
on every object select, add an attribute txt with the name of te input text
In the javascript you search this textbox for enabled or disabled
for example
<select id="ddl1" txt="txt1" onchange="HideTextBox(this);" >
<option value="0">0</option>
<option value="1">1</option>
<option value="2">2</option>
</select>
<input type="input" id="txt1" disabled/>

MVC - Causing server-side page validation to fire on button click, using an AJAX call

On an app I'm working on, I have a requirement that, upon clicking a certain button, validation fires on some related textboxes; if they do not pass, nothing occurs, otherwise an action that is fired from an AJAX call occurs. This AJAX call returns some message about the success of the operation.
My partial view this is occurring in looks a bit like this:
<div>
<div id='cell-phone'>
#Model.ValidationMessageFor(x=>x.Model.CellNumber)
#Model.TextBoxFor(x=>x.Model.CellNumber)
</div>
<div id='pager'>
<!-- Ditto, only x.Model.Pager; yes, some people use pagers still. -->
</div>
<div id='page-address'>
<!-- ... x.Model.PageAddress ... -->
</div>
<div id='pager-test'>
<a href='#' id='test-pager' class='button'>Test</a>
<span id='test-result'></span>
</div>
</div>
<script>
var $cellNum = $('#cell-phone input'),
$pagerNum = $('#pager input'),
$pageAddress = $('#page-address input'),
$testPager = $('#pager-test'),
$testResult = $('#test-result');
$(document).ready(function () {
$testPager.click(function () {
pagerTest();
});
});
function pagerTest() {
var args = { address: $pageAddress.val() };
$.getJSON('#Url.Action("SendTestPage")', args, function(result) {
$testResult.html(result.Message);
});
}
</script>
...down at the server level...
public JsonResult SendTestPage(string address)
{
// SNIP: Other unnecessary details.
var result = new EmailSendResult
{
success = SendEmailMethod(address)
};
result.message = result.success
? "Message sent!"
: "Couldn't send message...";
return result;
}
....
public class EmailSendResult
{
public bool success;
public string message;
}
Question: while I am able to get the message/success values back, I also need to cause the View Model's validations to fire. I don't see how to do this using an AJAX call. My suspicion is that either A) I'm using the wrong tool for the job, or B) I'm using the right tool for one job, but I need something else. What am I missing to be able to cause validations to fire?
When you click on 'test-pager' link, the action will be called but the validation of your form doesn't trigger because your link is not a submit. If you want to validation work you must have a submit button on the form. When the user clicks it the validation will fire. So change the test-pager to something like this:
<input type="submit" id="test-pager" class="button" />
Or ( if I understand question correctly) you can bind address textbox change event and within it call testPage function.

Selecting a dropdown option from webbrowser

My goal I need to select the second option.
I've tried following approach and can't set selected value. No error shows up, the selection just doesn't happen. Being very familiar with HTML myself, I know that "selected" and 'selected="selected"' work but not sure why it's not working with my C# code. What could be wrong?
webBrowser1.Document.GetElementById("field_gender1").
Children[1].SetAttribute("selected", "selected");
The HTML is
<select name="gender1" id="field_gender1" class="select">
<option selected="selected" value="1">val1</option>
<option value="2">val2</option>
</select>
Do this from WebBrowser_DocumentComplete(...)
var htmlDocument = webBrowser1.Document as IHTMLDocument2;
if (htmlDocument != null)
{
var dropdown = ((IHTMLElement)htmlDocument.all.item("field_gender1"));
var dropdownItems = (IHTMLElementCollection)dropdown.children;
foreach(IHTMLElement option in dropdownItems)
{
var value = option.getAttribute("value").ToString();
if(value.Equals("2"))
option.setAttribute("selected", "selected");
}
}
Your code should be working if it's at a suitable place, eg: button1_Click event, webBrowser1_DocumentCompleted event, etc.

Categories

Resources