So i have a checkbox which is loading from php on other page and since i cannot get the values of them ive written a jquery script that was supposed to check if a checkbox was checked and if so it would mark the corresponding hidden input with value 1 or 0.
But seems like it's only working for 1 in the loop no matter what i do.
<script>
$(document).ready(function() {
var total = <?php echo $count; ?>;
for (i = 0; i < total; i++) {
$('input[type="checkbox"]').change(function(event) {
if($(this).is(":checked")){
$(".check_"+i).val(1);
console.log("added"+i);
}else{
$(".check_"+i).val(0);
console.log("removed"+i);
}
});
}
});
</script>
looks like you are registering change event handler of checkbox for multiple times instead you need to put 1 or 0 on multiple i=hidden inputs.
You don't need loop here, just add change event handler for all checkboxes having id starts with check_ and read same id to create input hidden class selector. Set the value to input hidden.
See below code -
<script>
$(document).ready(function() {
//bind change event for checkbox having id starts with "check_"
$(document).on('change','input[type="checkbox"][id^=check_]', function(event) {
var id = $(this).attr('id');// id of checkbox checked/unchecked
$("."+id).val($(this).is(':checked')?1:0); // put 1 or 0 to the matching hidden input
});
});
</script>
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 creating a form builder script. I have a select input where the user can select the form element they want to use, depending on their selection ("select", "checkbox" or "radio") another form field is displayed allowing users to input their options.
Users can create as many instances of form elements as they want, so each select input has a dynamically created id that corresponds to the id of the hidden form field. I then use jQuery to determine whether the "options" field should be hidden or not (triggered on change of the form elements select input).
Currently, for every instance, I have the following code addedabove the select input:
<script>
jQuery(document).ready(function($) {
var arr = ['select', 'checkbox', 'radio'];
var thisForm = 'select.input-type-118';
function showHideSelect() {
var val = $(thisForm + ' option:selected').val();
var selectOptions = $('#select-options-118')
if (arr.indexOf(val) >= 0) {
selectOptions.show();
} else {
selectOptions.hide();
}
}
showHideSelect();
$(thisForm).change(function() {
showHideSelect();
});
});
</script>
Where var thisForm and var selectOptions are added dynamically and refer to the select option below this script.
I'm wondering if there is a better way to do this rather than repeat several instances of this, at the moment, a users page cold look like this:
<script>
...
</script>
<select>
...
</select>
<textarea>
This is hidden depending on the select option
</textarea>
<script>
...
</script>
<select>
...
</select>
<textarea>
This is hidden depending on the select option
</textarea>
<script>
...
</script>
<select>
...
</select>
<textarea>
This is hidden depending on the select option
</textarea>
...etc...etc
My concern is that I don't think it's best practice to have so many instances of the same script, but I'm unsure how to write a global script that will allow me to show/hide the textarea on an individual basis.
I have shown a more accurate depiction of my workings on this jsfiddle here:
https://jsfiddle.net/46stb05y/4/
You can use Event Delegation Concepts. https://learn.jquery.com/events/event-delegation/
With this you can change your code to
$(document).on('change','select',function() { //common to all your select items
showHideSelect($(this)); // passing the select element which trigerred the change event
});
This will work even on the select items that are added dynamically
You must change your function to receive the element as the parameter.
function showHideSelect($selectElement) {
var val = $selectElement.val();
var selectOptionsId = $selectElement.attr('class').replace('input-type','select-options');
var selectOptions = $("#"+selectOptionsId);
if (arr.indexOf(val) >= 0) {
selectOptions.show();
} else {
selectOptions.hide();
}
}
Here is the Working JsFiddle
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.