I have the following code that would get the value of the checkbox, but not the one that is checked the latest, it get the last(?) value of the checkbox. I would like to get the value of the checkbox that is recently checked.
This is my html.
<div class="custom-control custom-checkbox">
<input
type="checkbox"
class="custom-control-input chkbx"
value="123456"
data-valuetwo="Mike"
id="customCheck32"
name="choice[]"
/>
<label class="custom-control-label" for="customCheck32">Mike</label>
</div>
<div class="custom-control custom-checkbox">
<input
type="checkbox"
class="custom-control-input chkbx"
value="6542321"
data-valuetwo="John"
id="customCheck33"
name="choice[]"
/>
<label class="custom-control-label" for="customCheck33">John</label>
</div>
<div id="selecteditems" style="border: 1px solid black"></div>
<div class="itemhead"></div>
This is my script.
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.0/jquery.min.js"></script>
<script>
$(".chkbx").click(function() {
var selected = "";
var latestchoice = "";
$(".chkbx:checked").each(function() {
selected += $(this).attr("data-valuetwo") + "<br>";
latestchoice = $(this).attr("data-valuetwo");
});
$("#selecteditems").html(selected);
if ($(".itemhead").is(":empty")) {
$(".itemhead").html(latestchoice);
} else {
$(".itemhead").empty();
$(".itemhead").html(latestchoice);
}
});
</script>
With the following code, if I check Mike first, then John, I could see the latest choice changing from Mike to John. However, if I selected John first and select Mike, the value of latest choice would not change to Mike. Thank you!
To do that, you'll have to remember when the checkboxes were checked. One way to do that is to use jQuery's data cache for elements, see comments:
$(".chkbx").click(function() {
var $this = $(this);
// If this checkbox is checked...
if (this.checked) {
// ...remember when
$this.data("checked", Date.now());
} else {
// Not checked, remove the data
$this.removeData("checked");
}
var selected = "";
var latestchoice = "";
// Get and sort the checked checkboxes
var checked = $(".chkbx:checked").get().sort(function(a, b) {
return $(a).data("checked") - $(b).data("checked");
});
// Loop through them in sorted order
checked.forEach(function(cb) {
var $cb = $(cb);
selected += $cb.attr("data-valuetwo") + "<br>";
latestchoice = $cb.attr("data-valuetwo");
});
$("#selecteditems").html(selected);
if ($(".itemhead").is(":empty")) {
$(".itemhead").html(latestchoice);
} else {
$(".itemhead").empty();
$(".itemhead").html(latestchoice);
}
});
Live Example:
$(".chkbx").click(function() {
var $this = $(this);
// If this checkbox is checked...
if (this.checked) {
// ...remember when
$this.data("checked", Date.now());
} else {
// Not checked, remove the data
$this.removeData("checked");
}
var selected = "";
var latestchoice = "";
// Get and sort the checked checkboxes
var checked = $(".chkbx:checked").get().sort(function(a, b) {
return $(a).data("checked") - $(b).data("checked");
});
// Loop through them in sorted order
checked.forEach(function(cb) {
var $cb = $(cb);
selected += $cb.attr("data-valuetwo") + "<br>";
latestchoice = $cb.attr("data-valuetwo");
});
$("#selecteditems").html(selected);
if ($(".itemhead").is(":empty")) {
$(".itemhead").html(latestchoice);
} else {
$(".itemhead").empty();
$(".itemhead").html(latestchoice);
}
});
<div class="custom-control custom-checkbox">
<input
type="checkbox"
class="custom-control-input chkbx"
value="123456"
data-valuetwo="Mike"
id="customCheck32"
name="choice[]"
/>
<label class="custom-control-label" for="customCheck32">Mike</label>
</div>
<div class="custom-control custom-checkbox">
<input
type="checkbox"
class="custom-control-input chkbx"
value="6542321"
data-valuetwo="John"
id="customCheck33"
name="choice[]"
/>
<label class="custom-control-label" for="customCheck33">John</label>
</div>
<div id="selecteditems" style="border: 1px solid black"></div>
<div class="itemhead"></div>
This is my script.
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.0/jquery.min.js"></script>
That said, a list you can drag items around in might make for a better UX.
Related
In short, if a user selects yes to a radio option, I'm trying to obtain the data-name attribute from that input and push it to an array called accepted_array.
If a user selects no, then store data-name to declined_array.
Here is a visual to the markup:
<div class="guest__options-group">
<input id="attending-yes-0" type="radio" name="attendance-0" value="yes" data-name="John" required />
<label for="attending-yes-0">Yes</label>
</div>
<div class="guest__options-group">
<input id="attending-no-0" type="radio" name="attendance-0" value="no" data-name="John" required />
<label for="attending-no-0">No</label>
</div>
<!-- options for Alex -->
<div class="guest__options-group">
<input id="attending-yes-1" type="radio" name="attendance-1" value="yes" data-name="Alex" required />
<label for="attending-yes-1">Yes</label>
</div>
<div class="guest__options-group">
<input id="attending-no-1" type="radio" name="attendance-1" value="no" data-name="Alex" required />
<label for="attending-no-1">No</label>
</div>
Here are 2 approaches I've experimented with:
First approache.
(function ($) {
$( ".guest__attendance-input" ).each(function(index) {
$(this).on("click", function(){
var $this = $(this);
var checkedVal = $this.val();
var accepted_array = [];
var declined_array = [];
if( checkedVal == "yes" ) {
var name = $this.data("name");
accepted_array.push(name);
} else {
declined_array.push(name);
}
console.log("accepted " + accepted_array.join(","));
console.log("declined " + accepted_array.join(","));
});
});
}) (jQuery);
This only executes for the selected user and adds the name to both arrays.
Second approache.
(function ($) {
$( ".guest__attendance-input" ).each(function(index) {
$(this).on("click", function(){
var $this = $(this);
var data = [];
var checked = $this.is(':checked');
var name = $this.attr('data-name');
if (checked) {
if (!data[name]) {
data[name] = []
}
data[name].push($this.val())
}
console.log(data);
});
});
}) (jQuery);
Which only adds the user to a single array.
If both select yes, I need both names in the accepted_array. If someone selects yes initially and then selects no I need to remove them from the accepted_array and vice versa.
You can use splice with inArray to remove value from array if someone selects yes initially and then selects no and vice versa.
Example:
var accepted_array = [];
var declined_array = [];
$('.guest__options-group > input[type=radio]').on('change', function() {
var $this = $(this);
var name = $this.data("name");
var checkedVal = $this.val();
var name = $this.data("name");
if (checkedVal == "yes") {
accepted_array.push(name);
declined_array.splice($.inArray(name, declined_array), 1);
} else {
declined_array.push(name);
accepted_array.splice($.inArray(name, accepted_array), 1);
}
console.log("accepted " + accepted_array.join(","));
console.log("declined " + declined_array.join(","));
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<!-- options for John -->
<div class="guest__options-group">
<input id="attending-yes-0" type="radio" name="attendance-0" value="yes" data-name="John" required />
<label for="attending-yes-0">Yes</label>
</div>
<div class="guest__options-group">
<input id="attending-no-0" type="radio" name="attendance-0" value="no" data-name="John" required />
<label for="attending-no-0">No</label>
</div>
<!-- options for Alex -->
<div class="guest__options-group">
<input id="attending-yes-1" type="radio" name="attendance-1" value="yes" data-name="Alex" required />
<label for="attending-yes-1">Yes</label>
</div>
<div class="guest__options-group">
<input id="attending-no-1" type="radio" name="attendance-1" value="no" data-name="Alex" required />
<label for="attending-no-1">No</label>
</div>
Im having trouble getting values from the checked radio:
<form id="addform" /*action="catch.php" method="POST"*/>
<div class="form-group input-container">
<label class="col-sm-7"> *Href looks like "/vacacy/12": </label>
<input class="col-sm-3" name="vacancy_full_URL" value="0" type="radio" required>
<label class="col-sm-7"> *Href looks like "https://www.test.com/vacancy/12": </label>
<input class="col-sm-3" name="vacancy_full_URL" value="1" type="radio" required>
</div>
</form>
This is the JavaScript code:
$( "#check" ).click(function()
{
var $inputs = $('#addform :input');
var values = {};
$inputs.each(function()
{
if (this.name === "vacancy_full_URL")
{
if (/* check if radiobutton is checked */)
{
values[this.name] = $(this).val();
}
}
else
{
values[this.name] = $(this).val();
}
});
});
I'm having trouble finding the right functions to check this with. My earlier attempt if (this.checked() === true) did not work. Can you please help me?
Use is(":checked") to find if a radio button is checked. Also there are few mistakes in html form like a you have make the form self closing. Secondly there was no item with id check
$("#check").click(function(e) {
e.preventDefault()
var $inputs = $('#addform :input');
var values = {};
$inputs.each(function() {
if (this.name === "vacancy_full_URL" && $(this).is(":checked")) {
values[this.name] = $(this).val();
} else {
values[this.name] = $(this).val();
}
});
console.log(values)
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<form id="addform" action="catch.php" method="POST">
<div class="form-group input-container">
<label class="col-sm-7"> *Href looks like "/vacacy/12": </label>
<input class="col-sm-3" name="vacancy_full_URL" value="0" type="radio" required>
<label class="col-sm-7"> *Href looks like "https://www.test.com/vacancy/12": </label>
<input class="col-sm-3" name="vacancy_full_URL" value="1" type="radio" required>
</div>
<button type='submit' id='check'>Click</button>
</form>
You can handle click event on button and check radion click name with :checked
$(document).ready(function(){
$("#check").click(function(){
var radioValue = $("input[name='vacancy_full_URL']:checked").val();
if(radioValue){
alert("Your are a - " + radioValue);
}
});
});
Please try this.
$(document).ready(function () {
$("#check").click(function () {
var values = {};
var other_data = $('input[type=radio]', $('#addform'));;
$.each(other_data, function (key, input) {
if (input.checked) {
values[input.name + "_checked"] = input.value;
} else {
values[input.name+ "_unchecked"] = input.value;
}
});
});
})
I've got an array of checkboxes I need to display to the user the options they select to provide a total price for those options. The issue is that when I run the code I don't get any value in the array and I'm not sure why because I've correctly referenced the checkboxes. I've tried fixing the number of iterations in the for loop and renaming variables but I cant seem to get it to work.
var checkbox_list = document.forms[0];
var txt = "";
var checkedValue = null;
var inputElements = document.getElementsByClassName("checkboxb");
for (var i = 0; inputElements[i]; i++) {
if (inputElements[i].checked) {
txt += checkbox_list[i].value + ", ";
alert(txt);
break;
}
}
document.getElementById("quote").innerText = txt + "";
<div id="checkboxes">
<label for="one"><input type="checkbox" class="checkboxb"
name="options1"/>First checkbox</label>
<label for="two"><input type="checkbox" class="checkboxb"
name="options2"/>Second checkbox</label>
<label for="three"><input type="checkbox" class="checkboxb"
name="options3"/>Third checkbox</label>
</div>
You may also want an ES6 approach.
// This line just stores the inputs
const inputElements = document.getElementsByClassName("checkboxb");
// This replaces your for-loop. It iterates through the inputs and if they are checked,
// add the current value to an accumulated value
const calculate = _ => [...inputElements].reduce((a, c) => c.checked ? (a + ", " + c.value) : a, "").substr(2);
// This just performs the calculation whenever checkbox change, and display that result
[...inputElements].forEach(x => x.addEventListener("change", _ => quote.innerText = calculate()));
<div id="checkboxes">
<label><input type="checkbox" class="checkboxb"
name="options1" value="one"/>First checkbox</label>
<label><input type="checkbox" class="checkboxb"
name="options2" value="two"/>Second checkbox</label>
<label><input type="checkbox" class="checkboxb"
name="options3" value="three"/>Third checkbox</label>
</div>
<div id="quote"></div>
each time I click on a option his data-type should appear in the input.
But I want if the value is already in the .val of the input should not appear anymore and if I click twice I want to remove the data-type from input.
Here is my Jsfiddle:
$('.checkbox').on('click', function () {
var type = $(this).data('type'),
answer = $('.answer'),
initial = $('.answer').val();
$(this).toggleClass('checked');
if (answer.val().length === 0) {
answer.val(type);
} else {
answer.val(initial + ',' + type);
}
});
http://jsfiddle.net/xbwocrf3/
Thanks!
One solution is using jquery map:
$('.checkbox').on('click', function() {
$(this).toggleClass('checked');
//save the values of checked in an array
var answerValues = $(".checkbox.checked").map(function() {
return $(this).data("type");
}).get();
//update input text with this values
$(".answer").val(answerValues);
});
.checkbox.checked {
border: 2px solid green;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" class="answer" />
<div class="checkbox" data-type="1">Option #1</div>
<div class="checkbox" data-type="2">Option #2</div>
<div class="checkbox" data-type="3">Option #3</div>
<div class="checkbox" data-type="4">Option #4</div>
Do another check before adding the value there:
$('.checkbox').on('click', function () {
var type = $(this).data('type'),
answer = $('.answer'),
initial = $('.answer').val();
$(this).toggleClass('checked');
if (answer.val().length === 0) {
answer.val(type);
} else if (!new RegExp("\,?" + type + "\,?").test(initial)) {
answer.val(initial + ',' + type);
}
});
.checkbox.checked {
border:2px solid green;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" class="answer" />
<div class="checkbox" data-type="1">Option #1</div>
<div class="checkbox" data-type="2">Option #2</div>
<div class="checkbox" data-type="3">Option #3</div>
<div class="checkbox" data-type="4">Option #4</div>
Use jQuery's map function to get the type data from all elements. Then combine using the join function.
http://jsfiddle.net/xbwocrf3/8/
$('.checkbox').on('click', function() {
var answer = $('.answer');
$(this).toggleClass('checked');
answer.val( $(".checkbox.checked").map(function() {return $(this).data("type")}).get().join(", ") );
});
This solution is a little cleaner:
http://jsfiddle.net/xbwocrf3/9/ (link updated, I pasted it wrong before)
It uses native checkboxes
Instead of doing something as hard as trying to remove old values, it rewrites the whole value of the input from scratch
The items appear always in their natural order
HTML
<input type="text" class="answer" />
<div>
<input type="checkbox" value="1" name="something" id="something1"/>
<label for="something1">Option #1</label>
</div>
<div>
<input type="checkbox" value="2" name="something" id="something2"/>
<label for="something2">Option #2</label>
</div>
<div>
<input type="checkbox" value="3" name="something" id="something3"/>
<label for="something3">Option #3</label>
</div>
<div>
<input type="checkbox" value="4" name="something" id="something4"/>
<label for="something4">Option #4</label>
</div>
CSS
input[type="checkbox"]{
display: none;
}
input[type="checkbox"]:checked + label{
border:2px solid green;
}
Javascript
$('input[type=checkbox]').on('change', function() {
var $answer = $(".answer");
var checked_values = $.map($("input:checked"), function (element){
return element.value;
});
$answer.val(checked_values);
});
please check fiddle
$('.checkbox').on('click', function () {
$(this).toggleClass('checked');
var typen = '';
$(".checkbox").each(function () {
var type = $(this).data('type');
if ($(this).hasClass('checkbox checked')) {
typen = typen + ',' + type;
}
});
if (typen.length > 0) {
typen = typen.substring(1, typen.length);
}
$('.answer').val(typen);
});
Check if the input has checked class:
if($(this).hasClass('checked'))
return;
Final:
$('.checkbox').on('click', function() {
if($(this).hasClass('checked'))
return;//Stop the execution of the function
var type = $(this).data('type'),
answer = $('.answer'),
initial = $('.answer').val();
$(this).toggleClass('checked');
if(answer.val().length === 0) {
answer.val(type);
} else {
answer.val(initial +','+ type);
}
});
I need a function that can add checkbox values on click event. My html code is
<div data-role="fieldcontain">
<fieldset data-role="controlgroup">
<center><b> Plattforms </b></center>
<input type="checkbox" name="cbs" id="cbs" value = 945345 />
<label for="cbs">945345 Symbian</label>
<input type="checkbox" name="cbi" id="cbi" value = 945345 />
<label for="cbi">945345 iPhone</label>
<input type="checkbox" name="cbb" id="cbb" value = 945345 />
<label for="cbb">945345 Blackberry</label>
<input type="checkbox" name="cba" id="cba" value = 945345 />
<label for="cba">945345 Android</label>
<input type="checkbox" name="cbw" id="cbw" value = 945345 />
<label for="cbw">945345 Windows Mobile</label>
<input type="checkbox" name="cbo" id="cbo" value = 945345 />
<label for="cbo">945345 All Other</label>
</fieldset>
</div>
The logic is when a user click on a checkbox, the checkbox value goes to a variable and again the user if clicks on another checkbox that value adds up into first value. Thanks in advance
Do you mean like:
var total = 0;
$("input[type='checkbox']").click(function() {
//if you want to add on checked
if($(this).is(":checked")) {
var v = parseInt($(this).val(), 10);
total += v;
}
else {
total -= v;
}
});
Hope it helps
You could do;
var tot = 0;
$("input:checkbox").click(function() {
var val = parseInt(this.value, 10);
if($(this).is(":checked")) {
//add to total if it's checked
tot += vale;
}else{
//this was previously checked, subtract it's value from total
tot -= vale;
}
});