each checkbox that i check, i fill the input with it's id
now, how can i retrieve this id that i put inside the input if the user uncheck the checkbox?
exp:
estate SC,SP was checked;
input recieve SC,SP value in this format = SC,SP
but the user uncheck the checkbox with SC value, then SC should be removed from the input.
this is what i'm doing to fill the input with the checkboxes.
var separador = ",";
var estadosS = "";
$(".checkboxEstados").live("click", function(){
if($(this).is(":checked")){
estadosS += (estadosS == "") ? "" : separador;
estadosS += $(this).attr("id");
$("#holdEstados").val(estadosS);
}else{
// now i'm just cleaning all the input,
// but i need to clean only the checkbox that was unchecked
$("#holdEstados").val("");
}
});
dont know if i was clear, any question, be my guest.
Thanks.
An easy way to solve this is to avoid parsing and removing parts of the data. Instead of trying to remove 'SC', instead regenerate the entire contents of the text field each time any checkbox is selected.
When a checkbox click event is detected, deleted the contents of the text input field, scan all of the selected checkboxes, and include their IDs in the text input field.
You're logic can be greatly simplified. Simply grab each checkbox that is checked when the click event fires:
$(".checkboxEstados").live("click", function() {
var aryIds = new Array();
$(".checkboxEstados:checked").each(function() {
aryIds.push($(this).attr("id"));
});
$("#holdEstados").val(aryIds.toString());
});
Here's a working fiddle.
I would store the value in an array and add and remove values from it and then write the array to the output instead of trying to parse the text each time:
var estadosS = [];
$(".checkboxEstados").live("click", function(){
var index;
if($(this).is(":checked")){
// append the id to the list
estadosS.push($(this).attr("id"));
}else{
index = estadosS.indexOf($(this).attr("id"));
if(index > -1) {
estadosS.splice(index, 1);
}
}
$("#holdEstados").val(estadosS.join(separador));
});
If all you are aiming to do is get a list of the checked values from all the check boxes, you could do:
$('.checkboxEstados:checked').each(function(){
alert($(this).val());
});
And that should return all the check box items that have been checked. Then you don't have to worry about adding and removing data from a text box. I'm just alerting the value, you would want to store them into an object or something more useful.
Related
I'm new to JavaScript.
I have a webpage that the users can search the document ID and add it to their favourite. after submitting the search criteria, it shows a list ID and a checkbox next to it. so the user can check the checkbox or uncheck it to add and remove them from their list.
My issue is my code can't get the value of the checkbox generated. for example, there are three checkbox generated, chk1,chk2,chk3. when none of them are checked, my code is working I can get the value of the checkbox. but when one of them is checked for example, chk3 is checked, when I check chk1, it still shows the value of chk3 rather than chk1. I want to get the value of that checkbox just checked. I'm struggled to make it right.
<tr><%do until results_rs.EOF%>
<td class="tdid"><%Response.Write results_rs("id")%></td>
<td><input type="checkbox" id="myCheckbox" name ="myf[]" value="<%=results_rs("id")%>" onchange="myfc()">
<script>
function myfc(){
var selchb = getSelectedChbox(this.form);
alert(selchb)
}
function getSelectedChbox(frm) {
var selchbox = null;
var chk_arr=document.getElementsByName("myf[]")
var chklength=chk_arr.length
for (k = 0; k < chklength; k++) {
if (chk_arr[k].checked == true)
selchbox=chk_arr[k].value
}
return selchbox
**strong text**// rs.close;
// connection.close
}
</script></td>
<%results_rs.MoveNext%>
</tr>
The minimal change would be to pass this into myfc:
onchange="myfc(this)"
...and then use that in myfc:
function myfc(cb){
alert(cb.value);
}
But you might look into more modern event handling with addEventListener and such.
Note that there's no need to put an id on the checkbox, and in fact, it's invalid to have more than one checkbox with the same id, so probably best to just remove the id="myCheckbox" part entirely.
IDs in JS must be unique. Use a class class="myCheckbox"
Then you can do
window.addEventListener("load",function() {
var checks = document.querySelectorAll(".myCheckbox");
for (var i=0;i<checks.length;i++) { // all .myCheckbox
checks[i].addEventListener("click",function() {
console.log(this.checked,this.value); // this specific box
var checks = document.querySelectorAll(".myCheckbox:checked");
for (var i=0;i<checks.length;i++) { // all CHECKED .myCheckbox
console.log(checks[i].value); // only checked checkboxes are shown
}
});
}
});
In your case for example
window.addEventListener("load",function() {
var checks = document.querySelectorAll(".myCheckbox");
for (var i=0;i<checks.length;i++) { // all .myCheckbox
checks[i].addEventListener("click",function() {
if (this.checked) myfc(this.value); // this specific box
});
}
});
I have a form where i need to auto calculate value for checked row.
http://codepen.io/anon/pen/dOBaNN?editors=1010
I am calculating the value for the text field on keyup function but need to do following
Keep All text fields disabled
Second i need to enable only text field related to the checkbox checked
Third Calculate sum for only Checked text field
Right now i am able to calculate value for all checkbox not sure how to map checked checbox to related input and calculate values accordingly.
tried few thing but it keep breaking
1) Too disable your text fields set the disabled property to true.
$(".auto-sum").each(function () {
$(this).prop('disabled', true);
});
2) Enable inputs with checkboxes
$('input[type=checkbox]').on('change', function() {
var id = $(this).val();
var active = $(this).prop('checked');
$('.auto-sum[name=Amount' + id + ']').attr('disabled', !active);
calculateSum();
});
3) Skip disabled inputs when calculating
$(".auto-sum").each(function () {
if ($(this).prop('disabled')) return;
[...]
});
I updated your codepen: http://codepen.io/anon/pen/VmJgxM?editors=1011
I have multiple select inputs on a page and I'd like to set all of them to have a particular option selected if a checkbox is checked
Once the form is submitted the inputs that have been updated will be looped through and sent to the database, so I have a function to append a string to the option value which is called on change of the select
This is all working great, however I'd like to append the updated string (to the value, not text) when the select option is changed by the checkbox being checked, but can't seem to get this to work
Fiddle https://jsfiddle.net/69zzr6xa/2/
I've tried looping through each select like so and then checking if the second option is already selected. If not, append the string, but it doesn't appear to work
$('select').each(function() {
if (!$(this).$('option').text == 'Two') {
var inputname = $(this).find(":selected")[0].value;
$(this).(":selected").val(inputname + "-updated");
}
});
I think this is what you are looking for.
function set_to_two() {
$('option:nth-child(2)').each(function(){
$(this).prop('selected', true);
if( $(this).val().indexOf('-updated') < 0 ){
$(this).val( $(this).val() + "-updated" );
}
});
set_updated();
}
I am trying to get the value of a text input where the select box next to it is selected.
I've got to somehow join the checkbox and text-input together, so it knows only calculate the value of the text input where the checkbox on the same table row is selected.
An issue is also the fact that none of my checkboxes get the attribute of 'checked' when selected either, so I've not been able to target those which are :checked too.
I suspect my method so far is going a little too over the top so any suggestions are welcome.
http://rlpetproducts2.designlocker.co.uk/index.php?route=product/product&product_id=251
$('table.table-bordered input[type="checkbox"]').change(function () {
$(this).toggleClass('jordan');
});
$('#button-cart').hover(function () {
var sum = 0;
$('table.table-bordered input[type="checkbox"]:checked').each(function() {
$('table.table-bordered input[type="text"].jordan').each(function() {
sum += Number($(this).val());
});
});
console.log(sum);
});
The Goal: on 'Add to Basket' click, check at least one of the selected options is selected (else alert), if one is selected, calculate the total quantity from the inline input fields (where checkbox is selected) (for now simply alert the quantity total).
In this example, the value to be alerted would be 5.
Untested but it should work like this:
$('#button-cart').hover(function () {
var parent, sum = 0;
$('table.table-bordered input[type="checkbox"]:checked').each(function() {
// get current row
parent = $(this).closest('tr');
// in row find input and add the value
sum += parseFloat(parent.find('input[type="text"].jordan').val());
});
console.log(sum);
});
I am trying to clear a form and then repopulate it with new data. I have a page that has a list of search histories, along with a "search again" button, when clicked, it takes that search history string, split it, then match those again all the various form items; checkbox, radio, etc. The form has basically every kind of form element in it and everything is populating like I want it to except the checkboxes. The first time I click the populate form button, it works fine, but after the first click all the checkboxes start going haywire...some items populating like they should, some not, in a strange random pattern. I have not included the html because I don't think it is necessary but if anyone needs more info, please let me know.
This resets the form. I have tested this independently and it works.
function form_reset(){
$('#hosp_search_form')[0].reset();
$('#hosp_search_form').find("input[type=text], textarea").val("");
$('input[type=checkbox]').each(function(){
$('input[type=checkbox]').removeAttr('checked');
});
$('input[type=number]').val('');
$('input[type=radio]').each(function(){
$(this).removeAttr('checked');
});
On click, first clear the form of previous values, then grab the other needed values and format them...this part gets a little ugly in sections but I have consoled out all the values and everything is how it should be.
$('.search_again_btn').on('click', function(){
form_reset();
$('#hosp_search_form').find('input[type=checkbox]').removeAttr('checked');
var id = $(this).data('id');
var searchstring = $('#searchstring_' + id).text();
var patientcode = $('#patientcode_' + id).text();
var mrn = $('#mrn_' + id).text();
var first_name = patientcode.substr(0,2);
var last_name = patientcode.substr(2,2);
var age = patientcode.substr(4,3);
var gender = patientcode.substr(6,2);
var age = age.replace(/\D+/g, '');
gender = gender.replace(/[0-9]/g, '');
Populates some of the form, works fine
//populate fields in search form
$('input[name=fn]').val(first_name);
$('input[name=ln]').val(last_name);
$('input[name=patientage]').val(age);
$('input[name=mrn]').val(mrn);
Populate another part of the form, also always works as needed
//populate gender fields
if(gender == 'F'){
$('.female').attr('checked', 'checked');
}
if(gender == 'M'){
$('.male').attr('checked', 'checked');
}
Here is where I suspect the issue is. splitsearch is a long string (a previous search history) with items separated by a . and they get split into separate items. I console logged this, it correctly breaking it into the smaller values like I need, then iterate through those and iterate through all the checkboxes which each have a data attr holding values that can be in the splitsearch. If a value matches, it should make it checked. This works every time the first time, for any combo of splitsearch/search string values, but after the first time, I don't know what it is doing. I expect that each click, the form is cleared and it does the value matching again as I described.
//populate checkboxes
var splitsearch = searchstring.split('. ');
$.each(splitsearch, function(key, value){
$('input[type=checkbox').each(function(keyb, checkbox){
item = $(checkbox).data('services');
if(item == value){
$(this).attr('checked', 'checked');
console.log($(this));
}
});
This is doing the same as the above but works every time...probably because there is never multiple combinations like with checkboxes.
$('input[name=payor]').each(function(k, radio){
if(value == $(radio).data('payors')){
$(this).attr('checked', 'checked');
//console.log($(this));
}
});
Also like the above and works.
$('input[name=bedtype]').each(function(keyc, radio){
bed = $(radio).data('bed');
if(bed == value){
$(this).attr('checked', 'checked');
}
});
This part below is quite ugly but is populating the form like I need every time.
//if searchstring contains Needs Transportation, returns true, else returns false
if(value.indexOf("Needs Transportation") > -1 === true){
$('.transyes').attr('checked', 'checked');
}
if(value.indexOf("Near hospital") > -1 != true){
$('input[name=desiredzip]').val(searchstring.substr(5,5));
}
if(value.indexOf("5 mile radius") > -1 === true){
$('.miles_5').attr('checked', 'checked');
}
if(value.indexOf("10 mile radius") > -1 === true){
$('.miles_10').attr('checked', 'checked');
}
if(value.indexOf("15 mile radius") > -1 === true){
$('.miles_15').attr('checked', 'checked');
}
if(value.indexOf("20 mile radius") > -1 === true){
$('.miles_20').attr('checked', 'checked');
}
});
Scrolls the window up to the populated search form and show it.
window.scrollTo(0,100);
$('#search_show').show();
});
Just a thought but, it might help you to restructure your code a bit to keep it DRY.
// used to Hold search data in local or global
var data;
function form_reset() {
// clear form
}
function get_search_data() {
// populate data with search results
}
function form_populate() {
// use data to populate form
}
$('.search_again_btn').on('click', function(){
get_search_data();
form_reset();
form_populate();
});
// Initial Load of form
get_search_data();
form_populate();
that way you use the same population function initially as you do when you refresh and it forces you to put your data into a variable that can be seen in both the clear and populate functions removing your reliance on this and $(this).
also you need to bear in mind that the value of this inside a click function is going to be in the context of the click event itself and not the JavaScript object that the rest of your code belongs to.