MVC 4 EditorFor bool Checkbox always posting True - javascript

I have a bool property in my model. Its value is false when rendering the view. But when I submit the form, the value of TRUE is being passed to the controller. I am using a custom js function to get the values from the form to submit to a controller action. I am not sure how to get the correct value from the checkbox.
My model property:
public bool RushOrderFlag { get; set; }
The view markup:
#Html.EditorFor(model => model.RushOrderFlag)
The HTML Rendered:
<input class="chkbx" data-val="true" data-val-required="The Rush? field is required." id="RushOrderFlag" name="RushOrderFlag" type="checkbox" value="true">
<input name="RushOrderFlag" type="hidden" value="false">
My JS function
function GetFilterCriteria() {
var Criteria = {};
$('#frmCriteria input').each(function () {
Criteria[this.name] = $("#" + this.name).val();
});
return Criteria;
};
Even if in the console I put $('[name="RushOrderFlag"]').val(), after clicking the check box on and off, it is always returning true.
What am I doing wrong?

try
function GetFilterCriteria() {
var Criteria = {};
$('#frmCriteria input').each(function () {
Criteria[this.name] = false;
if ($("#" + this.name).is(':checked'))
Criteria[this.name] = true;
});
return Criteria;
};

Thanks all for the hints...in the end it had to be a bit more complex due to the way the razor creates 2 input controls for the checkbox. So here is what I had to do:
function GetFilterCriteria() {
var Criteria = {};
$('#frmCriteria input').each(function () {
if ($(this).attr('type') != 'hidden') {
if ($(this).attr('type') == 'checkbox') {
Criteria[this.name] = this.checked;
} else {
Criteria[this.name] = $("#" + this.name).val();
}
}
});
return Criteria;
};
I don't like it because if I ever want a hidden input, this will skip that. But for now it works. I find it hard to believe that it has to be this difficult :(

you can try using .CheckBoxFor() you will get an input element only.
for the checked property you can use:
$('#CurrentMailTemplateEnabled').get()[0].checked
to get the value by getting the DOM element first. At least that worked for me.

Related

how to tweak form validator.js to only send form if checkbox is checked

I have made a contact form using the example at https://bootstrapious.com/p/how-to-build-a-working-bootstrap-contact-form which works fine.
Now I would like to add a checkbox which the user has to check (besides a google recaptcha and the mandatory form fields) if he wants to be able to submit the form.
i think i have to tweak the validator.js file but since i don't know javascript, i have no idea how to edit the existing validator file.
HTML of additional checkbox:
<label>
<input type="chbox" name="chbox" id="chbox">Terms and conditions.
</label>
js:
function getValue($el) {
return $el.is('[type="checkbox"]') ? $el.prop('checked') :
$el.is('[type="radio"]') ? !!$('[name="' + $el.attr('name') + '"]:checked').length :
$el.val()
}
var Validator = function (element, options) {
this.options = options
this.validators = $.extend({}, Validator.VALIDATORS, options.custom)
this.$element = $(element)
this.$btn = $('button[type="submit"], input[type="submit"]')
.filter('[form="' + this.$element.attr('id') + '"]')
.add(this.$element.find('input[type="submit"], button[type="submit"]'))
this.update()
this.$element.on('input.bs.validator change.bs.validator focusout.bs.validator', $.proxy(this.onInput, this))
this.$element.on('submit.bs.validator', $.proxy(this.onSubmit, this))
this.$element.on('reset.bs.validator', $.proxy(this.reset, this))
this.$element.find('[data-match]').each(function () {
var $this = $(this)
var target = $this.data('match')
$(target).on('input.bs.validator', function (e) {
getValue($this) && $this.trigger('input.bs.validator')
})
})
this.$inputs.filter(function () { return getValue($(this)) }).trigger('focusout')
this.$element.attr('novalidate', true) // disable automatic native validation
this.toggleSubmit()
}
only if the mandatory fields are filled out and the checkbox and the recaptcha checks are made, the submit button should become clickable and the form can be submitted.
oh, i just found out myself that the html for the checkbox was incomplete. i added required="required". the complete line now is
<input type="checkbox" name="chbox" id="chbox" required="required">
and now finally works as intended.

Get checkbox state in array with javascript or jquery

I have on a devexpress grid one column with a checkbox. It is a simple checkbox column, which depends on which checkbox is checked I need to invoke different methods, it is not bind to a property from model.
I need to know which row is selected. I have tried to resolve this with this javascript code:
if (document.getElementById('selectDamage').checked) {
alert("checked");
var checkedValues = $('input:checkbox:checked').map(function () {
return this.value;
}).get();
console.log(checkedValues);
} else {
alert("You didn't check it! Let me check it for you.");
}
This returns only the checked values. I need to return something like Array{on, off, on}, the first is checked, the second one is unchecked and the last is checked. Is there a way in javascript or jquery to do that?
first add checkbox in grid then take a button and set onclick function of this button , then all checked data will go through array and finally split the array value and do your further job.(array value are saved into hidden field, i used hidden field and set the id lblarr )
<dx:GridViewDataColumn >
<HeaderTemplate>
</HeaderTemplate>
<DataItemTemplate>
<input type="checkbox" class="case" id="chkchild" name="checkboxModel" value='<%#Eval("SALE_DOC_#") %>' />
</DataItemTemplate>
</dx:GridViewDataColumn>
<script>
$('#btn1').click(function () {
var CheckCount =$('input:checkbox[name="checkboxModel"]:checked').length;
if (CheckCount > 0)
{
var valuesArray =
$('input:checkbox[name="checkboxModel"]:checked').map(function () {
return this.value;
}).get().join(",");
$('#<%=lblarr.ClientID%>').val(valuesArray);
}
else {
alert('Please check at least one data!')
}
})
</script>
Depending on the layout of your html, you could do something like this to get an updated array of indexed checked states
var els = $("table#gvDamages3_DXMainTable input[type=checkbox]");
els.on("change", function(){
var vals = [];
els.each(function() {
vals.push(this.checked);
});
console.log(vals);
});

Get Js Value in Laravel Controller

How do I get the js value in Laravel controller. I want to pass the value from the hidden fields to be saved in the db, but to my surprise it saves empty records for these fields. When I logged the values on the console, I am seeing it but it is not passed as the value to the controller. What better way am I to handle this?
public function store(UserContactRequest $userContactRequest)
{
$phone = $userContactRequest->phone_output;
if(Auth::user()) {
if($userContactRequest->isMethod('post')) {
$userContact = UserContact::firstOrNew(array('user_id'=>Auth::user()->id));
$userContact->phone = $phone;
$userContact->save();
return redirect()->route('userContactIndex')->with('message', 'Your question has been posted.');
}else{
return redirect('user/contact/create')->withErrors($userContactRequest)->withInput();
}
}
}
This is the blade file
<TH>FIELD</TH><TH>DECRIPTION</TH>
<input type="hidden" name="phone_output" id="phone_output">
<TR><TD><div>{!! Form::tel('phone', Input::old('phone'), ['class'=>'mid first-input-div', 'placeholder'=>'8023472436', 'id'=>'phone']) !!}</div></TD><TD class="font-description"><SPAN id="errNm1"><STRONG><I>FIRSTNAME</I></STRONG></SPAN> field requests the input of your surname or family name. Only <SPAN><STRONG><I>alphabets</I></STRONG></SPAN> are accepted as valid inputs. </TD></TR>
THis is the js file:
$("#phone").intlTelInput();
var input = $("#phone"),
output = $("#phone_output");
input.intlTelInput({
nationalMode: true,
utilsScript: "http://localhost:88/build/js/utils.js" // just for formatting/placeholders etc
});
// listen to "keyup", but also "change" to update when the user selects a country
input.on("keyup change", function() {
var intlNumber = input.intlTelInput("getNumber");
if (intlNumber) {
output.text("International: " + intlNumber);
console.log(intlNumber);
} else {
output.text("Please enter a number below");
}
});
You should use output.val() to set a value for the hidden input field.
You have used output.text() instead.
Updated snippet :
input.on("keyup change", function() {
var intlNumber = input.intlTelInput("getNumber");
if (intlNumber) {
output.val("International: " + intlNumber);
console.log(intlNumber);
} else {
output.val("Please enter a number below");
}
});

Validating a checkbox after already validating other sections of a form [duplicate]

I have a form with multiple checkboxes and I want to use JavaScript to make sure at least one is checked. This is what I have right now but no matter what is chosen an alert pops up.
JS (wrong)
function valthis(){
if (document.FC.c1.checked) {
alert ("thank you for checking a checkbox")
} else {
alert ("please check a checkbox")
}
}
HTML
<p>Please select at least one Checkbox</p>
<br>
<br>
<form name = "FC">
<input type = "checkbox" name = "c1" value = "c1"/> C1
<br>
<input type = "checkbox" name = "c1" value = "c2"/> C2
<br>
<input type = "checkbox" name = "c1" value = "c3"/> C3
<br>
<input type = "checkbox" name = "c1" value = "c4"/> C4
<br>
</form>
<br>
<br>
<input type = "button" value = "Edit and Report" onClick = "valthisform();">
So what I ended up doing in JS was this:
function valthisform(){
var chkd = document.FC.c1.checked || document.FC.c2.checked||document.FC.c3.checked|| document.FC.c4.checked
if (chkd == true){
} else {
alert ("please check a checkbox")
}
}
I decided to drop the "Thank you" part to fit in with the rest of the assignment. Thank you so much, every ones advice really helped out.
You should avoid having two checkboxes with the same name if you plan to reference them like document.FC.c1. If you have multiple checkboxes named c1 how will the browser know which you are referring to?
Here's a non-jQuery solution to check if any checkboxes on the page are checked.
var checkboxes = document.querySelectorAll('input[type="checkbox"]');
var checkedOne = Array.prototype.slice.call(checkboxes).some(x => x.checked);
You need the Array.prototype.slice.call part to convert the NodeList returned by document.querySelectorAll into an array that you can call some on.
This should work:
function valthisform()
{
var checkboxs=document.getElementsByName("c1");
var okay=false;
for(var i=0,l=checkboxs.length;i<l;i++)
{
if(checkboxs[i].checked)
{
okay=true;
break;
}
}
if(okay)alert("Thank you for checking a checkbox");
else alert("Please check a checkbox");
}
If you have a question about the code, just comment.
I use l=checkboxs.length to improve the performance. See http://www.erichynds.com/javascript/javascript-loop-performance-caching-the-length-property-of-an-array/
I would opt for a more functional approach. Since ES6 we have been given such nice tools to solve our problems, so why not use them.
Let's begin with giving the checkboxes a class so we can round them up very nicely.
I prefer to use a class instead of input[type="checkbox"] because now the solution is more generic and can be used also when you have more groups of checkboxes in your document.
HTML
<input type="checkbox" class="checkbox" value=ck1 /> ck1<br />
<input type="checkbox" class="checkbox" value=ck2 /> ck2<br />
JavaScript
function atLeastOneCheckboxIsChecked(){
const checkboxes = Array.from(document.querySelectorAll(".checkbox"));
return checkboxes.reduce((acc, curr) => acc || curr.checked, false);
}
When called, the function will return false if no checkbox has been checked and true if one or both is.
It works as follows, the reducer function has two arguments, the accumulator (acc) and the current value (curr). For every iteration over the array, the reducer will return true if either the accumulator or the current value is true.
the return value of the previous iteration is the accumulator of the current iteration, therefore, if it ever is true, it will stay true until the end.
Check this.
You can't access form inputs via their name. Use document.getElements methods instead.
Vanilla JS:
var checkboxes = document.getElementsByClassName('activityCheckbox'); // puts all your checkboxes in a variable
function activitiesReset() {
var checkboxesChecked = function () { // if a checkbox is checked, function ends and returns true. If all checkboxes have been iterated through (which means they are all unchecked), returns false.
for (var i = 0; i < checkboxes.length; i++) {
if (checkboxes[i].checked) {
return true;
}
}
return false;
}
error[2].style.display = 'none'; // an array item specific to my project - it's a red label which says 'Please check a checkbox!'. Here its display is set to none, so the initial non-error label is visible instead.
if (submitCounter > 0 && checkboxesChecked() === false) { // if a form submit has been attempted, and if all checkboxes are unchecked
error[2].style.display = 'block'; // red error label is now visible.
}
}
for (var i=0; i<checkboxes.length; i++) { // whenever a checkbox is checked or unchecked, activitiesReset runs.
checkboxes[i].addEventListener('change', activitiesReset);
}
Explanation:
Once a form submit has been attempted, this will update your checkbox section's label to notify the user to check a checkbox if he/she hasn't yet. If no checkboxes are checked, a hidden 'error' label is revealed prompting the user to 'Please check a checkbox!'. If the user checks at least one checkbox, the red label is instantaneously hidden again, revealing the original label. If the user again un-checks all checkboxes, the red label returns in real-time. This is made possible by JavaScript's onchange event (written as .addEventListener('change', function(){});
You can check that atleast one checkbox is checked or not using this simple code. You can also drop your message.
Reference Link
<label class="control-label col-sm-4">Check Box 2</label>
<input type="checkbox" name="checkbox2" id="checkbox2" value=ck1 /> ck1<br />
<input type="checkbox" name="checkbox2" id="checkbox2" value=ck2 /> ck2<br />
<script>
function checkFormData() {
if (!$('input[name=checkbox2]:checked').length > 0) {
document.getElementById("errMessage").innerHTML = "Check Box 2 can not be null";
return false;
}
alert("Success");
return true;
}
</script>
< script type = "text/javascript" src = "js/jquery-1.6.4.min.js" > < / script >
< script type = "text/javascript" >
function checkSelectedAtleastOne(clsName) {
if (selectedValue == "select")
return false;
var i = 0;
$("." + clsName).each(function () {
if ($(this).is(':checked')) {
i = 1;
}
});
if (i == 0) {
alert("Please select atleast one users");
return false;
} else if (i == 1) {
return true;
}
return true;
}
$(document).ready(function () {
$('#chkSearchAll').click(function () {
var checked = $(this).is(':checked');
$('.clsChkSearch').each(function () {
var checkBox = $(this);
if (checked) {
checkBox.prop('checked', true);
} else {
checkBox.prop('checked', false);
}
});
});
//for select and deselect 'select all' check box when clicking individual check boxes
$(".clsChkSearch").click(function () {
var i = 0;
$(".clsChkSearch").each(function () {
if ($(this).is(':checked')) {}
else {
i = 1; //unchecked
}
});
if (i == 0) {
$("#chkSearchAll").attr("checked", true)
} else if (i == 1) {
$("#chkSearchAll").attr("checked", false)
}
});
});
< / script >
Prevent user from deselecting last checked checkbox.
jQuery (original answer).
$('input[type="checkbox"][name="chkBx"]').on('change',function(){
var getArrVal = $('input[type="checkbox"][name="chkBx"]:checked').map(function(){
return this.value;
}).toArray();
if(getArrVal.length){
//execute the code
$('#msg').html(getArrVal.toString());
} else {
$(this).prop("checked",true);
$('#msg').html("At least one value must be checked!");
return false;
}
});
UPDATED ANSWER 2019-05-31
Plain JS
let i,
el = document.querySelectorAll('input[type="checkbox"][name="chkBx"]'),
msg = document.getElementById('msg'),
onChange = function(ev){
ev.preventDefault();
let _this = this,
arrVal = Array.prototype.slice.call(
document.querySelectorAll('input[type="checkbox"][name="chkBx"]:checked'))
.map(function(cur){return cur.value});
if(arrVal.length){
msg.innerHTML = JSON.stringify(arrVal);
} else {
_this.checked=true;
msg.innerHTML = "At least one value must be checked!";
}
};
for(i=el.length;i--;){el[i].addEventListener('change',onChange,false);}
<label><input type="checkbox" name="chkBx" value="value1" checked> Value1</label>
<label><input type="checkbox" name="chkBx" value="value2"> Value2</label>
<label><input type="checkbox" name="chkBx" value="value3"> Value3</label>
<div id="msg"></div>
$('input:checkbox[type=checkbox]').on('change',function(){
if($('input:checkbox[type=checkbox]').is(":checked") == true){
$('.removedisable').removeClass('disabled');
}else{
$('.removedisable').addClass('disabled');
});
if(($("#checkboxid1").is(":checked")) || ($("#checkboxid2").is(":checked"))
|| ($("#checkboxid3").is(":checked"))) {
//Your Code here
}
You can use this code to verify that checkbox is checked at least one.
Thanks!!

jQuery Use Loop for Validation?

I have rather large form and along with PHP validation (ofc) I would like to use jQuery. I am a novice with jQuery, but after looking around I have some code working well. It is checking the length of a Text Box and will not allow submission if it is under a certain length. If the entry is lower the colour of the text box changes Red.
The problem I have is as the form is so large it is going to take a long time, and a lot of code to validate each and every box. I therefore wondered is there a way I can loop through all my variables rather than creating a function each time.
Here is what I have:
var form = $("#frmReferral");
var companyname = $("#frm_companyName");
var companynameInfo = $("#companyNameInfo");
var hrmanagername = $("#frm_hrManager");
var hrmanagernameInfo = $("#hrManagerInfo");
form.submit(function(){
if(validateCompanyName() & validateHrmanagerName())
return true
else
return false;
});
Validation Functions
function validateCompanyName(){
// NOT valid
if(companyname.val().length < 4){
companyname.removeClass("complete");
companyname.addClass("error");
companynameInfo.text("Too Short. Please Enter Full Company Name.");
companynameInfo.removeClass("complete");
companynameInfo.addClass("error");
return false;
}
//valid
else{
companyname.removeClass("error");
companyname.addClass("complete");
companynameInfo.text("Valid");
companynameInfo.removeClass("error");
companynameInfo.addClass("complete");
return true;
}
}
function validateHrmanagerName(){
// NOT Valid
if(hrmanagername.val().length < 4){
hrmanagername.removeClass("complete");
hrmanagername.addClass("error");
hrmanagernameInfo.text("Too Short. Please Enter Full Name.");
hrmanagernameInfo.removeClass("complete");
hrmanagernameInfo.addClass("error");
return false;
}
//valid
else{
hrmanagername.removeClass("error");
hrmanagername.addClass("complete");
hrmanagernameInfo.text("Valid");
hrmanagernameInfo.removeClass("error");
hrmanagernameInfo.addClass("complete");
return true;
}
}
As you can see for 50+ input boxes this is going to be getting huge. I thought maybe a loop would work but not sure which way to go about it. Possibly Array containing all the variables? Any help would be great.
This is what I would do and is a simplified version of how jQuery validator plugins work.
Instead of selecting individual inputs via id, you append an attribute data-validation in this case to indicate which fields to validate.
<form id='frmReferral'>
<input type='text' name='company_name' data-validation='required' data-min-length='4'>
<input type='text' name='company_info' data-validation='required' data-min-length='4'>
<input type='text' name='hr_manager' data-validation='required' data-min-length='4'>
<input type='text' name='hr_manager_info' data-validation='required' data-min-length='4'>
<button type='submit'>Submit</button>
</form>
Then you write a little jQuery plugin to catch the submit event of the form, loop through all the elements selected by $form.find('[data-validation]') and execute a generic pass/fail validation function on them. Here's a quick version of what that plugin might look like:
$.fn.validate = function() {
function pass($input) {
$input.removeClass("error");
$input.addClass("complete");
$input.next('.error, .complete').remove();
$input.after($('<p>', {
class: 'complete',
text: 'Valid'
}));
}
function fail($input) {
var formattedFieldName = $input.attr('name').split('_').join(' ');
$input.removeClass("complete");
$input.addClass("error");
$input.next('.error, .complete').remove();
$input.after($('<p>', {
class: 'error',
text: 'Too Short, Please Enter ' + formattedFieldName + '.'
}));
}
function validateRequired($input) {
var minLength = $input.data('min-length') || 1;
return $input.val().length >= minLength;
}
return $(this).each(function(i, form) {
var $form = $(form);
var inputs = $form.find('[data-validation]');
$form.submit(function(e) {
inputs.each(function(i, input) {
var $input = $(input);
var validation = $input.data('validation');
if (validation == 'required') {
if (validateRequired($input)) {
pass($input);
}
else {
fail($input);
e.preventDefault();
}
}
})
});
});
}
Then you call the plugin like:
$(function() {
$('#frmReferral').validate();
});
You could give them all a class for jQuery use through a single selector. Then use your validation function to loop through and handle every case.
$(".validate").each(//do stuff);
form.submit(function(){
if(validateCompanyName() && validateHrmanagerName()) // Its logical AND not bitwise
return true
else
return false;
You can do this.
var x = $("input[name^='test-form']").toArray();
for(var i = 0; i < x.length; i++){
validateCompanyName(x[i]);
validateHrmanagerName(x[i]);
}

Categories

Resources