Truthy and falsey value (jQuery object) - javascript

I am implementing a function to check/uncheck radio buttons.
<!DOCTYPE html>
<html>
<head>
<title></title>
<script src = "http://code.jquery.com/jquery-2.1.4.min.js"> </script>
</head>
<body>
<form action="">
<input type="radio" name="sex" value="male" checked>Male<br>
<input type="radio" name="sex" value="female">Female
</form>
<script src = "../javascript/defaultCheckRadio.js"></script>
</body>
</html>
This code is doing the job, but I do not understand why the alert in the if block is never triggered. In my understanding, it should be triggered because all jQuery objects are truthy.
(function () {
var inElement = $('input');
var changeCheck = {
init: function () {
this.check();
},
check: function () {
$.each(inElement, function() {
var self = $(this);
if (self.checked) {
alert("if condition");
self.prop('checked',false);
} else {
alert("else");
self.prop('checked',true);
}
});
},
};
window.changeCheck = changeCheck.init();
})();

You have your if wrong, you are checking a javascript property on a jquery object, You should change:
if (self.checked) {
to:
if (self.prop('checked')) {

Just forget about jQuery and use vanilla-js:
if (this.checked) {
alert("if condition");
this.checked = false;
} else {
alert("else");
this.checked = true;
}
Note it can be simplified:
alert((this.checked = !this.checked) ? "else" : "if condition");

Related

how to get the value of checkbox currently unchecked in multi select dropdown list?

I am have created a multi select filter. For each of the options selected the new div element will be created with it's id is the value of checkbox selected. Till here it's working fine. But now I want to remove those div who's options(checkboxes) are un selected. I tried the below,
if(!($(this).is(":checked"))){
alert('is un-checked: ' + $(this).val());
}
but it's not working. Giving value of null. Can anyone please suggest me how can I achieve this?
CODE:
if (window.XMLHttpRequest)
{
areq = new XMLHttpRequest();
} else
{
areq = new ActiveXObject("Microsoft.XMLHTTP");
}
areq.onreadystatechange = function () {
if ((areq.readyState == 4) && (areq.status == 200)) {
document.getElementById("details7").innerHTML= areq.responseText;
var c=areq.responseText;
$('.matrb').SumoSelect({
triggerChangeCombined: false,
okCancelInMulti: true,
});
$('.matrb').on('change', function() {
if ($('option:selected', this).is(':checked')) {
alert('is checked: ' + $(this).val());
am=$(this).val();
nm=$(this).find('option:selected').attr("name");
am = am.toString().match(/\w+$/)[0];
console.log("am is:"+c);
}
else if(!($(this).is(":checked"))){
alert('is un-checked: ' + $(this).val());
}
if (window.XMLHttpRequest)
{
breq = new XMLHttpRequest();
} else
{
breq = new ActiveXObject("Microsoft.XMLHTTP");
}
breq.onreadystatechange = function () {
if ((breq.readyState == 4) && (breq.status == 200)) {
if(!( document.getElementById(am))){
var namee=document.createElement('p');
var newDiv=document.createElement('div');
newDiv.setAttribute('id', am);
newDiv.setAttribute("style","display:inline;");
namee.setAttribute("style","display:inline;");
var htm=breq.responseText;
newDiv.innerHTML=htm;
namee.innerHTML=nm;
console.log(htm);
console.log(newDiv);
document.getElementById("details8").appendChild(namee);
document.getElementById("details8").appendChild(newDiv);
}
var uncheckedValues = $("select#id").find('option').not(':selected');
var uncheckedArray = uncheckedValues.map(function () { return this.value;}).get();
console.log(uncheckedArray);
First of all, you need to bind change event for each checkbox so that whenever any checkbox is clicked (current one in your case) you can check if it is checked or unchecked.
$('#parent_container_selector').find('input[type="checkbox"]').each(function(index, element) {
$(this).on('change', function(){
//this is your current event! Grab it and do your logic here.
if($(this).is(':checked') == false)
{
//delete your required elements..
}
});
});
Something like this perhaps:
$('#checkboxes_container_id').find('input[type="checkbox"]')‌​.on('change', function (e) {
$('#checkboxes_container_id').find('input[type="checkbox"]').each(function(index, element) {
if (!$(this).is(':checked')) {
alert('is un-checked: ' + $(this).val());
return false; // in case you only want ONE alert
}
});
}
$('input[type=checkbox]').not(':checked')
$('#test').on('click', function() {
console.log($('input[type=checkbox]').not(':checked').length);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="checkbox" />
<input type="checkbox" />
<input type="checkbox" />
<input type="checkbox" />
<input type="checkbox" />
<input type="checkbox" />
<button id="test">Test</button>
$('input[type=checkbox]').on('change', function() {
if(!this.checked){
console.log('unchecked checkbox');
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="checkbox" />
<input type="checkbox" />
<input type="checkbox" />
<input type="checkbox" />
<input type="checkbox" />
<input type="checkbox" />
<button id="test">Test</button>
You can use "not" for the selecion
$('[attribute="value"]:not(":checked")').each(function() {
alert($(this).val());
});
Check this https://jsfiddle.net/wrajesh/3ga508x3/3/
Finally I found the solution. below is the code for that,
$('#myselect').on('change', function() {
var $sel = $(this),
val = $(this).val(),
$opts = $sel.children(),
prevUnselected = $sel.data('unselected');
// create array of currently unselected
var currUnselected = $opts.not(':selected').map(function() {
return this.value
}).get();
// see if previous data stored
if (prevUnselected) {
// create array of removed values
var unselected = currUnselected.reduce(function(a, curr) {
if ($.inArray(curr, prevUnselected) == -1) {
a.push(curr)
}
return a
}, []);
// "unselected" is an array
if(unselected.length){
alert('Unselected is ' + unselected.join(', '));
}
}
$sel.data('unselected', currUnselected)
}).change();
posting this because it may help someone.

Javascript Not Working/Loading

I've tried working with some code from JSFiddle, and it is working fine.
Although when I try and implement it in HTML, it doesn't work the same way.
Here's what I have so far:
Javascript:
var checker = document.getElementById('checkme');
var sendbtn = document.getElementById('sendNewSms');
checker.onchange = function(){
if(this.checked){
sendbtn.disabled = false;
} else {
sendbtn.disabled = true;
}
}
HTML:
<h1>Button should be enabled if at least one checkbox is checked</h1>
<input type="checkbox" id="checkme"/><input type="submit" name="sendNewSms" class="inputButton" id="sendNewSms" value=" Send " disabled/>
You need to wrap the script inside window.onload event to make sure that the dom elements are available.
window.onload = function() {
var checker = document.getElementById('checkme');
var sendbtn = document.getElementById('sendNewSms');
checker.onchange = function(){
if(this.checked) sendbtn.disabled = true;
else sendbtn.disabled = false;
}
}
<input type="checkbox" id="checkme"/>
<input type="submit" name="sendNewSms" class="inputButton" id="sendNewSms" value=" Send " />
Your javascript needs to be in <script> tags. It's not clear if they are or not by your question, so I'll assume they're not:
<html>
<head><title>Still learning</title></head>
<body>
<script type="text/javascript">
window.onload = function() {
var checker = document.getElementById('checkme');
var sendbtn = document.getElementById('sendNewSms');
checker.onchange = function(){
if(this.checked){
sendbtn.disabled = false;
} else {
sendbtn.disabled = true;
}
}
};
</script>
<h1>Button should be enabled if at least one checkbox is checked</h1>
<input type="checkbox" id="checkme"/><input type="submit" name="sendNewSms" class="inputButton" id="sendNewSms" value=" Send " disabled/>
</body>
</html>
Read up on html basics
This one: Uncaught TypeError: Cannot set property 'onchange' of null
Your javascript is executing before the html finishes completely loading.
This is why document.getElementById('checkme') is returning null. Put the function into a window.onload and insert the script into the <head> like this.
<html>
<head><title>Still learning</title>
<script>
window.onload = function() {
var checker = document.getElementById('checkme');
var sendbtn = document.getElementById('sendNewSms');
checker.onchange = function(){
if(this.checked){
sendbtn.disabled = false;
} else {
sendbtn.disabled = true;
}
}
};
</script>
</head>
<body>
<h1>Button should be enabled if at least one checkbox is checked</h1>
<input type="checkbox" id="checkme"/><input type="submit" name="sendNewSms" class="inputButton" id="sendNewSms" value=" Send " disabled/>
</body>
</html>
It should work now. See this fiddle: http://jsfiddle.net/brbcoding/n9z5D/

Enable/Disable a button on select of radio button in jquery

I have a page in which there are 2 radio buttons and a next button. I have made next button disabled and it is enabled only when I select any radio button. But now when I go to another page and come back to this page the next button comes as disabled although the radio button is already selected. PFB the code
$(document).ready(function () {
$('#commandButton_1_0').attr('disabled', 'true');
$('input:radio[name=a_SignatureOption]').click(function () {
var checkval = $('input:radio[name=a_SignatureOption]:checked').val();
if (checkval == '1' || checkval == '2') {
$('#commandButton_1_0').removeAttr('disabled');
}
});
});
Try
$(document).ready(function() {
$('input:radio[name=a_SignatureOption]').click(function() {
var checkval = $('input:radio[name=a_SignatureOption]:checked').val();
$('#commandButton_1_0').prop('disabled', !(checkval == '1' || checkval == '2'));
});
});
Demo: Fiddle
I took time to understand your problem,
This can be solved by unchecking the radio while loading the page.
$(document).ready(function () {
$('input:radio[name=a_SignatureOption]').prop('checked', false);
$('#commandButton_1_0').attr('disabled', 'true');
$('input:radio[name=a_SignatureOption]').click(function () {
var checkval = $('input:radio[name=a_SignatureOption]:checked').val();
if (checkval == '1' || checkval == '2') {
$('#commandButton_1_0').removeAttr('disabled');
}
});
});
check out JSFiddle, btw redirect to other site and press back button to find the difference.
Hope you understand.
// Try this.............
$(document).ready(function () {
$("input:radio[name=a_SignatureOption]").removeAttr('checked');
$('#commandButton_1_0').attr("disabled","disabled");
$('input:radio[name=a_SignatureOption]').click(function () {
var checkval = $('input:radio[name=a_SignatureOption]:checked').val();
if (checkval == '1' || checkval == '2') {
$('#commandButton_1_0').removeAttr("disabled","disabled");
}
});
});
It is simple as your question is
<form name="urfrm">
<input type="radio" value="1" name="a_SignatureOption"> Yes<br>
<input type="radio" value="2" name="a_SignatureOption"> No<br>
<input type="submit" id="butn" name="butn" value="next" disabled><br>
</form>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<script>
$(document).ready(function() {
//This will check the status of radio button onload
$('input[name=a_SignatureOption]:checked').each(function() {
$("#butn").attr('disabled',false);
});
//This will check the status of radio button onclick
$('input[name=a_SignatureOption]').click(function() {
$("#butn").attr('disabled',false);
});
});
</script>
The easiest solution I can think of - albeit somewhat belatedly, is:
// selects all input elements, whose name is 'a_SignatureOption' and whose
// type is 'radio'
// binds a change event-handler, using 'on()':
$('input[name=a_SignatureOption][type="radio"]').on('change', function(){
// sets the 'disabled' property of the button to 'true' if zero radio inputs
// are checked, or to false if one is checked:
$('#commandButton_1_0').prop('disabled', $('input[name=a_SignatureOption][type="radio"]:checked').length === 0);
// triggers the change event-handler on page load:
}).change();
References:
Attribute-equals ([attribute="value"]) selector.
change().
on().
prop().
On load of document you need to check whether radio button is clicked or not
$(document).ready(function() {
$('input:radio[name=a_SignatureOption]').each(function() {
checked(this);
});
$('input:radio[name=a_SignatureOption]').click(function() {
checked(this);
});
function checked(obj){
if($(obj).is(':checked')) {
$('#commandButton_1_0').removeAttr('disabled');
}else{
$('#commandButton_1_0').attr('disabled', 'true');
}
}
});
You forgot to check the buttons at the beginning.
$(document).ready(function () {
$('#commandButton_1_0').attr('disabled', 'true');
if( $('input[name=a_SignatureOption]:checked' ).size() > 0 ) {
$('#commandButton_1_0').removeAttr('disabled');
}
$('input[name=a_SignatureOption]').click(function () {
if( $('input:radio[name=a_SignatureOption]:checked' ).size() > 0 ) {
$('#commandButton_1_0').removeAttr('disabled');
}
});
});
By the way, I always suggest to add classes to form elements and work with those, instead of using [name="..."]. It's quicker and simplier and you can change input names (if necessary) without touching js
<html>
<head>
<script src="http://code.jquery.com/jquery-1.10.2.js"></script>
<script>
$(document).ready(function () {
$('#commandButton_1_0').attr('disabled', 'true');
$('input:radio[name=a_SignatureOption]').click(function () {
var checkval = $('input:radio[name=a_SignatureOption]:checked').val();
alert(checkval)
if (checkval == '1' || checkval == '2') {
$('#commandButton_1_0').removeAttr('disabled');
}
else {
$('#commandButton_1_0').attr('disabled', 'disabled');
}
});
});
</script>
</head>
<body>
<input type="radio" name="a_SignatureOption" value="1" /> value1
<br />
<input type="radio" name="a_SignatureOption" value="2"/> value2
<br />
<input type="radio" name="a_SignatureOption" value="3" checked="checked"/> value3
<br />
<input type="button" id="commandButton_1_0" value="Next"/>
</body>
</html>

JavaScript Validation

I am using the following code to check if at least one checkbox is selected from my checkboxlist in asp.net. I am using jGrowl to throw up a message which works, but the message is still displayed if a selection is made. Any ideas? Also, story_type is an asp label, I am using the code below, but I can't get the jGrowl message to display...
var story_type = document.getElementById('story_type').value;
var agile_list = document.getElementById('agile_factors');
var arrayOfCheckBoxes = agile_list.getElementsByTagName("input");
for (counter = 0; counter < arrayOfCheckBoxes.length; counter++) {
if (arrayOfCheckBoxes[counter].checked) {
return true;
} else {
(function($) {
$.jGrowl("Please Choose up to 3 Agile Factors", { theme: 'smoke', closer: true });
})(jQuery);
return false;
}
}
if (story_type == "[SELECT TYPE]") {
(function($) {
$.jGrowl("Please Select Story Type", { theme: 'smoke', sticky: true, closer: true })
return false;
})(jQuery);
return true;
}
Since you have jQuery you can do this to simplify your code a bit:
<div id="options">
<input type="checkbox" name="opt1" /> Option 1
<input type="checkbox" name="opt2" /> Option 2
<input type="checkbox" name="opt3" /> Option 3
<input type="checkbox" name="opt4" /> Option 4
</div>
<div>
validate
</div>
<script type="text/javascript">
;(function() {
$("#validate").click(function() {
validateInputs();
});
function validateInputs() {
alert($("#options input:checked").length + " checked");
}
})();
</script>
Here is a jsFiddle of the above code; http://jsfiddle.net/rvXHG/

Input Type: Separating JavaScript Code From Front End Code

The following is code that is within an html file. What is the ideal way to separate the JavaScript code (if (this.value etc etc)) from html file?
input type="text" name="username" onblur="if (this.value == '') {this.value = 'email';}" onfocus="if (this.value == 'email') {this.value = '';}"
<head>
<script type="text/javascript">
function ClearDefValue (input) {
if (input.value == '') {
input.value = input.defaultValue;
}
}
function SetDefValue (input) {
if (input.value == input.defaultValue) {
input.value = '';
}
}
</script>
</head>
<body>
<input type="text" name="username" value="email" onblur="ClearDefValue (this)" onfocus="SetDefValue (this)" />
</body>
If you want to put the JavaScript content into an external file:
HTML file:
<head>
<script type="text/javascript" src="utils.js"></script>
</head>
<body>
<input type="text" name="username" value="email" onblur="ClearDefValue (this)" onfocus="SetDefValue (this)" />
</body>
utils.js file:
function ClearDefValue (input) {
if (input.value == '') {
input.value = input.defaultValue;
}
}
function SetDefValue (input) {
if (input.value == input.defaultValue) {
input.value = '';
}
}
Related links:
script element,
onblur event,
onfocus event.
<!doctype html>
<html><head>
<script src="file.js"></script></head><body>
<input id="foo" type="text">
</body></html>
Method #1:
in file.js which you reference in the <head> with a <script>:
window.onload = function() {
var input = document.getElementById('foo');
input.onfocus = function() { if ( this.value == '' ) { this.value = 'blah';} }
input.onblur = function() { if ( this.value == 'blah') { this.value = ''; } }
}
And ideally you'd want to use an addEvent function which supports dom listeners.
Method #2:
The (arguably) more elegant way would be:
var addEvent = (function() {
function addEventIE(el, ev, fn) {
return el.attachEvent('on' + ev, function(e) {
return fn.call(el, e);
});
}
function addEventW3C(el, ev, fn) {
return el.addEventListener(ev, fn, false);
}
return window.addEventListener ? addEventW3C:addEventIE;
})();
addEvent(window, 'load', function() {
var input = document.getElementById('foo');
addEvent(input, 'blur', function(){});
addEvent(input, 'focus', function(){});
});
Method #3:
You can also avoid the whole onload and addEvent nonsense and just put your script before the end body tag if it's a fairly simplistic site.
<script src="file.js"></script>
</body>
file.js:
var input = document.getElementById('foo');
input.onfocus = function() { if ( this.value == '' ) { this.value = 'blah';} }
input.onblur = function() { if ( this.value == 'blah') { this.value = ''; } }

Categories

Resources