I'm trying to add the values of any checked checkbox to an input text field.
Here's my fiddle: http://jsfiddle.net/Lf6ky/
$(document).ready(function() {
$(":checkbox").on('click', function() {
if ($(':checkbox:checked')) {
var fields = $(":checkbox").val();
jQuery.each(fields, function(i, field) {
$('#field_results').val($('#field_results').val() + field.value + " ");
});
}
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
<input type="text" id="field_results" /><br>
<input type="checkbox" value="1">1<br>
<input type="checkbox" value="2">2<br>
<input type="checkbox" value="3">3
In this example, I have 3 checkboxes, with the values 1,2,3. If I click on all these checkboxes, then the input field should look like this: 1 2 3
If I uncheck any of these checkboxes, then that corresponding value should disappear in the input field.
How do I do this?
I've stored the collection of check-boxes in a variable $checks, then attach the handler to this collection. Inside the event handler, I take the collection once again and filter (return) only the check-boxes that are checked.
map() returns a jQuery object containing the values of the checked check-boxes, get() converts it to a standard array. Join those values with a space and put 'em in the input.
$(document).ready(function(){
$checks = $(":checkbox");
$checks.on('change', function() {
var string = $checks.filter(":checked").map(function(i,v){
return this.value;
}).get().join(" ");
$('#field_results').val(string);
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" id="field_results"/><br>
<input type="checkbox" value="1">1<br>
<input type="checkbox" value="2">2<br>
<input type="checkbox" value="3">3
On click of a checkbox, loop through the checked inputs, append to a string then assign that to your text box:
$(document).ready(function() {
$("input:checkbox").click(function() {
var output = "";
$("input:checked").each(function() {
output += $(this).val() + " ";
});
$("#field_results").val(output.trim());
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
<input type="text" id="field_results" /><br>
<input type="checkbox" value="1">1<br>
<input type="checkbox" value="2">2<br>
<input type="checkbox" value="3">3
First issue is
if($(':checkbox:checked')) {
will always be true since it returns a jQuery object and an object is a truthy value. If you were to use the if, you want to check the length. aka if($(':checkbox:checked').length) {
Secondly
var fields = $(":checkbox").val();
returns only the first element's value and it returns any checkbox, not just the checked ones. You want to loop through $(':checkbox:checked')
One way to attack it is to use an each and an array.
$(":checkbox").on('change', function() {
var total = [];
$(':checkbox:checked').each( function(){ //find the checked checkboxes and loop through them
total.push(this.value); //add the values to the array
});
$('#field_results').val(total.join(" ")); //join the array
});
Problem
if($(':checkbox:checked')) will always be true
var fields = $(":checkbox").val(); Will give first checkbox value
You can try this.
$(document).ready(function() {
$(":checkbox").on('click', function() {
var fields = '';
$(":checkbox").each(function() {
if (this.checked) {
fields += $(this).val() + ' ';
}
});
$('#field_results').val($.trim(fields))
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
<input type="text" id="field_results" />
<br>
<input type="checkbox" value="1">1
<br>
<input type="checkbox" value="2">2
<br>
<input type="checkbox" value="3">3
Related
I am wanting to loop over an checkbox input and check if the checkbox ISNT selected then add the value of the checkbox to an array which im wanting to POST through ajax.
I have an example below of looping through checkboxes which are selected but how would i do the inverse of this while still including the .each?
var categories = [];
$("input[name='categories[]']:checked").each(function () {
categories.push(this.value);
});
You mean this?
$("input[name='categories[]']").each(function () {
if (!this.checked) categories.push(this.value);
});
or
const categories = $("input[name='categories[]']").not(":checked") // or ]:not(:checked)")
.map(function() { return this.value })
.get();
console.log(categories)
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type="checkbox" name="categories[]" value="1" checked />
<input type="checkbox" name="categories[]" value="2" />
<input type="checkbox" name="categories[]" value="3" checked />
hope you can help me :)
I have this code to get the value of the checkboxes:
function check() {
var Input = Array.prototype.slice.call(document.querySelectorAll(".checkboxes:checked")).map(function(el) {
return el.value;
}).join(',')
document.getElementById('output2').innerHTML = Input;
return false;
}
I want that the output is in the order I selected the checkboxes. Is there a way to get them in correct order?
You can set the timestamp to them when they are changed (comments inline)
var allCheckboxes = document.querySelectorAll("input[type='checkbox'][data-name]");
//bind the event to set time value on change
[...allCheckboxes].forEach(s => s.addEventListener("change", function(e) {
e.currentTarget.timeval = new Date().getTime();
}));
document.querySelector("button").addEventListener("click", check);
function check() {
var output = [...allCheckboxes]
.filter(s => s.checked) // filter out non-checked
.sort((a, b) => a.timeval - b.timeval) //sort by timeval
.map(s => s.getAttribute("data-name")).join(","); //fetch only data-name for display
document.getElementById('output').innerHTML = output;
}
Check 1 <input type="checkbox" data-name="check1"> <br/> Check 2 <input type="checkbox" data-name="check2"> <br/> Check 3 <input type="checkbox" data-name="check3"> <br/> Check 4 <input type="checkbox" data-name="check4"> <br/> Check 5 <input type="checkbox"
data-name="check5"> <br/>
<button>check</button>
<div id="output"></div>
You can set an array and save the values as they are selected.
You can achive this by giving each chcekbox an event listener.
In the event listener you add an if to validate if the click event was when checked and then add them to your list/array.
Hope this helps :)
var checks = document.querySelectorAll('input[type=checkbox]');
var order = [];
for(var i=0; i<checks.length;i++){
checks[i].addEventListener("click", function(){
if(this.checked)
order.push(this.value);
})
}
<input type="checkbox" value="A">A
<input type="checkbox" value="B">B
<input type="checkbox" value="C">C
<input type="checkbox" value="D">D
<br>
<button onclick="console.log('Order: '+order)">Check order</button>
You can add a data-id attribute to each section. And when you click on one checkbox, change the attribute values of each checkbox to a serial number. To do this, it's easier to use jquery
You could use a Set and add or delete depending of the checked state of the check box.
Set returns the items in insertation order.
var checks = document.querySelectorAll('input[type=checkbox]'),
order = new Set,
i
for (i = 0; i < checks.length; i++) {
checks[i].addEventListener("click", function() {
order[['delete', 'add'][+this.checked]](this.value);
});
}
<input type="checkbox" value="A">A
<input type="checkbox" value="B">B
<input type="checkbox" value="C">C
<input type="checkbox" value="D">D
<br>
<button onclick="console.log('Order: '+[...order])">Check order</button>
I have an array of comma separated string. This will determined whick checkbox should be disabled.
var lbl = "A,C";
Then I want to compare it on the checkboxes in the form. The check boxes values are A,B,C,D.
Based on the string given, the checkbox which value are A and C should be disabled.
This is my current script:
$('#f_sendTo input[type=checkbox]').each(function() {
var arr_cek_txt = $(this).val().split('||'); //This is checkboxes value
var arr_lbl_ext = lbl.split(','); //this is the string = "A,C"
var val_lbl_ext;
$.each(arr_lbl_ext,function(i){
if(arr_cek_txt[1] == arr_lbl_ext[i]){
$(this).prop("disabled", true);
}
});
});
You can do something like:
Loop thru the checkbox using each(). Check the value and if the value is in array, disable the checkbox.
$(document).ready(function() {
var lbl = "A,C";
var arr_lbl_ext = lbl.split(','); /* Init this outside each. So that no need to do this every loop*/
$('#f_sendTo input[type=checkbox]').each(function() {
var arr_cek_txt = $(this).val(); /* Get the value of checkbox */
if (arr_lbl_ext.indexOf(arr_cek_txt) == -1) $(this).prop("disabled", false);
else $(this).prop("disabled", true);
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<div id="f_sendTo">
<input type="checkbox" name="cb" value="A"> A <br />
<input type="checkbox" name="cb" value="B"> B <br />
<input type="checkbox" name="cb" value="C"> C <br />
<input type="checkbox" name="cb" value="D"> D <br />
</div>
I'm having trouble display value of radio button
when I click on the radio buttons,
I want to see all the values of buttons in the box.
its shows values on the console but in the box, it only shows 'carrot' which is one of ingredients in the array.
function mixRecipeBox(){
var mixIngredients = document.getElementsByTagName('input');
for(i=0; i<mixIngredients.length; i++){
if(mixIngredients[i].checked)
console.log(mixIngredients[i].value);
document.getElementById('mixbox').innerHTML = mixIngredients[i].value;
}
}
You are replacing all data of mixbox in each loop. use this to
append data.
You forgot {} for if block
Empty mixbox on start of function.
use checkbox instead of radio so user can discard choice.
function mixRecipeBox(){
document.getElementById('mixbox').innerHTML=""
var currentHTML;
var mixIngredients = document.getElementsByTagName('input');
for(i=0; i<mixIngredients.length; i++){
if(mixIngredients[i].checked)
{
console.log(mixIngredients[i].value);
currentHTML= document.getElementById('mixbox').innerHTML;
document.getElementById('mixbox').innerHTML = currentHTML+mixIngredients[i].value;
}
}
}
<input type="checkbox" value="1" onchange="mixRecipeBox()">
<input type="checkbox" value="2" onchange="mixRecipeBox()">
<input type="checkbox" value="3" onchange="mixRecipeBox()">
<input type="checkbox" value="4" onchange="mixRecipeBox()">
<div id="mixbox"></div>
Loop over each radio element and assign a click event handler.
The radio button click handler first clears the mixbox, then loops over each radio element and puts checked radio button values in the mixbox.
<div id="rads">
<input type="radio" value="one" />1
<input type="radio" value="two" />2
<input type="radio" value="three" />3
</div>
<div id="mixbox"></div>
<script>
var rads = document.querySelectorAll('#rads input[type=radio]');
var mixbox = document.getElementById('mixbox');
Array.prototype.forEach.call(rads, function (elem) {
elem.addEventListener('click', function (evt) {
mixbox.innerHTML = '';
Array.prototype.forEach.call(rads, function (ele) {
if ( ele.checked ) { mixbox.innerHTML += ele.value + '<br>'; }
})
})
})
</script>
JSFiddle
what are the best practices to binding events triggered by multiple input fields which are dependent on each other in jquery?
For eg: lets take a search engine which searches for students based on what is entered and selected in the fields below.
1. text boxes
2. select lists
3. select boxes
4. option buttons
Without a button which will trigger these events, what is the best way to achieving the following:
Displaying search result as soon as user enters or selects values in one of the input fields and refines the search as users enters or selects values in other fields options.
Displaying search result only after each fields has a valid value.
Any input would be appretiated.
I've put this together this jsFiddle http://jsfiddle.net/VJwpv/1/.
If you are looking at doing validation with JavaScript then I'd recommend you look into this jQuery Validation plugin
HTML
<div id="searchForm">
<input id="textBox" class="searchField" type="text" />
<select id="dropDown" class="searchField">
<option value="Option1">Option1</option>
<option value="Option2">Option2</option>
</select>
<input id="checkbox1Value" type="checkbox" name="checkbox" value="Checkbox1" />Checkbox1
<input id="checkbox2Value" type="checkbox" name="checkbox" value="Checkbox2" />Checkbox2
<input type="radio" name="radio" value="Radio1" /> Radio1
<input type="radio" name="radio" value="Radio2" /> Radio2
</div>
<div id="results"></div>
JavaScript
function validateForm() {
// if valid
return true;
// else return false
}
function performSearch() {
var textBoxValue = $("#textBox").val();
var dropDownValue = $("#dropDown").val();
var checkbox1Value = $("#checkbox1Value").is(":checked");
var checkbox2Value = $("#checkbox2Value").is(":checked");
var radioValue = $("input:radio[name=radio]:checked").val();
// What you'd actually do here is an AJAX call to get the search results
// and pass all the values defined above in the request
$("#results").html("Textbox: " + textBoxValue + ". Dropdown: " + dropDownValue + ". Checkbox1: " + checkbox1Value + ". Checkbox2: " + checkbox2Value + ". Radio: " + radioValue);
}
function onChange() {
if (validateForm()) {
performSearch();
}
}
$(document).ready(function() {
$("#searchForm input, #searchForm select").change(function() {
onChange();
});
});
Just give them all a common class name, and bind the change event using a class selector:
HTML:
<input type="text" class="search-field" />
<input type="text" class="search-field" />
<select class="search-field" ><option>1</option><option>2</option></select>
<input type="radio" class="search-field" />
JS:
$('.search-field').change(function() {
// validate all search field values
// display search results based on values
// if search results already shown, filter based on $(this).val()
});
If you have many of these fields, rather than having a handler be bound to each one (as the above code accomplishes), you would get better performance by using a delegated event handler:
HTML:
<div id='parent'>
<input type="text" class="search-field" />
<input type="text" class="search-field" />
<select class="search-field" ><option>1</option><option>2</option></select>
<input type="radio" class="search-field" />
</div>
JS:
$('#parent').on('change', '.search-field', function() {
// validate all search field values
// display search results based on values
// if search results already shown, filter based on $(this).val()
});