How can I change my checkbox to radio buttons? - javascript

So, I want to change my checkbox, that has checked and unchecked state to radio buttons that say, Yes (checked) or No (unchecked).
Here's what I did for the checkbox:
In my view:
#Html.CheckBoxUi("PerpendicularCheckbox",#H.GetString("IsPerpendicular"), null, new { style = "margin-right:10px", #class = "type-style-paragraph" })
js:
$('input:checkbox[name=PerpendicularCheckbox]').on({
"change": function () {
if (getUpdate()) {
var $this = $(this);
if (($this).is(':checked'))
$("ul li button").click();
}
}
});
if (!Perpendicular) {
$("#PerpendicularCheckbox").prop("checked", false);
}
else {
$("#PerpendicularCheckbox").prop("checked", true);
}
I was wondering what would I need to change it to radio buttons, yes and no options, using html extension in asp.net mvc?
EDIT:
My loosy attempt at radio buttons:
#Html.RadioButtonForUi("PerpendicularCheckbox",#H.GetString("IsPerpendicular"), null, new { style = "margin-right:10px", #class = "type-style-paragraph" })
$('input:radio[name=PerpendicularCheckbox]').on({
"change": function () {
if (getUpdate()) {
var $this = $(this);
if (($this).is(':checked'))
$("ul li button").click();
}
}
});
RadioButtonForUi :
public static MvcHtmlString RadioButtonForUi<TModel, TProperty>(
this HtmlHelper<TModel> htmlHelper,
Expression<Func<TModel, TProperty>> expression,
string name,
bool IsEnable,
bool IsChecked,
object onchange = null,
string className = "",
bool isRequreid = true
) {etc.....}

Here is a tested sample:
<div class="form-group">
#Html.LabelFor(model => model.SaleOfPropertyPurchase, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
<div class="checkbox">
#Html.RadioButtonFor(model => model.SaleOfPropertyPurchase, true, new { id = "SaleOfPropertyPurchase-true" }) Yes
#Html.RadioButtonFor(model => model.SaleOfPropertyPurchase, false, new { id = "SaleOfPropertyPurchase-false" }) No
#Html.ValidationMessageFor(model => model.SaleOfPropertyPurchase, "", new { #class = "text-danger" })
</div>
</div>
</div>
Here is some sample jquery that reacts to the radio button click, and also sets up initial display on the form:
#Scripts.Render("~/bundles/jquery")
<script type="text/javascript">
$(function () {
$('#CurrentPropertyOwner-true').on('change', function () {
$('#CurrentProperty').show();
});
});
$(function () {
$('#CurrentPropertyOwner-false').on('change', function () {
$('#CurrentProperty').hide();
});
});
$(document).ready(function () {
var ischecked = $('#CurrentPropertyOwner-true').is(':checked')
if (ischecked == true) {
$('#CurrentProperty').show();
}
var ischecked = $('#CurrentPropertyOwner-false').is(':checked')
if (ischecked == true) {
$('#CurrentProperty').hide();
}
});
</script>

You need to render two radio buttons for the property, one with the value of "True" and the other with the value of "False" so the selected value can be bound to a boolean value
You custom html helper would need to be
namespace YourAssembly.Html
{
public static class MyHelpers
{
public static MvcHtmlString BooleanButtonsFor<TModel>(this HtmlHelper<TModel> helper, Expression<Func<TModel, bool>> expression)
{
ModelMetadata metaData = ModelMetadata.FromLambdaExpression(expression, helper.ViewData);
string name = ExpressionHelper.GetExpressionText(expression);
StringBuilder html = new StringBuilder();
// Yes button
string id = string.Format("{0}-yes", name);
html.Append(helper.RadioButtonFor(expression, "True", new { id = id }));
html.Append(helper.Label(id, "Yes"));
// No button
id = string.Format("{0}-no", name);
html.Append(helper.RadioButtonFor(expression, "False", new { id = id }));
html.Append(helper.Label(id, "No"));
// enclode in a div for easier styling with css
TagBuilder div = new TagBuilder("div");
div.AddCssClass("radiobuttongroup");
div.InnerHtml = html.ToString();
return MvcHtmlString.Create(div.ToString());
}
}
}
then add a reference to the <namespaces> section of web.config
<add namespace="YourAssembly.Html "/>
and use it in the view
#Html.BooleanButtonsFor(m => m.YourBoolProperty)

Related

How to add/remove element in list on the basis of selection of 2 dropdown list in multi select bootstrap dropdown jquery?

Hope all of you fine and doing well.
I am using multi select bootstrap drop down jquery. I am using asp.net core to populdate Listbox, its working fine for selection,select all etc.
But i want that when i select element from Dropdown A then this element must be removed from dropdown B and if i unselect element from dropdown A then it must added/show in dropdownB. And vice virsa as well, if element selected in dropdown B then this element removed from dropdownA, also if select all from dropdownA then all elements removed from dropdownB and vice virsa as well.
Hope you understand guys.
For example: If A,B,C,D values in dropdownlistA and if i select A then it must be disable or hide from dropdownB,if i select all then must remove all from dropdownB, and also vice virsa for dropdownB as well,
Note: DropdownA and DropdownB both have same number of values/elements,same text ,same value,
View
#section AddToHead{
<link rel="stylesheet" href="~/css1/bootstrap-3.1.1.min.css" type="text/css" />
<link rel="stylesheet" href="~/css1/bootstrap-multiselect.css" type="text/css" />
<script type="text/javascript" src="https://code.jquery.com/jquery-1.8.2.js"></script>
<script type="text/javascript" src="~/js1/bootstrap-2.3.2.min.js"></script>
<script type="text/javascript" src="~/js1/bootstrap-multiselect.js"></script>
}
<form class="column" asp-controller="group" asp-action="createresult" style="height:100%;" method="post">
<span class="column" style="height:50px;">
#Html.ListBoxFor(x => x.AvailablePlayers, Model.AvailablePlayers, new { id = "PlayersTeamA", onChange = "getSelectedOptions(this)", multiple = "multiple" })
#Html.ValidationMessageFor(model => model.TeamOnePlayers)
</span>
<span class="column">
#Html.ListBoxFor(x => x.AvailablePlayers, Model.AvailablePlayers, new { id = "PlayersTeamB", onChange = "getSelectedOptions(this)", multiple = "multiple" })
#Html.ValidationMessageFor(model => model.TeamTwoPlayers)
</span>
</form>
</div>
#section Scripts {
<script type="text/javascript">
$(function () {
$('#PlayersTeamA').multiselect({
includeSelectAllOption: true
});
$('#PlayersTeamB').multiselect({
includeSelectAllOption: true
});
});
function getSelectedOptions(sel) {
var idddl = sel.id;
var opts = [],
opt;
var len = sel.options.length;
for (var i = 0; i < len; i++) {
opt = sel.options[i];
if (opt.selected) {
opts.push(opt);
var idul = sel.id;
alert(idul);
var ul = document.getElementById(idul);
ul.removeChild(ul.childNodes[1]);
}
}
return opts;
}
Here is a working demo like below:
#model Players
<form class="column" asp-controller="group" asp-action="createresult" style="height:100%;" method="post">
<div id="A">
<span class="column" style="height:50px;">
#Html.ListBoxFor(x => x.AvailablePlayers, Model.AvailablePlayers, new { id = "PlayersTeamA", multiple = "multiple" })
</span>
</div>
<div id="B">
<span class="column">
#Html.ListBoxFor(x => x.AvailablePlayers, Model.AvailablePlayers, new { id = "PlayersTeamB", multiple = "multiple" })
</span>
</div>
</form>
#section Scripts {
<script src="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-multiselect/0.9.15/js/bootstrap-multiselect.min.js"></script>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-multiselect/0.9.15/css/bootstrap-multiselect.css"/>
<script>
$(function () {
$('#PlayersTeamA').multiselect({
includeSelectAllOption: true
});
$('#PlayersTeamB').multiselect({
includeSelectAllOption: true
});
});
var data = [];
$('#B option').each(function (index, item) {
data.push({ label: this.label, value: this.value });
});
$("#PlayersTeamA").change(function () {
var selectedText = $('#PlayersTeamA').val();
var newData = data;
selectedText.forEach(function (element, index, array) {
newData = newData.filter(function (el) { return el.value != element; });
});
$("#PlayersTeamB").multiselect('dataprovider', newData);
});
</script>
}
My testing model:
public class Players
{
public SelectList AvailablePlayers { get; set; }
}
public class AvailablePlayer
{
public int Id { get; set; }
public string Name { get; set; }
}
My testing controller:
[HttpGet]
public async Task<IActionResult> Index()
{
var player = new List<AvailablePlayer>()
{
new AvailablePlayer(){ Id=1,Name="aa"},
new AvailablePlayer(){ Id=2,Name="bb"},
new AvailablePlayer(){ Id=3,Name="cc"}
};
var model = new Players()
{
AvailablePlayers = new SelectList(player, "Id", "Name")
};
return View(model);
}
Result:
It appears you are using bootstrap's multiselect. In the documentation, we can see that you can configure data as follows (after executing .multiselect on particular input, as you do in your sample):
var data = [
{label: "Messi", value: "Messi"},
{label: "Ronaldo", value: "Ronaldo"}
];
$("#PlayersTeamA").multiselect('dataprovider', data);
Now, attach to 'onchange' event of #PlayersTeamA and update the available data for #PlayersTeamB, for example like this:
$("#PlayersTeamA").change(function () {
var selectedText = $(this).find("option:selected").text();
var newData = data.filter(function(el) { return el.value == selectedText; });
$("#PlayersTeamB").multiselect('dataprovider', newData);
});
You have to attach to onchange of #PlayersTeamB as well, I believe (so that it works in both directions).

How to click ActionLink automatically when the dropdown is changes?

I have one dropdown and one actionlink.
where this actionlink will be clicked automatically when the dropdown changes. How to do that?. below is my code, thanks.
#Html.DropDownListFor(model => model.PaymentCode, (List<SelectListItem>)ViewBag.JenisPembayarans, new { #class = "form-control" })
#Html.ActionLink(
"Detail",
"GetInsuranceCompany","ParamBlacklistPembayaran",
new { id = Model.PaymentCode }, new { #class = "ddlSubmit"})
Controller
public ActionResult GetInsuranceCompany( ParamBlacklistPembayaranViewModel model,string id)
{
LoadThirdPartyDDL(string.Empty, string.Empty, id);
return View("Create", model);
}
#Html.DropDownListFor(model => model.PaymentCode, (List<SelectListItem>)ViewBag.JenisPembayarans, new { #class = "form-control",#id="ddl" })
#Html.ActionLink("Detail",
"GetInsuranceCompany","ParamBlacklistPembayaran",
new { id = "PaymentCodeVal" }, new { #id="anchorclick",#class = "ddlSubmit"})
You should call click event on drop down change like this:
<script>
document.getElementById('ddl').onchange = function () {
var path = document.getElementById('anchorclick').href;
path = path.replace("PaymentCodeVal", document.getElementById('ddl').value);
document.getElementById("anchorclick").href=path;
document.getElementById('anchorclick').click();
};
</script>
#NOTE : You want get updated PaymentCode. you have to inject url to pass PaymentCode on change event.
Assign onchange event in new {} section where you can raise the event of the particular action link by using their id.
#Html.DropDownListFor(model => model.PaymentCode, (List<SelectListItem>)ViewBag.JenisPembayarans, new { #class = "form-control", #id = "MyId", onchange = "MyFunction()" })
<script type="text/javascript">
function MyFunction() {
//alert('Changed');
document.getElementsByClassName("ddlSubmit").click();
$('#YourLabelId').val('ReplaceWithThisValue');
}
</script>
References:
Handling onchange event in HTML.DropDownList Razor MVC

How to add a clear button in jquery autocomplete(mvc razor)

I have a search functionality which already works by searching the data that the user requests. I would like to add a clear button for the user to be able to clear the search bar, at the moment the user has to clear the search using the "backspace" button and press "enter to go back the page with all the data. I am a expert in front end so would appreciate some help thank you in advance.
Javascript
$(function () {
$("#SearchString").autocomplete({
source: '#Url.Action("GetUserJSON")',
minLength: 1
})
});
$(function () {
$("#SearchString").focus();
});
$(function () ) {
$("#clearbutton").click(function () {
$('#SearchString').autocomplete('close');
});
};
Razor HTML
#using (Html.BeginForm("Index", "User", FormMethod.Get, null))
{
<div class="search-wrap">
#Html.TextBoxFor(m => m.SearchString, new { id = "SearchString", #class = "lookup txt-search js-autocomplete-submit", #placeholder = "Search", #type ="search" })
#*<img src="~/Content/Images/close.png" id ="closebutton"/>*#
<button type="button" id="clearbutton">Click Me!</button>
<i onclick="submitform()" class="btn-search fa fa-search"></i>
</div>
}
C# Class where data get pull from
public JsonResult GetUserJSON(string term)
{
var stores = (from st in UserLogic.GetUserIndex(1, term).IndexList
select new { st.Username, st.FirstName, st.LastName }).ToList();
List<String> returnList = new List<string>();
foreach (var item in stores)
{
if (item.Username.ToString().ToUpper().StartsWith(term.ToUpper()))
{
returnList.Add(item.Username.ToString());
}
else if (item.FirstName.ToUpper().Contains(term.ToUpper()))
{
returnList.Add(item.FirstName);
}
else if (item.Username.ToUpper().Contains(term.ToUpper()))
{
returnList.Add(item.Username);
}
}
returnList = returnList.Distinct().OrderByAlphaNumeric(s => s).ToList();
return Json(returnList, JsonRequestBehavior.AllowGet);
}
I think this is what you need:
$(function () {
$("#clearbutton").click(function () {
$('#SearchString').autocomplete('close');
$("#SearchString").val("")
});
});
Add $("#SearchString").val("") to your clearbutton click event
Edit:
You have mistyped the function for clearSearch
this is working example
please try using this
$("#clearbutton").click(function () {
$('#SearchString').autocomplete('close').val('');
});

How to get a #html.Checkbox to update a #html.dropdownList

I have the following checkbox:
#Html.CheckBox("Norm", false, new { #class = "checkbox" })
Once this is checked, I want it to auto update my dropdown
#Html.DropDownList("selectedCore", (SelectList)ViewBag.CoreSheets)
The dropdown selectlist is populated from my controller like this,
ViewBag.CoreSheets = new SelectList(db.CoreSheets, "sheetID", "Abb");
So in summary, I want to click the check box and have the current dropdown value be updated.
Cheers,
B
N J
Try this code
#Html.CheckBox("Norm", false, new { #class = "checkbox",#onclick="clickNorm()" })
<script type="text/javascript">
function clickNorm(){
$.ajax({
url:'#Url.Action("LoadSelectedCoreList")'
dataType:'json',
success:function(res){
if(res && res.length>0){
$('#selectedCore).empty();
$.each(res,function(index,item){
$('#selectedCore').append(new Option(item.Abb,item.sheetID));
});
}
}
});
</script>
In Coltroller
public ActionResult LoadSelectedCoreList()
{
var selectedCoreList=..
return Json(selectedCoreList,
JsonRequestBehavior.AllowGet);
}
I solved this myself by doing the following,
Check box
#Html.CheckBox("Norm", false, new { #class = "checkbox" })
Jquery
<script type="text/javascript">
$(document).ready(function() {
$("#Norm").on("click", function () {
if ($(this).is(":checked")) {
$("#kammcoreauto").val(1);
$("#kammfaceauto").val(1);
$("#spacecoreauto").val(1);
$("#Washercoreauto").val(1);
$("#IsoCoreauto").val(1);
$("#IsoFaceauto").val(1);
}
});
});
</script>
and this just refers to the id of the dropdowns that you can add like this
#Html.DropDownList("selectedCore", (SelectList)ViewBag.CoreSheets, new { id = "kammcoreauto" })
Big Thanks to everyone who tried to help

Combining Razor, Ajax, JSON

I try to make following parts run, but always failed. The objective is: if a target in combobox is selected, the mediaId's combobox should be filled with respective values. At this moment I just emulate the values of mediaId combobox. Can anyone show me how to combine them correctly? Thx in advance.
The view Medium.cshtml:
<script src="#Url.Content("~/Scripts/PartialLoad.js")" type="text/javascript"></script>
<div class="editor-label">
#Html.LabelFor(model => model.Files[i].TargetId)
</div>
<div class="editor-field">
#Html.DropDownListFor(model => model.Files[i].PTargetId, (ViewData["targets"] as SelectList).MakeSelection(Model.Files[i].PTargetId))
</div>
<div class="editor-label">
#Html.LabelFor(model => model.Files[i].MediaId)
</div>
<div class="editor-field">
#Html.DropDownListFor(model => model.Files[i].MediaId, (ViewData["mediaIds"] as SelectList).MakeSelection(1))
</div>
The javascript partialload.js
$(document).ready(function () {
$("#targets").change(function () { GetMValues("#targets", "#mediaIds"); });
});
function ClearDrop(objSource) {
$(objSource).empty();
}
function GetMValues(objSource, objDest) {
var url = '/GetMValues/';
$.getJSON(url, { id: $(objSource).val() },
function (data) {
ClearDrop(objDest); $.each(data, function (index, optionData) {
$(objDest).append("<option value='" + optionData.Value + "'>" + optionData.Text + "</option>");
});
});
}
The homecontroller.cs
public ActionResult GetMValues(String id)
{
int myId = 0;
int.TryParse(id, out myId);
var mediumIds = new List<long>();
int max = myId + 3;
// just to emulate the data in the list
for ( long l = 1 ; l < max ; l++ ){
mediumIds.Add(l);
}
var select = new SelectList(mediumIds, "PTargetId", "TargetId");
return Json(select, JsonRequestBehavior.AllowGet); //allow get needed to allow get calls
}
Here you are using an id selector for the dropdownlist: $("#targets") but your dropdown doesn't seem to have such id. Maybe you want to assign it an id or a class:
#Html.DropDownListFor(
model => model.Files[i].PTargetId,
(ViewData["targets"] as SelectList).MakeSelection(Model.Files[i].PTargetId),
new { id = "targets" }
)
But because this seems to be repeated and you cannot have multiple elements with the same id a class selector is probably more appropriate:
#Html.DropDownListFor(
model => model.Files[i].PTargetId,
(ViewData["targets"] as SelectList).MakeSelection(Model.Files[i].PTargetId),
new { #class = "targets" }
)
and then:
$(document).ready(function () {
$(".targets").change(function () {
...
});
});
Same remark obviously for #mediaIds.

Categories

Resources