how to set radio button checked using knockout.js? - asp.net-mvc

I have two radio buttons.
<td>
<div style="display: inline; margin-right: 10px">
<input type="radio" name="USGlobalUser" data-bind:"checked:IsGlobal/>US
</div>
<div style="display: inline">
<input type="radio" name="USGlobalUser" data-bind:"checked:IsGlobal"/>Global
</div>
</td>
I am populating my model like this
QuestionnaireModel = function (data) {
self.IsGlobal = ko.protectedObservable(data ? data.IsGlobal : false);
}
The value is coming from DB perfectly and its getting populated in self.IsGlobal as true/false. Based upon this true/false, I want to set my radio button checked.

The checked binding works differently for radio buttons:
For radio buttons, KO will set the element to be checked if and only if the parameter value equals the radio button node’s value attribute. So, your parameter value should be a string.
So your IsGlobal should hold a string and you need to have the same string as the value of the radio buttons:
<input type="radio" name="USGlobalUser"
data-bind="checked: IsGlobalCheckbox" value="false" />US
<input type="radio" name="USGlobalUser"
data-bind="checked: IsGlobalCheckbox" value="true" />Global
And in your viewmodel:
self.IsGlobal = ko.observable(data ? data.IsGlobal + "" : "false");
If you want to keep the IsGlobal to store a boolean value you need to create a new computed property for the radio button which does the conversion:
self.IsGlobalCheckbox = ko.computed({
read: function() {
return self.IsGlobal() + "";
},
write: function (v) {
if (v == "true") self.IsGlobal(true)
else self.IsGlobal(false)
}
});
Demo JSFIddle.
And by the way as Tomas noted your binding systax is broken in your sample.

Value from DB is boolean True/False
I changed in viewmodel :
self.IsGlobal = ko.protectedObservable(data ? data.IsGlobal.toString() : "");
and in cshtml :
<td>
<div style="display: inline; margin-right: 10px">
<input type="radio" name="USGlobalUser" value="false" data-bind="checked:IsGlobal()" />US
</div>
<div style="display: inline">
<input type="radio" name="USGlobalUser" value="true" data-bind="checked:IsGlobal()" />Global
</div>
</td>

It`s much more simple. If you want to store something different from string in observable attached to radio buttons just set checkedValue binding for each radio button to same value as html element.
<div style="display: inline; margin-right: 10px">
<input type="radio" name="USGlobalUser" data-bind="checked: IsGlobal, checkedValue: false" value="false" />US</div>
<div style="display: inline">
<input type="radio" name="USGlobalUser" data-bind="checked: IsGlobal, checkedValue: true" value="true" />Global</div>
var QuestionnaireModel = function (data) {
var self = this;
self.IsGlobal = ko.observable(data ? data.IsGlobal : false);
}
ko.applyBindings(new QuestionnaireModel({
IsGlobal: true
}))

After data-bind attribute should be equality sign instead of colon.
<input type="radio" name="USGlobalUser" data-bind="checked:IsGlobal"/>

Related

Getting all the values (checked and unchecked) from the dynamic checkbox in mvc

I'm adding a textbox and a corresponding checkbox to the view on click of a button. These checkbox will determine if the textbox value needs to be shown or hidden.
With the below code I've getting all the textbox fields, but for the checkbox I only get the checked values.
This is the view part
$('#btn-Add-Key-Name').click(function (e) {
i++;
e.preventDefault();
$(`<div class="row" id="rowid`+ i +`">
<div class= "col col-4" >
<section>
<label class="input">
<i class="icon-prepend fa fa-id-badge"></i>
<input type="text" name="KeyName" value="" placeholder="Key Name">
</label>
</section>
</div>
<div class="col col-2">
<label class="checkbox">
<input type="checkbox" name="IsKeyValid" value="true">
<i></i> Key
</label>
</div>
</div >`).appendTo($fields);
});
On the Controller
public JsonResult AddKeyToDB(string[] KeyName, IEnumerable<string> IsKeyValid)
{
}
//Is there a way to get the unchecked values as well for eg:
keyName = ["private", "public"] ,
IsKeyValid = ["false", "true"]
In your html you dont need to hard-code value of checkbox thats why you are only having checked values. So you need to make following change to your code. Just remove value="true" from input type checkbox.
<input type="checkbox" name="IsKeyValid" >

How to show password entered when checkbox is clicked?

in my form i have one checkbox so when i check the checkbox it should show password entered in password field.i am doing it using angular 7.
<div class="form-group">
<label for="Password" class="control-label">Password</label>
<div>
<input type="password" class="form-control" name="Password" ngModel
#pwd="ngModel" placeholder="Password" required pattern="^(?=.*[a-z])(?
=.*
[A-Z])(?=.*\d)(?=.*[#$!%*?&])[A-Za-z\d#$!%*?&]{8,}$">
<div *ngIf= pwd.invalid>
<small class="form-text text-danger" *ngIf=
pwd.errors.required>Password Required</small>
<small class="form-text text-danger"
*ngIf=pwd.errors.pattern>Minimum eight characters, at least one
uppercase letter, one lowercase letter, one number and one special
character.</small>
</div>
</div>
</div>
<div class="form-group form-check">
<input type="checkbox" class="form-check-input"
[disabled]="pwd.invalid">
<label class="form-check-label" id="show" for="exampleCheck1">Show
Password</label>
</div>
By checking the checkbox it should show password entered in the password field.
Hi and welcome on Stackoverflow!
Try to switch between type="password" and type="text" based on checkbox value.
Add #showPassword to your checkbox input, like that :
<input #showPassword type="checkbox" class="form-check-input" [disabled]="pwd.invalid">
Then on your password field :
<input type="showPassword.checked ? 'text' : 'password'" .... />
EDIT (in case you did not solve it yet, and for others) :
component.ts
// show/hide boolean variable
showPassword: boolean;
constructor() {
// init value in constructor
this.showPassword = false;
}
// click event, show/hide based on checkbox value
showHidePassword(e) {
this.showPassword = e.target.checked;
}
component.html
<input [type]="showPassword ? 'text' : 'password'" />
<input type="checkbox" (change)="showHidePassword($event)" > toggle view

Set radio button checked item from ASP MVC 3 controller

Below is a group of radio buttons that appear on my view. I am able to retrieve the selected item via this simple code
string criteria = filter["criteria"];
however I do not know how to retain the selected item. Once the controller posts back to the view the default radio button is always selected.
<form method="post">
#Html.TextBox("searchValue", ViewBag.CurrentFilter as string, new { placeholder = "Search" })
<input type="image" src="#Url.Content("~/Content/Images/Filter.bmp")" alt="Filter" style="padding-top: 0px;" />
<span class="error" style="clear: both;">
#ViewBag.ErrorMessage
</span>
<br />
<br />
<input type="radio" name="criteria" id="bankName" value="bankName" checked="true"/>
<label for="bankName">Bank Name</label>
<input type="radio" name="criteria" id="EPURL" value="EPURL" />
<label for="EPURL">EPURL</label>
<input type="radio" name="criteria" id="specialNotes" value="specialNotes" />
<label for="SpecialNotes">Special Notes</label>
<input type="radio" name="criteria" id="email" value="email" />
<label for="email">Email</label>
<input type="radio" name="criteria" id="dynamicsId" value="dynamicsId" />
<label for="dynamicsId">Dynamics ID</label>
<input type="radio" name="criteria" id="stat" value="stat" />
<label for="fixed">Agent ID </label>
</form>
The answer to this question wound up being incredibly simple. First mistake I made was not using the #Html controls. Second was using FormCollection as an input parameter for the index controller. By changing the radio buttons to the following:
#Html.RadioButton("criteria", "bankName", true)<span>Bank Name</span>
#Html.RadioButton("criteria", "EPURL")<span>EPURL</span>
#Html.RadioButton("criteria", "specialNotes")<span>Special Notes</span>
#Html.RadioButton("criteria", "email")<span>Email</span>
#Html.RadioButton("criteria", "dynamicsId")<span>Dynamics ID</span>
#Html.RadioButton("criteria", "stat")<span>Agent ID</span>
and the signature of the Index method in the controller to this:
public ActionResult Index(string criteria, string searchValue)
The selected radio button stayed selected after the post back.
If I understand your need correctly you could set the name of the item you want checked in the ViewBag (or ViewData or Model) and set the checked property in your view accordingly. Something like this:
<form method="post">
#Html.TextBox("searchValue", ViewBag.CurrentFilter as string, new { placeholder = "Search" })
<input type="image" src="#Url.Content("~/Content/Images/Filter.bmp")" alt="Filter" style="padding-top: 0px;" />
<span class="error" style="clear: both;">
#ViewBag.ErrorMessage
</span>
<br />
<br />
#{
var checkedItemName = ViewBag.CheckedItemName;
}
<input type="radio" name="criteria" id="bankName" value="bankName" checked="#((checkedItemName == "bankName"))"/>
<label for="bankName">Bank Name</label>
<input type="radio" name="criteria" id="EPURL" value="EPURL" checked="#((checkedItemName == "EPURL"))"/>
<label for="EPURL">EPURL</label>
<input type="radio" name="criteria" id="specialNotes" value="specialNotes" checked="#((checkedItemName == "specialNotes"))"/>
<label for="SpecialNotes">Special Notes</label>
<input type="radio" name="criteria" id="email" value="email" checked="#((checkedItemName == "email"))"/>
<label for="email">Email</label>
<input type="radio" name="criteria" id="dynamicsId" value="dynamicsId" checked="#((checkedItemName == "dynamicsId"))"/>
<label for="dynamicsId">Dynamics ID</label>
<input type="radio" name="criteria" id="stat" value="stat" checked="#((checkedItemName == "stat"))"/>
<label for="fixed">Agent ID </label>
</form>
Don't refresh the complete page...Use JQuery and do an Ajax call
$.ajax({
url: "Your Url",
async: true,
type: 'POST',
data: JSON.stringify({ ParameterName: Param_Value }),
beforeSend: function (xhr, opts) {
},
contentType: 'application/json; charset=utf-8',
complete: function () { },
success: function (data) {
//Success Callback
//Code to set value to your control
}
});

How to find the text in label-for of jQuery mobile Radio and Checkbox with knockout?

I'm using jQuery 1.9.1, jQM 1.3 & knockout 2.2.1.
My html is as follows:
<div data-role="page" id="coloursView">
<div data-role="content">
<fieldset data-role="controlgroup">
<legend>Colour:</legend>
<input type="radio" name="colours" data-bind="checked: colour" id="radio-1" value="1" />
<label for="radio-1">Red</label>
<input type="radio" name="colours" data-bind="checked: colour" id="radio-2" value="2" />
<label for="radio-2">Blue</label>
<input type="radio" name="colours" data-bind="checked: colour" id="radio-3" value="3" />
<label for="radio-3">Green</label>
</fieldset>
</div><!--/content -->
</div><!--/page -->
My view model is also very simple:
function ColoursViewModel() {
this.template = "coloursView";
this.colour = ko.observable("1");
this.label = ko.observable(); // custom binding
}
Now, i would like to get the description of the selected colour, not the value.
It seems to me, that i need a custom binding, like this one:
ko.bindingHandlers.label = {
update: function(element, valueAccessor) {
var value = ko.utils.unwrapObservable(valueAccessor());
$("radio", element).filter(function(el) { return $(el).text() === value; }).prop("checked", "checked");
}
};
But i'm not able to get the text of the related label - the label-for text.
Someone could help?
Thanks in advance
Update
Here is another approach where to find only :checked items and remove white-space in text.
Checkbox
$('input[type=checkbox]').each(function () {
if ($(this).is(':checked')) {
var checkbox = $(this).prev('label').text();
alert('Checkbox: ' + checkbox.replace(/\s+/g, ' '));
}
});
Radio
$('input[type=radio]').each(function () {
if ($(this).is(':checked')) {
var radio = $(this).prev('label').text();
alert('Radio: ' + radio.replace(/\s+/g, ' '));
}
});
Updated Demo
Checkbox
$('div.ui-checkbox').find('span.ui-btn-text').text();
Radio
$('div.ui-radio').find('span.ui-btn-text').text();
Sorry if i answer myself, but i think i got it. At least for radio inputs.
Now, i have a custom binding handler at fieldset level, to keep the markup clean and more readable, as i can:
<fieldset data-role="controlgroup" id="front-colours" data-bind="frontColourLabel: frontColour">
<legend>Front Colour: <span data-bind="text: frontColourDescription"></span> (Value: <span data-bind="text: frontColour"></span>)</legend>
<input type="radio" name="front-colours" data-bind="checked: frontColour" id="fc-radio-1" value="red" />
<label for="fc-radio-1">Red</label>
<input type="radio" name="front-colours" data-bind="checked: frontColour" id="fc-radio-2" value="blue" />
<label for="fc-radio-2">Blue</label>
<input type="radio" name="front-colours" data-bind="checked: frontColour" id="fc-radio-3" value="green" />
<label for="fc-radio-3">Green</label>
</fieldset>
this is the binding handler i come up:
ko.bindingHandlers.frontColourLabel = {
update: function(element, valueAccessor, allBindingsAccessor, viewModel, bindingContext) {
ko.utils.unwrapObservable(valueAccessor());
var id = $('input:radio[name='+element.id+']:checked').prop("id");
var radioText = $('label[for=' + id + ']').text();
viewModel.frontColourDescription(radioText);
}
};
the only tricky part here, is that the id of the fieldset is equal to the name of the radio-group, as it's easy to filter out what radio-group i want to address.
WORKING EXAMPLE: http://jsfiddle.net/h7Bmb/1/
I try now to get the checkbox part to work. Someone can help?

vertically displayed jquery buttonset

i'm using the jquery ui button, is it possible to display the radio button vertically?it seems to default to horizontal.
http://jqueryui.com/demos/button/#radio
many thanks
I wrote a short plugin that implement vertical buttonset for radio buttons and checkboxes with jquery ui.
1. jQuery Plugin
(function( $ ){
//plugin buttonset vertical
$.fn.buttonsetv = function() {
$(':radio, :checkbox', this).wrap('<div style="margin: 1px"/>');
$(this).buttonset();
$('label:first', this).removeClass('ui-corner-left').addClass('ui-corner-top');
$('label:last', this).removeClass('ui-corner-right').addClass('ui-corner-bottom');
var maxWidth = 0; // max witdh
$('label', this).each(function(index){
var labelWidth = $(this).width();
if (labelWidth > maxWidth ) maxWidth = labelWidth ;
})
$('label', this).each(function(index){
$(this).width(maxWidth);
})
};
})( jQuery );
2. Sample markup
<h2> Radio Buttonset </h2>
<div id="radio">
<input type="radio" id="radio1" name="radio" value="1"/><label for="radio1">Choice 1</label>
<input type="radio" id="radio2" name="radio" value="2"/><label for="radio2">Choice 2</label>
<input type="radio" id="radio3" name="radio" value="3"/><label for="radio3">Choice 3</label>
</div>
<h2> Checkbox Buttonset </h2>
<div id="checkbox">
<input type="checkbox" id="check1" name="check" value="1"/><label for="check1">Choice 1</label>
<input type="checkbox" id="check2" name="check" value="2"/><label for="check2">Choice 2</label>
<input type="checkbox" id="check3" name="check" value="3"/><label for="check3">Choice 3</label>
</div>
3. Plugin Usage
$(document).ready(function(){
//call plugin
$("#radio").buttonsetv();
$("#checkbox").buttonsetv();
});
Here the plugin and example code
I hope this can help you :)
Place the individual buttons in their own div tags.
Credit to leacar21 from: https://forum.jquery.com/topic/how-to-vertical-radio-button-set
<div id="someSet">
<div><input type="radio" id="button1"... ></div>
<div><input type="radio" id="button2"... ></div>
<div><input type="radio" id="button3"... ></div>
</div>
There isn't a built-in way to do this...not at the moment anyway. The markup and styling is built around a horizontal set.

Resources