I still learning javascript, i think this is ez question, but i can't fix it with my experience (already try search some source), this my code
This is example:
PHP
<?php
<input type="checkbox" checked="checked" value="1" class="box_1">1</label> // checked
<input type="checkbox" value="2" class="box_1">2</label> //unchecked
<input type="checkbox" checked="checked" value="3" class="box_1">3</label> // checked
<input type="checkbox" value="4" class="box_1">4</label> //unchecked
<input type="checkbox" checked="checked" value="5" class="box_1">5</label> // checked
<input type="button" value="Submit" id="button-price" class="button" />
?>
I try check the check box with javasript by class, (i can't use by name&id because i use looping)
I try build condition like this Javascript :
$('#button-price').bind('click', function() {
var box = '';
$(".box_1").each(function(){ // for each checkbox in class box_1(1-5)
if(this).attr("checked","true"){ // if this checked box is true
var value = (this.value).toLowerCase(); // take the value
box = box + value; // store to box
}
});
});
when click button then take value and store to box,
I know there error in here if(this).attr("checked","true"){
what it should be writing the condition?
Try using prop instead of attr
if($(this).prop('checked')) {
}
Hope this helps.
You can use the jQuery .prop() method to check the checkbox state:
if ($(this).prop("checked")) { // if this checked box is true
box += $(this).val().toLowerCase(); // store to box
}
Suggestion: (this.value).toLowerCase() will work but try not mixing up jQuery code with pure javascript. Instead of it you can use the solution above.
Related
i am submitting data through FormData and i am trying to alert values of check boxes which are checked in my form, right now i am able to make it work for only one check box.
how can i alert values of all those check boxes which are checked.
var formData = new FormData(document.getElementById("update-form"));
$("#myCheckbox1").on('change',function(){
if($("#myCheckbox1").is(':checked'))
$('#hiddenInput1').val(1);
else{
$('#hiddenInput1').val(0);
}
});
alert(
$('#hiddenInput1').val()
);
Check Box 1:
<input type="hidden" value="0" name="visa" id="hiddenInput1">
<input type="checkbox" value="1" id="myCheckbox1">
Example Check Box 2:
<input type="hidden" value="0" name="visa1" id="hiddenInput2">
<input type="checkbox" value="1" id="myCheckbox2">
How to Alert Values of all check boxes which are checked in FormData without repeating code. i found similar example online but none were using FormData.
Form Name is : update-form
You can make use of start with attribute selector to select all checkboxes having id start with myCheckbox and attach it to change event handler.
Inside handler, you can read if checkbox is checked or not and change value of hidden input which is placed before checkbox.
See below code
$(function(){
$("input[type=checkbox][id^=myCheckbox]").on('change',function(){
var isChecked = $(this).is(':checked');
var $hiddenInput = $(this).prev('input[type=hidden]');
if(isChecked)
$hiddenInput.val(1);
else{
$hiddenInput.val(0);
}
alert($hiddenInput.val());
});
//iterate all hidden input on form submit
$('#update-form').submit(function(){
$('input[id^=hiddenUnput]').each(function(){
alert($(this).val());
});
$(this).submit();
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
Exammple Check Box 1:
<input type="hidden" value="0" name="visa" id="hiddenInput1">
<input type="checkbox" value="1" id="myCheckbox1">
Example Check Box 2:
<input type="hidden" value="0" name="visa" id="hiddenInput2">
<input type="checkbox" value="1" id="myCheckbox2">
I haven't been able to find this answer. I don't know if I'm searching wrong or my lexicon is incorrect but I am trying to get the selected elements of a group of jquery radio buttons. Here is my JS code:
var hideFieldsBasedOnRadioButtonValue = function () {
var $employmentStatusRadioButtons = $(".edit-profile-employment-information input[name='user[profile_attributes][employment_status]']");
var displayOrHideRequiredFields = function ($radioButton) {
if ($radioButton.val() === "Full Time" || $radioButton.val() === "Part Time") {
$radioButton.closest("div.form-row").next(".required-input-when-yes").removeClass("d-none");
} else {
$radioButton.closest("div.form-row").next(".required-input-when-yes").addClass("d-none");
}
}
displayOrHideRequiredFields($(".edit-profile-employment-information input[name='user[profile_attributes][employment_status]']:checked"));
$employmentStatusRadioButtons.on("change", function () {
displayOrHideRequiredFields($(this));
});
}
This is a stripped down version of this function. I have a few more radio buttons that need to either hide or display additional fields depending on the radio button's value. What I'm having trouble with specifically is I want to trim this line down:
displayOrHideRequiredFields($(".edit-profile-employment-information input[name='user[profile_attributes][employment_status]']:checked"));
the $employmentStatusRadioButtons are a collection of jquery objects and I'm unable to figure out how to grab the selected one. Any help would be amazing.
Instead of using the same ".edit-profile-employment-information input[name='user[profile_attributes][employment_status]']" selector on this line and on line 2 of the code I want to do something like
displayOrHideRequiredFields($employmentStatusRadioButtons:checked);
Now that won't work. The closest I've been able to get this to work is by doing the following;
displayOrHideRequiredFields($employmentStatusRadioButtons.selector + ":checked")
But I don't really like how that looks. We aren't using ES6 or else it would be awesome.
I haven't been able to find anything to help me in this regard. Does anyone know any methods specifically where I can do something like this?
You can use the jquery filter() function for filtering a variable with jQuery objects.
var $radios = $('[name=test],[name=test2]');
var $radiosFiltered = $radios.filter(':checked');
$radiosFiltered.each(function(){
console.log($(this).val());
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type="radio" name="test" value="1" checked>
<input type="radio" name="test" value="2">
<input type="radio" name="test" value="3">
<input type="radio" name="test2" value="4">
<input type="radio" name="test2" value="5" checked>
<input type="radio" name="test2" value="6">
You was so close, you need to use filter to get the checked elements from your collection :
$employmentStatusRadioButtons.filter(':checked');
I have to control the checked status a list of checkboxes from another checkbox.
HTML:
<input id="readall" name="readall" type="checkbox" value="1">
<div id="permGrid">
<input id="recipe.read" name="recipe.read" type="checkbox" value="1" rel="read">
<input id="group.read" name="group.read" type="checkbox" value="1" rel="read">
<input id="ingredients.read" name="ingredients.read" type="checkbox" value="1" rel="read">
</div>
JS:
$('#readall').click(function()
{
var checkStatus = $(this).is(':checked');
var checkboxList = $('#permGrid input[rel="read"]');
$(checkboxList).attr('rel', 'read').each(function(index)
{
if(checkStatus == true)
{
$(this).attr('checked', 'checked');
console.log($(this).attr('checked'));
}
else
{
$(this).removeAttr('checked').reload();
console.log($(this).attr('checked'));
}
});
});
The above code seems fine but the check/uncheck works only for the first time. But when I click the main checkbox second time, it doesn't change the status of other checkboxes into 'checked'. Is there anything I need to do?
I found something similar here. I compared the code and mine and this code is somewhat similar but mine doesn't work.
Try using prop, and shorten the code alot like this
$('#readall').click(function () {
var checkboxList = $('#permGrid input[rel="read"]')
checkboxList.prop('checked', this.checked);
});
DEMO
You can't use a method .reload like this
$(this).removeAttr('checked').reload();
// returns Uncaught TypeError: Object #<Object> has no method 'reload'
Remove it, and it will work.
JSFiddle
Use a class for all the checkboxes which you need to change on click of some checkbox. Like:
<input id="recipe.read" class="toChange" name="recipe.read" type="checkbox" value="1" rel="read" />
I have added a class="toChange" to all the checkboxes except the first one.
<input id="readall" name="readall" type="checkbox" value="1">
<div id="permGrid">
<input id="recipe.read" class="toChange" name="recipe.read" type="checkbox" value="1" rel="read" />
<input id="group.read" class="toChange" name="group.read" type="checkbox" value="1" rel="read" />
<input id="ingredients.read" class="toChange" name="ingredients.read" type="checkbox" value="1" rel="read" />
</div>
Then use the following script:
$('#readall').click(function(){
var checkStatus = $(this).is(':checked');
if(checkStatus){
$(".toChange").attr('checked', 'checked');
}
else{
$(".toChange").removeAttr('checked')
}
});
Demo
I have checkbox html.
<label><input type="checkbox"><span>Air Conditioning</span></label>
<label><input type="checkbox"><span>Cable TV Service</span></label>
<label><input type="checkbox"><span>Private Bathroom</span></label>
I need to have seperate value for each checkbox, so I can get those values from all and store in variable. For example
<label><input type="checkbox" data="1"><span>Air Conditioning</span></label>
<label><input type="checkbox" data="2"><span>Cable TV Service</span></label>
<label><input type="checkbox" data="3"><span>Private Bathroom</span></label>
So if all the 3 are selected I will need my variable as
room_features = '1-2-3';
If any one is then unchecked, variable will be updated as
room_features = '2-3';
So on every change on checkbox, variable should be updated. I am confused if either adding data="1" etc is fine for checkboxes? I normally do for anchors when there is single double quotes.
Live Demo
You should use value in each checkbox. for ex:
HTML:
<input type="checkbox" value="1" checked />
<input type="checkbox" value="2" checked />
<input type="checkbox" value="3" />
JQuery:
var searchIDs = $("input:checkbox:checked").map(function(){
return this.value;
}).toArray();
html
<label><input type="checkbox" checked="checked" data="1"><span>Air Conditioning</span></label>
<label><input type="checkbox" checked="checked" data="2"><span>Cable TV Service</span></label>
<label><input type="checkbox" data="3"><span>Private Bathroom</span></label>
JS
var selectedvalue=[];
$(":checkbox:checked").each(function(){
selectedvalue.push($(this).attr("data"));
});
alert(selectedvalue.join("-"));// your desired result
demo
reference Arrays and checked-selector
You can use .map() method, note that I have added value attribute to the element instead of data as an input should have a value otherwise what's the point of using it? If you want to use data-* attributes, you should specify an identifier. Something like <input type="checkbox" data-id="1">, then you can get the value using jQuery data() method: $(elem).data('id');.
<label><input type="checkbox" value="1"><span>Air Conditioning</span></label>
...
var vals = $('input[type=checkbox]:checked').map(function(){
return this.value; // return $(this).data('whatever');
}).get().join('-');
get() returns an array, if you need an array you can remove the .join() method which returns a string.
try this dynamic one
var room_features = "";
$('[type=checkbox]').change(function () {
var data = "-" + $(this).attr('data');
if (room_features.indexOf(data) != -1) {
room_features = room_features.replace(data, "");
alert(room_features);
} else {
room_features = room_features + data;
alert(room_features);
}
});
Demo Fiddle
javascript
getElementById("chkbox1").checked=true;
jquery
$("#chkbox1").prop("checked");
or
$("#chkbox1").attr("checked");
check this Jsfiddle
$("#btn").click(function(event){
var selectedvalue=[];
$(":checkbox:checked").each(function(){
selectedvalue.push($(this).attr("data"));
});
alert(selectedvalue.join("-"));// your desired result
})
Suppose I have four check-boxes in a form Check-a,Check-b,Check-c,Check-d.
Check-a and Check-b are already selected.I can get which check-box is checked or not unchecked by using Jquery.
Now I have unchecked Check-a. So Check-a were checked and I had made this unchecked from checked. So now Check-c and Check-d were already unchecked and Check-a is unchecked by me.I am in search of a way to track which are unchecked from checked and which were previously unchecked.
Can Anyone Tell me a way ?
Assuming the same HTML as #definitelyundefinable, this does kind of the same thing but it's slightly cleaner because it doesn't use hidden fields, and fake arrays (as strings in the hidden field)
$(function() {
var history = [];
$("input").click(function() {
history.push({
id: this.id,
checked: this.checked
});
});
// If you'd like, you can initialize the array
// with the initial values with the following line
$("input").click();
});
if you need a kind of click-history, why not just use an extra field?
html:
<form>
<div>
<input type="checkbox" name="fruit" value="o" id="orange" />
<label for="orange">orange</label>
</div>
<div>
<input type="checkbox" name="fruit" value="a" id="apple" />
<label for="apple">apple</label>
</div>
<div>
<input type="text" name="history" id="history" />
</div>
</form>
jquery script:
$("input").click(function() {
$("#history").val( $("#history").val() + $(this).val() + ";");
});
you can make it hidden and evaluate the ; separated list afterwards..