Setting html checkbox checked value based on mvc model - javascript

I have an Edit view where I have some checkboxes that I need populated based on values from the model. I would like to avoid using different CheckBoxListFor extensions, as I believe there is a simpler way to do it.
I tried to set the value with javascript, but I end up with all checkboxes checked, which is not ok.
This is what I tried:
function SetAdminCheckBox() {
var contains = #Model.RoleNames.Contains("Admin");
var True = true;
var result;
result = contains ? 'checked' : '';
return result;
}
<input type="checkbox" name="roleNames" value="Admin" checked="SetAdminCheckBox()"/>

I found a way to do it, using some razor syntax:
<input type="checkbox" name="roleNames" value="Admin" #if (Model.RoleNames.Contains("Admin")) {<text>checked="checked"</text>} />

you can't use "checked" attribute like that, checked has no value it is either present or not if it is present than checkbox is checked otherwise not
use an if to write two version one which will output checked attribute and other which will not.

Related

How to collect a string from a radio input and send it to a useState? (React) [duplicate]

I have a MVC3 app using Project Awesome (http://awesome.codeplex.com/), but I am getting a weird behaviour on checkboxes. I have the following simple Html within a Modal popup <input type="checkbox" class="check-box" name="IsDeleted">
When I submit the form containing this element, its post value is 'on' instead of the expected 'true' (when element is checked).
Does anybody know why this is? I am assuming there may be some javascript somewhere messing with the form data, but wanted to check whether there isn't some HTML I am missing.
Thanks
Set the checkboxes value attribute to true and you will get true in your post value.
It's browser specific, I suppose, what to send when value is undefined. You need to defined value attribute on your radios/checkboxes to be sure what will be passed back to you. I would suggest value="1"
set data-val="true" and value="true" by deafult...
if checkbox is checked then returns true
Check Checkbox is checked or not if checked set Hidden field true else set hidden field false.
$('#hiddenFieldId').val($('#CheckBoxId').attr('checked')=='checked')
Surely you should just check if it is set - the value that it sends across is irrelevant, if it's not checked, then nothing at all gets sent when you POST.
Nothing worked!
I ended up on a hacky way after seeing the serialised form object just before posting to controller/action. Its not safe in case if anyone would have any textboxes inside that may contain ampersands. In my case, i had an array of checkboxes, so I did this hack after I am very sure, i won't have problems.
var formData = $("#form").serialize();
formData = formData.replaceAll('=on&','=true&');
if (formData.endsWith('=on'))
{
formData = formData.substring(0, formData.length - 3) + "=true";
}
Hope it helps to those 'someone' with my scenario. Happy hacking.
Use jQuery for cross-browser decision. And it will return true or false anyway.
$('#check-box-id').attr('checked' ) == true
if your checkbox has an id check-box-id. For your current version use the next (select by class name):
$('.check-box').attr('checked' ) == true
Use jQuery
var out=$('.check-box').is('checked')
If checkbox is checked out=true
else out=false
In HTML, add a input type="hidden" above checkbox:
<input name="active" id="activeVal" type="hidden">
<input id="active" type="checkbox">
Then, add a script as below:
$('#activeVal').val($('#active').is(':checked'));
$('#active').change(function() {
$('#activeVal').val($('#active').is(':checked'));
});
When you do eg. $('#your-form').serialize() in jQuery, you will get value of checkbox when checked active: true or uncheck active: false

Checking a Checkbox through JS in browser

I'm looking to set multiple values and checkboxes on a webpage using JS.
I'm able to do values using
document.querySelector('input[name="date"]').value = '1/1/2000';
document.querySelector('form').submit();
...that's simple enough. There are multiple checkboxes that may or may not need to be checked. What is the process to check a box through the console? Here is a sample of one of them when it is checked:
input id="FormView1_cb_EXAMPLE" type="checkbox"
name="FormView1$cb_EXAMPLE" checked="checked"
You can do this by targeting the checked attribute of the item after selecting it with either querySelector or getElementByID. Then simply set it to true for checked.
document.querySelector('#steve').checked=true
<input id="steve" type="checkbox">
If you need to do it to multiple and they all have the same class name, you can use querySelectorAll and a forEach/for loop and set each one to true (checked) using that method. (this would only work if your list of which ones need to be checked conditionally is constant)
I hope your job looks
var input = document.querySelector('#FormView1_cb_EXAMPLE').checked;
console.log(input)
<input id="FormView1_cb_EXAMPLE" type="checkbox">

Checkbox checked not passing an actual value?

My code checks the value of 2x checkboxes to equal true/false depending on a radio field. I see the checkboxes being ticket on the web page.
However, once they are passed over a HTML POST form, they have no values and always equal false.
If I give the checkboxes a value "TRUE" then of course they have only that value.
What am I missing here?
<script>
$(function() {
var MAIN= $("input[type='radio']");
var marketingPhone = $("input[type='checkbox'][name='marketingPhone']");
var marketingRobo = $("input[type='checkbox'][name='marketingRobo']");
MAIN.on('change', function()
{
if ($(this).val() == "TRUE") {
marketingPhone.prop('checked',true);
marketingRobo.prop('checked',true);
} else {
marketingPhone.prop('checked',false);
marketingRobo.prop('checked',false);
}
});
});
</script>
The fields are as follows:
<input type="checkbox" name="marketingPhone" value=""/>
<input type="checkbox" name="marketingRobo" value=""/>
Checkboxes, if not checked, do not get posted at all with the form.
So if you post a form with checkboxes even if they have some value but they are not checked, you can not get checkbox's values in $_POST or $_GET arrays.
You need to specify a value in the HTML. If a checkbox is checked, that value is posted. These values can be anything and are definitely not the same as the true/false that are used for the prop()-call (those just mean 'set or clear the check mark').
Example:
<input type="checkbox" name="marketingPhone" value="yes"/>
<input type="checkbox" name="marketingRobo" value="absolutely"/>
When both are checked, this is posted:
marketingPhone=yes&marketingRobo=absolutely
When not all are checked, the corresponding name=value are omitted from the posted data.
If you really want to post a value (e.g. "true" or "false") for every checkbox all the time, then the only way to do so is by adding hidden fields (one for each checkbox) that you control yourself, setting the value of the hidden field to "true" or "false" using script. You might as well then not set the checkbox value to prevent confusion on the receiving end.
Also be aware that form fields always post strings, so either treat them as literal strings or parse them into booleans on the receiving end.

Knockout - Checking checkboxes according to observableArray

So I have a list of schedules that I need to display for a user and show which schedules he or she is currently on and give them the possibility to jump on and off said schedules.
My viewmodel looks like this
self = this;
self.shifts = ko.observableArray();
self.selectedShifts = ko.observableArray();
//I populate self.shifts here with a WEB API call
//Run through each shift and check if current user is on it and set checked / not checked value for checkbox
ko.utils.arrayForEach(self.shifts(), function(shift) {
//Clear array
self.usersOnShift([]);
//Populate array with all users on the shift
self.usersOnShift = ko.observableArray(WEB API CALL HERE);
var userInShift = ko.utils.arrayFirst(self.usersOnShift(), function(user) {
if (selectedUserId == user.ID) {
return true;
}
});
if (userInShift) {
self.selectedShifts.push(shift.ID);
}
});
ko.applyBindings(self);
My HTML looks like this
<div class="simple_overlay" id="shiftOverlay">
<div class="details">
<div data-bind="foreach: shifts">
<div><span class="staff-initials" data-bind="text:wardName"> </span><input type="checkbox" data-bind="value: ID, checked: $root.selectedShifts"/> </div>
</div>
<div>
Connect
Close
</div>
</div>
</div>
I can see that the value of the checkboxes are set correctly to the ID of the corresponding shifts. However a shift that I know the user in question is on is not checked and I know that the selectedShifts observableArray contains the value.
Somehow the "checked: $root.selectedShifts" call / check is not working but I know that it contains the right value. What am I doing wrong?
The problem is that your value is an integer, but when bound to the checkbox element, it becomes a string. When the checked binding tries to find the value in the array, it doesn't find a match because it uses strict equality for comparison and (2 === "2") is false.
The simplest way to work around this problem is to convert your values to string when you add them to the array:
self.selectedShifts.push("" + shift.ID);
Of course this means that your model has to change, and that might not be a great solution. I came up with a custom binding, checkedInArray that replaces checked and supports any type of value. You can learn about it, see it in action, and use it like this:
<input type="checkbox" data-bind="checkedInArray: {value: ID, array: $root.selectedShifts }" />
In Knockout 2.3.0 (which is still in development) there will be a new binding, checkedValue, that will allow you use any type of value with the checked binding. Using that version, you could update your HTML to use checkedValue:
<input type="checkbox" data-bind="checkedValue: ID, checked: $root.selectedShifts"/>
Is shift.ID an observable property? If it is, then you need to add it to the array like this:
self.selectedShifts.push(shift.ID());
Otherwise you're just adding the whole observable to the array, and not the value.

How to disable enable a checkbox based on another checkbox?

Following code is generated by a for loop.
<form action="saveresponse.php" method="POST" name="mainForm">
<input class="cbox_yes" type="checkbox" name="yes[]" value="01.jpg"
onclick="spenable()" /> OK
<input class="cbox_sp" type="checkbox" name="sp[]" value="01.jpg" disabled />Special<br />
<input class="cbox_yes" type="checkbox" name="yes[]" value="02.jpg"
onclick="spenable()" /> OK
<input class="cbox_sp" type="checkbox" name="sp[]" value="02.jpg" disabled />Special<br />
etc etc upto n times...
Now, what I want is that on page load, all the sp[] checkboxes should be disabled and enabled only if their corrosponding yes[] checkbox is checked by user.
Javascript code I am using: (Just to check if JS is capturing the states of yes[] checkbox?
function spenable(){
var yes = document.mainForm.yes[].value;
if (yes == true)
//alert("true");
document.mainForm.yes[].value = checked;
else
//alert("false");
document.mainForm.yes[].value = checked;
};
};
But I am not getting any alert (Neither Yes, Nor No).
So, is yes[] (Square brackets) in second line is incorrect? Or my if/else condition is wrong in JS?
P.S. All the questions here at SO or on Google deal with only one case/pair.
P.S. If required, I can change yes[] to yes1, yes2, yes3 etc and corresponding sp1, sp2, sp3 where 1,2,3 is $i of For loop, but then how will I capture/refer to it in JS?
_UPDATE:_
The flow/conditions are(Clarification):
Initially Special checkbox will be disabled and OK checkbox will be unchecked.
Then if user checks Ok, Special gets enabled.
If user want, he can tick Special.
If, later, user changes mind and untick the OK, Special should be unticked as well as disabled again.
I used jQuery here for the sake of simplicity.
$("input[name='yes[]']").change(function() { //When checkbox changes
var checked = $(this).attr("checked");
$(this).next().attr("disabled", !checked); //The next checkbox will enable
});​ // or disable based on the
// checkbox before it
Demo: http://jsfiddle.net/DerekL/Zdf9d/
Pure JavaScript: http://jsfiddle.net/DerekL/Zdf9d/1/
Update
It will uncheck the first checkboxes when the Special checkbox is checked.
Pure JavaScript: http://jsfiddle.net/DerekL/Zdf9d/2/
More Updates
Here's the demo:
Pure JavaScript: http://jsfiddle.net/DerekL/Zdf9d/3/
jQuery: http://jsfiddle.net/DerekL/Zdf9d/4/
Little note: document.querySelectorAll works on all modern browsers and IE8+ including IE8. It is always better to use jQuery if you want to support IE6.
You can't use yes[] as an identifier in the Javascript, so you have to access the field using the name as a string:
document.mainForm["yes[]"]
This will not return a single element, it will return an array of elements. Use an index to access a specific element:
document.mainForm["yes[]"][0]
The value of the checkbox will always be the value property, regardless of whether the checkbox is selected or not. Use the checked property to find out if it's selected:
function spenable() {
var yes = document.mainForm["yes[]"][0].checked;
if (yes) {
alert("true");
} else {
alert("false");
};
}
To access the specific checkbox that was clicked, send the index of the checkbox in the event call:
<input class="cbox_yes" type="checkbox" name="yes[]" value="01.jpg" onclick="spenable(0);" /> OK
Use the index in the function:
function spenable(idx) {
var yes = document.mainForm["yes[]"][idx].checked;
var sp = document.mainForm["sp[]"][idx];
sp.disabled = !yes;
}
If you are open to using jQuery:
$('input[type="checkbox"]').click(function(){
var obj = $(this);
obj.next('.cbox_sp').attr({'disabled':(obj.is(':checked') ? false : 'disabled')});
});
This solution will assign an onclick event handler to all checkboxes and then check to see if the corresponding "special" checkbox should be disabled or not. It also sets the default checked state to true.
Working Example: http://jsfiddle.net/6YTqC/

Categories

Resources