check if checkbox is checked add value else if unchecked remove value - javascript

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
})

Related

How to get the value of selected radio button where multiple radio buttons have same name using javascript

All of these radio buttons have an onclick method in which I am trying to get the value of the selected radio button.
<div id="interior">
<label><input type="radio" name="groundfloordropdown" value="125">1BHK</label>
<label><input type="radio" name="groundfloordropdown" value="175">2BHK</label>
<label><input type="radio" name="groundfloordropdown" value="225">3HK</label>
</div>
You can use JQuery to get the value by
let value = $('input[name="groundfloordropdown"]:checked').val().
var names = document.getElementsByName("groundfloordropdown");
groundfloordropdown.forEach((ground) => {
if (ground.checked) {
alert(`Choise: ${ground.value}`);
}
})
this is a pure js
have a good day :)
Do not declare js events inside tags. This will lead to many bad consequences.
I made you a little javascript code using the forEach() method. This method is required to work with the collection. Namely, when you work with many elements that have the same class, or it will be the same tag.
Also, in this example you get the value of the input tag and the label tag.
If you have any questions, let me know. I will answer with pleasure.
let radio = document.querySelectorAll('.radiogroup input');
let label = document.querySelectorAll('.radiogroup label');
radio.forEach(function (radio_current, index) {
radio_current.addEventListener('change', function () {
console.log('Value Radio: ' + this.value + '; Value Label: ' + label[index].innerText);
});
});
<div class="radiogroup">
<label><input type="radio" name="groundfloordropdown" value="125">1BHK</label>
<label><input type="radio" name="groundfloordropdown" value="175">2BHK</label>
<label><input type="radio" name="groundfloordropdown" value="225">3HK</label>
</div>

Pass Dynamically Generated Checked CheckBox's Value to Method in ASP.NET MVC

I have a form in View that on button click sends Model full of data to my Controller's ActionResult method.
In View I am generating checkboxes based on ViewModel's certain list content. Basically the number of checkboxes depends on number of items in the list while the page loads, so it may vary from session to session.
It the moment checkboxes are getting values corresponding to the items from the list.
I want to include checkboxes in the form. I don't know however how to pass their values dynamically to the Method along with Form's Model for other controls in the Form as their Id's, Names and number of them may vary.
ANyone has some idea how I can identify values of checkboxes that are checked?
In Razor/CSHTML:
<input type="checkbox" id="GB" class="CHK" onchange="selectCountry()" /> GB
<input type="checkbox" id="IE" class="CHK" onchange="selectCountry()" /> IE
<input type="checkbox" id="FI" class="CHK" onchange="selectCountry()" /> FI
<input type="checkbox" id="SE" class="CHK" onchange="selectCountry()" /> SE
<input type="checkbox" id="DK" class="CHK" onchange="selectCountry()" /> DK
In JS (to identify the variable):
var CountryChosen=''; //create empty variable to be filled
function selectCountry() {
if (document.getElementById("GB").checked == true) {
CountryChosen = "GB";
}
if (document.getElementById("IE").checked == true) {
CountryChosen = "Ireland";
}
if (document.getElementById("FI").checked == true) {
CountryChosen = "Finland";
}
if (document.getElementById("SE").checked == true) {
CountryChosen = "Sweden";
}
if (document.getElementById("DK").checked == true) {
CountryChosen = "Denmark";
}
}
You could also do an empty array for multiple selections:
CountriesChosen = [];
and instead of CountryChosen = X, do .push() to add to the full array and call the variables as part of the array...food for thought anyhow.
You can then use the JS variables to pass to the controller and action result but it depends what the action result is doing (e.g. JSON call could be through AJAX/JQUERY call and use the CountryChosen as a variable).
You can do it easily by using jQuery selectors as below. Keep the name of all checkboxes as the same and use the selector as below.
function getChecked() {
var checked_items = '';
$("input[name='item']:checked").each(function () { // get the checked items
checked_items = checked_items + "&item=" + $(this).val();
});
alert('JQUERY : Checked items are : ' +checked_items)
checked_items = ''
var items = document.getElementsByName("item")
for (i=0;i<items.length;i++){
if (items[i].checked)
checked_items = checked_items + "&item=" + items[i].value;
}
alert('JAVASCRIPT : Checked items are : ' +checked_items)
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/1.2.3/jquery.min.js"></script>
<input type="checkbox" name="item" value="1" />1
<input type="checkbox" name="item" value="2" />2
<input type="checkbox" name="item" value="3" />3
<input type="checkbox" name="item" value="4" />4
<input type="button" value="Submit" onclick="getChecked()">

Remove specific characters from string jquery [duplicate]

This question already has answers here:
jQuery: Add values of checkboxes to input text field
(4 answers)
Closed 4 years ago.
OK, So although it seems normal substring or replaces solution answer it is quite complex for me.
I have 3 checkboxes
A,B,C
and one text box
Now, when user select any checkbox the value of checkbox appends into textbox i.e. Fist he selects A -> textbox will be appended by A
Then if selects B -> textbox value will be A, B and so on.
i have done it already.
Now the problem is for unchecking.
If the value of textbox is A,B,C i.e. the selected checkboxes are A,B,C and if user deselects the B then the value should be A,C and then again deselects the c then the value should be A.
I have tried multiple ways but don't work for all conditions, sometimes it becomes A, C or A, B
Any solution?
Thank you in advance :)
You can simply recreate the list on change of a box
let els = [...document.getElementsByClassName('check')];
els.forEach(e => e.addEventListener('change', () => {
document.getElementById('foo').value = els.filter(x => x.checked).map(x => x.value).join();
}))
.flex {
display: flex;
flex-direction: column;
}
<div class="flex">
<input id="foo" />
<label><input type="checkbox" class="check" value="A"/>A</label>
<label><input type="checkbox" class="check" value="B"/>B</label>
<label><input type="checkbox" class="check" value="C"/>C</label>
</div>
Try this:
1) On each checkbox click/unclick get the value of all checked checkboxes. (for example ['A', 'B'])
2) Generate the new string with join the values . ['A', 'B'].join(',') // returns 'A,B'
3) Set the textbox with the new string
If you need code you can submit your current code.
Here's what I came up with, without knowing how you're tracking what's checked or not, it's a data driven approach.
var checked = [];
function updateValue() {
$('#selected').val(checked.toString());
}
$('[type=checkbox]').click(function(e) {
var value = e.target.value;
if(e.target.checked) {
checked.push(value);
} else {
checked.splice(checked.indexOf(value), 1);
}
updateValue();
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="checkbox" value="A">A<br>
<input type="checkbox" value="B">B<br>
<input type="checkbox" value="C">C<br>
<input type="text" id="selected">
$(function() {
const valArray = []; // our value array here what gonna show in textarea
/**
- on change check if checkbox checked or not
- if checked push value of checkbox to array
if not search in our array "valArray" and get it's index then remove it
- change textarea value with the new array "valArray"
*/
$('.checkboxes input').on('change', function(e) {
const $thisVal = $(this).val(),
isChecked = $(this).is(':checked');
if (isChecked) {
valArray.push($thisVal);
} else {
const searchOnThisVal = valArray.find(item => $thisVal === item),
getTheIdx = valArray.indexOf(searchOnThisVal);
valArray.splice(getTheIdx, 1);
}
$('.textarea').empty();
$('.textarea').text(valArray);
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="checkboxes">
<label>
<input type="checkbox" value="a">
the checkbox A.
</label>
<label>
<input type="checkbox" value="b">
the checkbox B.
</label>
<label>
<input type="checkbox" value="c">
the checkbox C.
</label>
</div>
<textarea class="textarea" placeholder="your choice..."></textarea>
this should work in your case using jQuery API

Take value for each check box if checked Javascript

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.

List variable values that are checked with jQuery

I have gotten pretty far with this in jsFiddle, though I can't figure out why it's not adding a bullet to the first value..
http://jsfiddle.net/dvCmR/128/
<div id="checkboxes">
<input id="chkbx_0" type="checkbox" name="one" />Option 1
<input id="chkbx_1" type="checkbox" name="two" />Option 2
<input id="chkbx_2" type="checkbox" name="three" />Option 3
<input id="chkbx_3" type="checkbox" name="four" />Option 4
</div>
<div class="content"></div>
<script>
$("input").click(function(e) {
var selected = $("#checkboxes input:checked").map(function(i, el) {
return el.name;
}).get();
$('.content').empty();
$(".content").append(selected.join("<li>"));
});
</script>
​
Thanks!!!
As #Pointy said, join will not add li when you have a single element. Also, you don't need to use join at all, simply add the elements with a single loop:
$("input").click(function(e) {
var $content = $('.content').empty();
$("#checkboxes input:checked").each(function(i, el) {
$("<li>" + el.name + "</li>").appendTo($content);
});
});​
DEMO.
The .join() function only puts the string between elements. The result is therefore
name1<li>name2<li>name3
when you need
<li>name1<li>name2<li>name3
Also, dropping <li> elements into a <div> is pretty questionable.
You can still use .join(), but you should add another <li> to the beginning of the result string when (after the join) it's not empty.
Try this:
$("input").click(function(e) {
var selected = $("#checkboxes input:checked").map(function(i, el) {
return "<li>"+el.name+"</li>"
}).get();
$(".content").html(selected.join(""));
});
Fiddle

Categories

Resources