checkbox being checked on false - jquery - javascript

$('#checkyes').prop('checked', row['checkb']);
var check = row['checkb'];
alert(check);
$('#checkyes').checkboxradio('refresh');
The alert correctly shows the value inside row['checkb'] to be false, yet the checkbox gets ticked anyway. Am I missing some quotations somewhere or can I not use the row value?

Try
$('#checkyes').prop('checked', (row['checkb'] == 'true') ? true : false);
Or
$('#checkyes').prop('checked', (row['checkb'] == 'true') );
Or
var chk = (row['checkb'] == 'true') ? true : false; //Or var chk = (row['checkb'] == 'true');
$('#checkyes').prop('checked', chk );
Problem
row['checkb'] has value string true or false not Boolean value .
So $('#checkyes').prop('checked', row['checkb']); will evaluate to checked.
String value here prop('checked', String) makes it true for all cases .

From Tushar Gupta's answer, I'd suggest:
$('#checkyes').prop('checked', row['checkb'] == 'true');

var isResult = (row['checkb'] == 0) ? false : true;
$('#checkyes').prop('checked', isResult);
$('#checkyes').prop('checked', JSON.parse(row['checkb']));

Related

WebForms - Custom Validator No Longer Working

In my WebForms application I have a CustomValidator control. This control executes a JavaScript function that I created. If this function returns false, the form won't submit. This validator is used with the standard RequiredFieldValidator and RegularExpressionValitors.
This used to work perfectly fine, however, now, even if the JavaScript function returns false, the page will still submit. For some reason the CustomValidator is being ignored. As long as the RequiredFieldValidator and RegularExpressionValidator controls pass, the page will submit, even though the JavaScript function displays the errors on submission.
I have debugged the JavaScript function and it is definitely returning false. I didn't use any server side code with my CustomValidator.
JavaScript:
function validateForm() {
if (document.getElementById("DDApplicationID").selectedIndex > 0
&& document.getElementById("div_applicationType").style.display != "none") {
return true;
}
else if (document.getElementById("DDApplicationID").selectedIndex > 0) {
var valid = true;
((validateTrainStation() == false) ? valid = false : valid);
((validateSupportType() == false) ? valid = false : valid);
((validateHomeStatus() == false) ? valid = false : valid);
((validateOtherNationality() == false) ? valid = false : valid);
((validateOtherHomeStatus() == false) ? valid = false : valid);
((validateSortCode() == false) ? valid = false : valid);
((validateCareLeaverMessage() == false) ? valid = false : valid);
return valid; //returns false in JavaScript debugger on Chrome
}
}
Web Forms .aspx
<form id="Application" runat="server">
<asp:CustomValidator ID="CustomValidator1" runat="server" ValidationGroup="AllValidation" ClientValidationFunction="validateForm"></asp:CustomValidator>
<asp:Button ID="SaveLSFApplication" runat="server" Text="Submit Application" OnClick="saveApplication" ValidationGroup="AllValidation" />
</form>
WebForms .aspx.vb
Sub saveApplication(ByVal sender As Object, ByVal e As EventArgs)
If Page.IsValid Then
'--- do logic
End If
End Sub
I know just client side validation isn't good enough, but it's for parts of the form that are non-optional only when a specific criteria has been met, i.e. when a user selects "Other" in drop down box and we want them to put in a reason in a text box.
I've fixed this issue myself. Even though the JavaScript function was returning false, this means nothing in the context of a CustomValidator control. In order to prevent the form from submitting, the CustomValidator evaluates the property IsValid. If IsValid is false, then the form will not submit.
Here is the amended JavaScript function to reflect this change:
function validateForm(sender, args) { //added two function parameters
if (document.getElementById("DDApplicationID").selectedIndex > 0
&& document.getElementById("div_applicationType").style.display != "none") {
return true;
}
else if (document.getElementById("DDApplicationID").selectedIndex > 0) {
var valid = true;
((validateTrainStation() == false) ? valid = false : valid);
((validateSupportType() == false) ? valid = false : valid);
((validateHomeStatus() == false) ? valid = false : valid);
((validateOtherNationality() == false) ? valid = false : valid);
((validateOtherHomeStatus() == false) ? valid = false : valid);
((validateSortCode() == false) ? valid = false : valid);
((validateCareLeaverMessage() == false) ? valid = false : valid);
args.IsValid = valid; //no longer returning valid
}
}
As you can see, I've added two function parameters, sender and args. Then, instead of simply returning valid, I'm now setting the property IsValid of the args parameter to the value of valid. So, if valid is false, then IsValid is false. This IsValid is then evaluated which then prevents the form from continuing to submit.

jQuery - Field values and comparisons

I am making a form validation and want to check a number of radio button values. By default no values are selected. There are two options for each question - yes and no.
First I hide the 'caution message' and check whenever one of the inputs are changed. What I want to happen is when all options are set to no (value is N), then the error message will show, otherwise it will hide. I want it so that if any of the options are then changed to yes the error message will hide. What happens here is if any of the values are changed to yes the error message shows. Maybe I'm over complicating how this should work?
$('.cautionMessage').hide();
$('.weeeDetailsChange input').change(function () {
var ownBrand = $('input[name="ownbrand"]:checked').val();
var resell = $('input[name="resell"]:checked').val();
var ImportBasis = $('input[name="importbasis"]:checked').val();
var distributeEEE = $('input[name="distributeeee"]:checked').val();
var exportEU = $('input[name="exporteu"]:checked').val();
var distanceSelling = $('input[name="distanceselling"]:checked').val();
if ( ownBrand && resell && ImportBasis && distributeEEE && exportEU && distanceSelling === 'Y' ) {
$('.cautionMessage').show();
console.log('Show');
} else {
$('.cautionMessage').hide();
console.log('Hide');
}
});
Ah I see what's happening -- probably just needed a fresh set of eyes on this.
What you're currently doing is checking that only distanceSelling is yes whereas you should be checking that all values are no and running your show/hide based on that since you want to show the message if any of the values are 'yes'.
Try the following:
$('.cautionMessage').hide();
$('.weeeDetailsChange input').change(function () {
var ownBrand = $('input[name="ownbrand"]:checked').val();
var resell = $('input[name="resell"]:checked').val();
var ImportBasis = $('input[name="importbasis"]:checked').val();
var distributeEEE = $('input[name="distributeeee"]:checked').val();
var exportEU = $('input[name="exporteu"]:checked').val();
var distanceSelling = $('input[name="distanceselling"]:checked').val();
if (ownBrand == 'N' && resell == 'N' && ImportBasis == 'N' && distributeEEE == 'N' && exportEU == 'N' && distanceSelling == 'N' ) {
// all values are 'N'
$('.cautionMessage').show();
console.log('Show');
} else {
// not all values are 'N'
$('.cautionMessage').hide();
console.log('Hide');
}
});
I hope I understood that correctly. Hope that helps!
A couple of changes that I made. I use the property checked prop('checked') instead of val() because it actually returns me a Boolean so I do not need to compare it to y or anything. I then flip the hide and show where the caution message is only hidden when all check boxes are check. Click here to see example
$('.caution').hide();
$(".weeeDetailsChange").change(function(){
var ownBrand = $('input[name="ownbrand"]:checked').prop('checked')
var resell =$('input[name="resell"]:checked').prop('checked')
var ImportBasis = $('input[name="importbasis"]:checked').prop('checked')
var distributeEEE = $('input[name="distributeeee"]:checked').prop('checked')
var exportEU = $('input[name="exporteu"]:checked').prop('checked')
var distanceSelling = $('input[name="distanceselling"]:checked').prop('checked')
if ( ownBrand && resell && ImportBasis && distributeEEE && exportEU && distanceSelling) {
$('.caution').hide();
console.log('hide');
} else {
$('.caution').show();
console.log('show');
}
});

use variables in "document.Form1.checkbox.checked == true"

in
document.Form1.checkbox.checked == true
can i substitute Form1 and checkbox by javascript variables??
var a= checkbox;
var b= Form1;
document.b.a.checked == true
You can do it like this:
var form = 'Form1';
var field = 'checkbox';
document[form][field].checked == true
Also you can give ID for that checkbox and then use it.
document.getElementById('checkbox1').checked == true

Why does the order of Boolean values affect this program?

I created a basic program where user input is turned into an alert on submission. I can't figure out why the program only works as intended if I use false rather than true as the first condition in my if/else statement. I'm sure this is very basic but I've failed to find anything of relevance. After a long search I decided to post the question. Any answers will be greatly appreciated.
The HTML:
<form id="greetingForm">
<input type="text" name="userInput" id="userInput"/>
<input type="submit" value="click" id="submit"/>
</form>
The broken script:
function output(){
var input = document.getElementById('userInput').value;
if(input == true){
alert(input);
}else{
alert('Say something!');
}
}
function init(){
var greetingForm = document.getElementById('greetingForm');
greetingForm.onsubmit = output;
}
window.onload = init;
The working script:
function output(){
var input = document.getElementById('userInput').value;
if(input == false){
alert('Say something!');
}else{
alert(input);
}
}
function init(){
var greetingForm = document.getElementById('greetingForm');
greetingForm.onsubmit = output;
}
window.onload = init;
The variable input will never be equal to the boolean true because it is a string. Try changing it to:
function output(){
var input = document.getElementById('userInput').value;
if(input != ""){
alert(input);
}else{
alert('Say something!');
}
}
To clarify ferd tomale's answer, it's one of the "weird" type conversion cases where a check on equality to true does not behave in the same way as check on equality to false.
"" == false -> true
"a" == false -> false, but
"" == true -> false
"a" == true -> false
You can switch to using typesafe comparison operators (===, !==), which behave much more predictable, but then you'll have to convert values to the correct type yourself. Or you can learn the quirks of JS's automatic type conversion when you use == or !=.
Because your input is a string. And string == true will be false.
You can set breakpoints to check them.

javascript if fails

I do not see where my error is, If there is any
<!DOCTYPE html> <html> <head>
<script type="text/javascript">
//http://stackoverflow.com/questions/10251149/using-javascript-to-detect-google-chrome-to-switch-css
//provera brosera
function check_chrome_ua() {
var ua = navigator.userAgent.toLowerCase();
var is_chrome = /chrome/.test(ua);
alert("func check_chrome_ua() " + is_chrome);
return is_chrome;
}
//promena nadpisa
function check() {
//alert("check1");
var check = check_chrome_ua();
alert("var check " + check + "; func check_chrome_ua() " + check_chrome_ua());
if (check == "false") {
alert("change text");
document.getElementById("opomena").style.color = "red";
document.getElementById("opomena").innerHTML = 'Warning you are not using Google Chrome';
}
}
</script>
</head>
<body onmousemove="check()">
<div id="opomena">Thank you for using Google Chrome.</div>
</body>
</html>
Popups on Google Chrome popup says true, on Firefox says false
popup "change text" does not display in Firefox tho var check is false.
Thank you in advance for advice
Change
if (check == "false") {
to
if (!check) {
or
if (check == false) {
if you really want to check for the boolean value, false.
The regexp, test method which you call at /chrome/.test(ua) returns a boolean, but check == "false" is comparing that boolean to a string. The two are not equal.
In JavaScript, == is permissive when it comes to comparing strings to objects, but not as permissive as Perl's eq operator.
0 == false
false == false
"false" == [false]
false != "false"
0 != "false"
It's a good habit to try and use !== and === which are well-defined operators to compare primitive values.
You have to check for boolean value false, not "false" (it's a string).
Only if (!check) would be enough (or more verbose version if (check == false) ).

Categories

Resources