Always getting the same value if the checkbox is unchecked also - javascript

Input checkbox will be like this
<input id="idCheckbox" name="check" type="checkbox" value="AllValue" style="width: auto; height: auto; font-weight: bolder;" data-bind="checked: idCheckbox" />
Always getting the same value (AllValue) if the checkbox is unchecked also.
var AllPoliciesChk = document.getElementById("idCheckbox").value;

try it, its working fine for me. I have used jquery here is the working example in jsfiddle https://jsfiddle.net/26Ltymkx/
jquery code
var AllPoliciesChk = document.getElementById("idCheckbox").value;
$(document).on('click', '#idCheckbox', function(){
if ($('#idCheckbox').is(":checked")) {
//...your code
}
}
})

Related

check if all inputs are checked

I have 2 buttons and 2 inputs. The "buy"-button should only fire its default function when both inputs are checked. If not it should mark them with a red border. What am I doing wrong here?
jQuery(function($) {
$('.checkedterms:checked').length == $('.checkedterms').length
$("#upsellyes").click(function(e) {
$(".checkedterms").change(function(){
if (!$('.checkedterms:checked').length == $('.checkedterms').length) {
e.preventDefault();
$("#terms-required").addClass('invalid');
}
else {
$("#terms-required").removeClass('invalid');
}
});
});
});
.invalid {
border: 1px solid red;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="terms-required">
<input type="checkbox" class="checkedterms" name="terms" id="terms" style="position: absolute;"><label for="terms" class="checkbox" style="display: inline-block!important;font-weight:normal!important;margin-left: 25px;">I have read <a href="#" >Allgemeinen Geschäftsbedingungen</a>.<span class="required">*</span></label><br />
<input type="checkbox" class="checkedterms" name="terms" id="terms" style="position: absolute;"><label for="terms" class="checkbox" style="display: inline-block!important;font-weight:normal!important;margin-left: 25px;">I have read <a href="#" >Widerrufsbelehrung</a>.<span class="required">*</span></label><br />
</div><br>
buy<br><br>
no thanks
There's a couple of issues here:
You've got an equality check at the start of the code which does nothing.
You've nested the change handler on the checkboxes within the click handler of the button; remove it.
Unrelated to the issue, but you are using duplicate id attributes. They need to be unique within the DOM.
Your logic is backwards. You state that you want the red border to only appear when both checkboxes are not checked when the 'Buy' button is clicked.
You can also make the logic more succinct by caching the checkbox selector and using toggleClass(). Something like this:
jQuery(function($) {
$("#upsellyes").click(function(e) {
var $terms = $('.checkedterms');
$("#terms-required").toggleClass('invalid', $terms.length != $terms.filter(':checked').length);
});
});
.invalid {
border: 1px solid red;
}
.checkedterms {
position: absolute;
}
label {
display: inline-block!important;
font-weight: normal!important;
margin-left: 25px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="terms-required">
<input type="checkbox" class="checkedterms" name="terms" />
<label for="terms" class="checkbox">
I have read Allgemeinen Geschäftsbedingungen.
<span class="required">*</span>
</label><br />
<input type="checkbox" class="checkedterms" name="terms" />
<label for="terms" class="checkbox">
I have read <a href="#" >Widerrufsbelehrung</a>.
<span class="required">*</span>
</label><br />
</div><br />
buy<br><br>
no thanks
Finally note the use of a separate stylesheet. Inline styling is a bad idea and should be avoided where possible.
remove this line
$(".checkedterms").change(function(){ //remove
//keep the code that's currently here
}); //remove
leaving you with
jQuery(function($) {
$('.checkedterms:checked').length == $('.checkedterms').length
$("#upsellyes").click(function(e) {
if ($('.checkedterms:checked').length != $('.checkedterms').length) {
e.preventDefault();
$("#terms-required").addClass('invalid');
}
else {
$("#terms-required").removeClass('invalid');
}
});
});
the code wasn't running because you were setting an event listener on the checkboxes inside the event listener on the button. what was happening is that when you clicked the button, javascript would set an event listener on the checkboxes that fires when their state changes
You need an if statement at line 2 and one more '='
if ($('.checkedterms:checked').length === $('.checkedterms').length) {
....
}
and you should put an eventListener each input change

Check which checkboxes is checked

I have read this post and this post and others but i didnt get it to work in my code.
here is the Fiddle for better see my code on live.
this is my js
//////first code to try////
if ($('input.chek').is(':checked')) {
$('.check-addon').css('background-color','green');
}
//////second code///////
var boxes = $('input[class="chek"]:checked');
$(boxes).each(function(){
$('.check-addon').css('background-color','green');
});
this is my html
<div class="inline-container"><div class="checkboxes" >
<span class="check-addon"><input id="id1" class="chek" type="checkbox" value="1" name="id1">title1</span>
<span class="check-addon"><input id="id2" type="checkbox" class="chek" value="1" name="id2">title2</span>
<span class="check-addon"><input id="id3" type="checkbox" class="chek" value="1" name="id3">title3</span>
</div></div>
i dont know what im doing wrong here . i couldnt get the background Green Of the checked box in my code.
any help would much apreciated.
EDIT
even the answers down works in fiddle But i guess i have more problem here.
if i write html code above Normal , the js code is fired and works But im using html code inside js function like that:
function houses(){
var x ='<div class="inline-container"><div class="checkboxes" >
<span class="check-addon"><input id="id1" class="chek" type="checkbox" value="1" name="id1">title1</span>
<span class="check-addon"><input id="id2" type="checkbox" class="chek" value="1" name="id2">title2</span>
<span class="check-addon"><input id="id3" type="checkbox" class="chek" value="1" name="id3">title3</span>
</div></div>';
return x ;
}
so this function when i call it it works but when i want apply the above code on it its not working and not firing at all.
this function is Out of the Dom handler. Fiddle here
Bind the input with a on change event
$('.chek').on('change', function () {
$(this).closest('.check-addon').css('background-color',this.checked?'green':'none');
});
DEMO
Update
You need to use event-delegation on dynamically added elements
$(document).on('change','.chek',function(){
$(this).closest('.check-addon').css('background-color',this.checked?'green':'none');
});
You need to use click/change event to detect the changes on checkboxes. Use:
$('input').change(function(){
if (this.checked)
$(this).parent().css('background-color','green');
else
$(this).parent().css('background-color','none');
});
Demo
You can use this:
$("input:checkbox").on("change", function(){
if($(this).prop("checked")){
$(this).parent(".check-addon").css('background-color','green');
}
else{
$(this).parent(".check-addon").css('background-color','white');
}
});
fiddle
You have to do like this :
1st Way:
$(".chek").change(function () { // will fire when checkbox checked or unchecked
if (this.checked) // check if it is checked
$(this).closest(".check-addon").css('background-color', 'green'); //find parent span and add css
else
$(this).closest(".check-addon").css('background-color','transparent');
})
FIDDLE:
http://jsfiddle.net/2u697b57
2nd Way:
More better approach is to create a css class and add/remove it on check/uncheck:
CSS:
.green
{
background-color:green;
}
JQUERY:
$(".chek").change(function () {
if (this.checked)
$(this).closest(".check-addon").addClass("green");
else
$(this).closest(".check-addon").removeClass("green");
FIDDLE:
http://jsfiddle.net/2u697b57/1/

Linking checkboxes to text inputs and updating its fields

I am trying to link a checkbox to a text input in order to update the value inside the input field.
My problem is how do I update the value accordingly when the checkbox is ticked. For example, I would like to have a text stating status is "Pending" (with the checkbox unticked) and once the box is ticked, update the value to "Completed" and possibly highlight the text input to a green colour.
Picture:
Code:
<div class="status-updates">
<label class="radio" for="status-updates">
<input type="checkbox" name="status" id="statuses">
</label>
<input type="text" name="pending-completed" id="pending-completed" class="pending-completed" placeholder="Pending">
</div>
Do I need some sort of jQuery to run some sort of input validation?
Would appreciate some help on this.
Thank you.
Try below jquery code(bind .change() event of checkbox) :-
$('#statuses').change(function(){
if($(this).is(':checked'))
{
$("#pending-completed").attr('placeholder','Completed')
}
else
{
$("#pending-completed").attr('placeholder','Pending')
}
});
EDIT(Placeholder with green color) :-
Jquery :
$('#statuses').change(function(){
if($(this).is(':checked'))
{
$("#pending-completed").attr('placeholder','Completed').addClass('green-class')
}
else
{
$("#pending-completed").attr('placeholder','Pending').removeClass('green-class')
}
});
CSS :
.green-class::-webkit-input-placeholder {
color: green;
}
DEMO
Try this : bind change event to checkbox and put placeholder as per checkbox checked status.
$(function(){
$('#statuses').change(function(){
var placeholder = $(this).is(':checked')?"Completed":"Pending";
$("#pending-completed").attr('placeholder',placeholder);
});
});
LIVE DEMO: http://jsfiddle.net/don/qaxow1jz/
jQuery:
$('input[name=status]').change(function() {
var inputText = 'input[name=pending-completed]';
if($(this).is(':checked')) {
$(inputText).attr('placeholder', 'Completed').addClass('highlight');
} else {
$(inputText).attr('placeholder', 'Pending').removeClass('highlight');
}
});
HTML:
<div class="status-updates">
<label class="radio" for="status-updates">
<input type="checkbox" name="status" id="statuses">
</label>
<input type="text" name="pending-completed" id="pending-completed" class="pending-completed" placeholder="Pending">
</div>
CSS:
input.highlight[name=pending-completed]::-webkit-input-placeholder {
color: green;
}
input.highlight[name=pending-completed]:-moz-placeholder {
color: green;
}
input.highlight[name=pending-completed]::-moz-placeholder {
color: green;
}
input.highlight[name=pending-completed]:-ms-input-placeholder {
color: green;
}
Have a look at this . Working example : http://jsfiddle.net/gmwzzL10/
HTML
<div class="status-updates">
<label class="radio" for="status-updates">
<input type="checkbox" name="status" id="statuses" class="checkbox_status">
</label>
<input type="text" name="pending-completed" id="pending-completed" class="pending-completed" placeholder="Pending">
</div>
JS
$("document").ready(function(){
$(".checkbox_status").click(function(){
var inputBox = $(this).closest(".status-updates").find(".pending-completed");
if($(this).is(':checked')){
inputBox.attr("placeholder","Completed").addClass("make-green");
}
else{
inputBox.attr("placeholder","Pending").removeClass("make-green");
}
})
})
CSS
.make-green{
border: 1px solid green;
}

Issue showing div with jquery

I seem to be having a hard time displaying a div when a checkbox is clicked, the issue is pretty straight forward, but i cant seem to find the right jquery solution to resolve this, though i feel like i am very close.
$html=
'<form action="contacted.php" method="POST">
<input type = "hidden" name = "contact" class = "hidden" value = "'.$ip.'">
<input type="checkbox" id="contact'.$ip.'" value = "'.$ip.'" onclick="show()"/>
<div class="hide" style="
display:none;
border:3px
solid black;
background-color:grey;
color:white;
width:200px;
position:absolute;
left:40%;
top:20%;
-moz-border-radius: 15px;
border-radius: 15px;
padding:4px;
z-index:1000;
Width:500px;
">
<textarea name = "notes" style = "" > Let\'s get some notes about that...</textarea>
<input type="submit" value="YES"/>
<input type="button" value="NO" onclick="hide()">
</div>
</form>';
this is in a for loop and $ip is an identifier. but its pretty straight forward.
jquery that i have tried
function show(){
$(this).parent().find('.hide').css("display","block")
}
im trying to display the div hide when the checkbox is clicked (this happens multiple times on the same page) and i cant piece together the right combination from the jquery documentation. Any ideas? im sure this will be simple, I am more than willing to except javascript suggestions :)
add class to input like this and try it please
<input type="checkbox" id="contact'.$ip.'" class="contact_click" value="'.$ip.'" onclick="show()"/>
$('.contact_click').on('click',function(){
$(this).closest('div').css('css','block');
});
Try this
Change
<input type="checkbox" id="contact'.$ip.'" value = "'.$ip.'" onclick="show()"/>
to
<input type="checkbox" id="contact'.$ip.'" value = "'.$ip.'" onclick="show(this)"/>
and script as
function show()
{
this.parent().find('.hide').css("display","block");
}
Pass the clicked element into your function like this
<input type="checkbox" id="contact'.$ip.'" value = "'.$ip.'" onclick="show(this)"/>
and
function show(element){
$(element).parent().find('.hide').css("display","block");
}
you dont even need the class the checkbox is a direct child of the div.
$(this).parent().show(0);
just make sure you bind the click handler to the check box and that will definitely work.
and just to make sure you are binding the event right try this when you click the check box
function test(){
var test = $(this).parent().attr('class');
alert(test);
}
and you should get hide. so if you get hide it is binded correctly

How can I know which radio button is selected via jQuery?

I have two radio buttons and want to post the value of the selected one.
How can I get the value with jQuery?
I can get all of them like this:
$("form :radio")
How do I know which one is selected?
To get the value of the selected radioName item of a form with id myForm:
$('input[name=radioName]:checked', '#myForm').val()
Here's an example:
$('#myForm input').on('change', function() {
alert($('input[name=radioName]:checked', '#myForm').val());
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form id="myForm">
<fieldset>
<legend>Choose radioName</legend>
<label><input type="radio" name="radioName" value="1" /> 1</label> <br />
<label><input type="radio" name="radioName" value="2" /> 2</label> <br />
<label><input type="radio" name="radioName" value="3" /> 3</label> <br />
</fieldset>
</form>
Use this..
$("#myform input[type='radio']:checked").val();
If you already have a reference to a radio button group, for example:
var myRadio = $("input[name=myRadio]");
Use the filter() function, not find(). (find() is for locating child/descendant elements, whereas filter() searches top-level elements in your selection.)
var checkedValue = myRadio.filter(":checked").val();
Notes: This answer was originally correcting another answer that recommended using find(), which seems to have since been changed. find() could still be useful for the situation where you already had a reference to a container element, but not to the radio buttons, e.g.:
var form = $("#mainForm");
...
var checkedValue = form.find("input[name=myRadio]:checked").val();
This should work:
$("input[name='radioName']:checked").val()
Note the "" usaged around the input:checked and not '' like the Peter J's solution
You can use the :checked selector along with the radio selector.
$("form:radio:checked").val();
If you want just the boolean value, i.e. if it's checked or not try this:
$("#Myradio").is(":checked")
Get all radios:
var radios = jQuery("input[type='radio']");
Filter to get the one thats checked
radios.filter(":checked")
Another option is:
$('input[name=radioName]:checked').val()
$("input:radio:checked").val();
In my case I have two radio buttons in one form and I wanted to know the status of each button.
This below worked for me:
// get radio buttons value
console.log( "radio1: " + $('input[id=radio1]:checked', '#toggle-form').val() );
console.log( "radio2: " + $('input[id=radio2]:checked', '#toggle-form').val() );
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form id="toggle-form">
<div id="radio">
<input type="radio" id="radio1" name="radio" checked="checked" /><label for="radio1">Plot single</label>
<input type="radio" id="radio2" name="radio"/><label for="radio2">Plot all</label>
</div>
</form>
Here's how I would write the form and handle the getting of the checked radio.
Using a form called myForm:
<form id='myForm'>
<input type='radio' name='radio1' class='radio1' value='val1' />
<input type='radio' name='radio1' class='radio1' value='val2' />
...
</form>
Get the value from the form:
$('#myForm .radio1:checked').val();
If you're not posting the form, I would simplify it further by using:
<input type='radio' class='radio1' value='val1' />
<input type='radio' class='radio1' value='val2' />
Then getting the checked value becomes:
$('.radio1:checked').val();
Having a class name on the input allows me to easily style the inputs...
try this one.
it worked for me
$('input[type="radio"][name="name"]:checked').val();
In a JSF generated radio button (using <h:selectOneRadio> tag), you can do this:
radiobuttonvalue = jQuery("input[name='form_id\:radiobutton_id']:checked").val();
where selectOneRadio ID is radiobutton_id and form ID is form_id.
Be sure to use name instead id, as indicated, because jQuery uses this attribute (name is generated automatically by JSF resembling control ID).
Also, check if the user does not select anything.
var radioanswer = 'none';
if ($('input[name=myRadio]:checked').val() != null) {
radioanswer = $('input[name=myRadio]:checked').val();
}
If you have Multiple radio buttons in single form then
var myRadio1 = $('input[name=radioButtonName1]');
var value1 = myRadio1.filter(':checked').val();
var myRadio2 = $('input[name=radioButtonName2]');
var value2 = myRadio2.filter(':checked').val();
This is working for me.
I wrote a jQuery plugin for setting and getting radio-button values. It also respects the "change" event on them.
(function ($) {
function changeRadioButton(element, value) {
var name = $(element).attr("name");
$("[type=radio][name=" + name + "]:checked").removeAttr("checked");
$("[type=radio][name=" + name + "][value=" + value + "]").attr("checked", "checked");
$("[type=radio][name=" + name + "]:checked").change();
}
function getRadioButton(element) {
var name = $(element).attr("name");
return $("[type=radio][name=" + name + "]:checked").attr("value");
}
var originalVal = $.fn.val;
$.fn.val = function(value) {
//is it a radio button? treat it differently.
if($(this).is("[type=radio]")) {
if (typeof value != 'undefined') {
//setter
changeRadioButton(this, value);
return $(this);
} else {
//getter
return getRadioButton(this);
}
} else {
//it wasn't a radio button - let's call the default val function.
if (typeof value != 'undefined') {
return originalVal.call(this, value);
} else {
return originalVal.call(this);
}
}
};
})(jQuery);
Put the code anywhere to enable the addin. Then enjoy! It just overrides the default val function without breaking anything.
You can visit this jsFiddle to try it in action, and see how it works.
Fiddle
$(".Stat").click(function () {
var rdbVal1 = $("input[name$=S]:checked").val();
}
This works fine
$('input[type="radio"][class="className"]:checked').val()
Working Demo
The :checked selector works for checkboxes, radio buttons, and select elements. For select elements only, use the :selected selector.
API for :checked Selector
To get the value of the selected radio that uses a class:
$('.class:checked').val()
I use this simple script
$('input[name="myRadio"]').on('change', function() {
var radioValue = $('input[name="myRadio"]:checked').val();
alert(radioValue);
});
Use this:
value = $('input[name=button-name]:checked').val();
DEMO : https://jsfiddle.net/ipsjolly/xygr065w/
$(function(){
$("#submit").click(function(){
alert($('input:radio:checked').val());
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table>
<tr>
<td>Sales Promotion</td>
<td><input type="radio" name="q12_3" value="1">1</td>
<td><input type="radio" name="q12_3" value="2">2</td>
<td><input type="radio" name="q12_3" value="3">3</td>
<td><input type="radio" name="q12_3" value="4">4</td>
<td><input type="radio" name="q12_3" value="5">5</td>
</tr>
</table>
<button id="submit">submit</button>
If you only have 1 set of radio buttons on 1 form, the jQuery code is as simple as this:
$( "input:checked" ).val()
I've released a library to help with this. Pulls all possible input values, actually, but also includes which radio button was checked. You can check it out at https://github.com/mazondo/formalizedata
It'll give you a js object of the answers, so a form like:
<form>
<input type="radio" name"favorite-color" value="blue" checked> Blue
<input type="radio" name="favorite-color" value="red"> Red
</form>
will give you:
$("form").formalizeData()
{
"favorite-color" : "blue"
}
JQuery to get all the radio buttons in the form and the checked value.
$.each($("input[type='radio']").filter(":checked"), function () {
console.log("Name:" + this.name);
console.log("Value:" + $(this).val());
});
To retrieve all radio buttons values in JavaScript array use following jQuery code :
var values = jQuery('input:checkbox:checked.group1').map(function () {
return this.value;
}).get();
try it-
var radioVal = $("#myform").find("input[type='radio']:checked").val();
console.log(radioVal);
Another way to get it:
$("#myForm input[type=radio]").on("change",function(){
if(this.checked) {
alert(this.value);
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form id="myForm">
<span><input type="radio" name="q12_3" value="1">1</span><br>
<span><input type="radio" name="q12_3" value="2">2</span>
</form>
From this question, I came up with an alternate way to access the currently selected input when you're within a click event for its respective label. The reason why is because the newly selected input isn't updated until after its label's click event.
TL;DR
$('label').click(function() {
var selected = $('#' + $(this).attr('for')).val();
...
});
$(function() {
// this outright does not work properly as explained above
$('#reported label').click(function() {
var query = $('input[name="filter"]:checked').val();
var time = (new Date()).toString();
$('.query[data-method="click event"]').html(query + ' at ' + time);
});
// this works, but fails to update when same label is clicked consecutively
$('#reported input[name="filter"]').on('change', function() {
var query = $('input[name="filter"]:checked').val();
var time = (new Date()).toString();
$('.query[data-method="change event"]').html(query + ' at ' + time);
});
// here is the solution I came up with
$('#reported label').click(function() {
var query = $('#' + $(this).attr('for')).val();
var time = (new Date()).toString();
$('.query[data-method="click event with this"]').html(query + ' at ' + time);
});
});
input[name="filter"] {
display: none;
}
#reported label {
background-color: #ccc;
padding: 5px;
margin: 5px;
border-radius: 5px;
cursor: pointer;
}
.query {
padding: 5px;
margin: 5px;
}
.query:before {
content: "on " attr(data-method)": ";
}
[data-method="click event"] {
color: red;
}
[data-method="change event"] {
color: #cc0;
}
[data-method="click event with this"] {
color: green;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form id="reported">
<input type="radio" name="filter" id="question" value="questions" checked="checked">
<label for="question">Questions</label>
<input type="radio" name="filter" id="answer" value="answers">
<label for="answer">Answers</label>
<input type="radio" name="filter" id="comment" value="comments">
<label for="comment">Comments</label>
<input type="radio" name="filter" id="user" value="users">
<label for="user">Users</label>
<input type="radio" name="filter" id="company" value="companies">
<label for="company">Companies</label>
<div class="query" data-method="click event"></div>
<div class="query" data-method="change event"></div>
<div class="query" data-method="click event with this"></div>
</form>
$(function () {
// Someone has clicked one of the radio buttons
var myform= 'form.myform';
$(myform).click(function () {
var radValue= "";
$(this).find('input[type=radio]:checked').each(function () {
radValue= $(this).val();
});
})
});

Categories

Resources