Setting values of selected checkbox - javascript

I have checkboxe that will dynamically appear number of times based on my database. Each checkbox Id is generated dynamically. Where initial value of $i is 1.
<input type="checkbox" name="ch[]" id="<?php echo $i - 1;?>" />
Now want to set value of each selected checkbox to 1 and 0 to all unselected checkbox in real time . Plz help me.

If I understood correctly, to set values in real time you need to do the following:
$("[name='ch[]']").on("change", function() {
this.value = +this.checked;
});
DEMO: http://jsfiddle.net/MMSFB/

If I understand correctly you want to toggle the values of the checkboxes. I would suggest using jquery and something like this:
php:
<input type="checkbox" class="toggleable" name="ch[]" id="<?php echo $i - 1;?>" />;
javascript:
$(".toggleable").each( function(i, elem) {
elem.checked=!elem.checked;
});

Related

I am efforting to send a radio value of input tag in div tag to javascript

I wonder why getElementById doesn't work in radio type.
My HTML code for PHP parsing.
echo "<div id='poll".$i."'>
...
<input type='radio' name='vote' value='0' onclick='getVote".$i."(this.value)'>
...
<input type='radio' name='vote' value='1'onclick='getVote".$i."(this.value)'>
</form>
</div>";
...
<input type='text' name='txtfile' id='txt".$i."' value=".$item_link4." hidden>
$i is number given by for loop in PHP. My js code is something wrong with html code. I show you just 1 sample js code and, please see the detail.
function getVote23(str) {
...
document.getElementById("poll23").innerHTML=this.responseText;
}
}
var vote = document.getElementById("poll23").value+" "+document.getElementById("txt23").value+" "+getCookie("username");
xmlhttp.open("GET","poll_vote.php?vote="+vote,true);
xmlhttp.send();
}
And I have tested the result if the vote value is sent to poll_vote.php.
Next is the first part of poll_vote.php code.
$vote = $_GET['vote'];
echo $vote;
I received the next result.
undefined www.doctorsnews.co.kr-news-articleView.html-idxno=123372 Ohjho
Why null show up? Where does the value of onclick function go out?
Please help me.
Change radio name by name='vote'.$i and pass $i on click of radio button to get vote function and no need to generate repeated code for each block so that you can get value of related radio by
<form >
<img src='./imoticon/good.png' style='width:29px;height:29px;'>좋아요:
<input type='radio' name='vote'.$i value='0' onclick='getVote($i)'>
<img src='./imoticon/bad.png' style='width:29px;height:29px;'>싫어요:
<input type='radio' name='vote'.$i value='1'onclick='getVote($i)'>
</form>
function getVote(index) {
var vote = document.querySelectorAll('input[name="vote'+index+'"]:checked')[0].value+" "+document.getElementById("txt"+index).value+" "+getCookie("username");
xmlhttp.open("GET","poll_vote.php?vote="+vote,true);
xmlhttp.send();
}
The Right code is below.
var vote = str +" "+document.getElementById("txt23").value+" "+getCookie("username");
I appreciate Syscall's brief and right answer.
I didn't cast any downvote ever. But I realized many developers cast that easily and they didn't give any advice nor any answer.
I don't understand that action.
In oriental proverb,
見指忘月
Every developer will search that meaning easily.

Check multiple Checkbox jQuery

I have this code to get back a json string:
$.getJSON("<?php echo BASE_URL; ?>/editTask.php?ID="+tid,function(result){
$.each(result.staff, function() {
$("#checkbox[value=" + this + "]").prop('checked');
});
});
The json looks like this
{"staff":[13,17,15]}
I have a PHP snippet like this
<div id="checkbox" class="checkbox" style="max-height:150px;overflow:auto;">
<?php
for ($i = 0; $i < count($user_list); ++$i) {
echo '<label>'
.'<input type="checkbox" name="tasksUser[]"
value="'.$user_list[$i]['uid'].'">'
.$user_list[$i]['surname'].', '.$user_list[$i]['forename']
.'</label><br />';
}
?>
</div>
I want that every checkbox that has the value that is in result.staff be checked. But I think I have an error in my each part. But in the Firefox console is no error showing.
Could you help me?
Yes there is an issue in your $.each function.
$.each(result.staff,
function() {
$("#checkbox[value=" + this + "]").prop('checked');
^
Here is the issue.
});
});
As you don't have any id or class associated with element you can access it using element name/+type
You must replace your code with
$("input[type='checkbox'][value=" + this + "]").prop("checked", true);
Here I am accessing all checkboxes with values available and setting checked as true.
You're using this selector to look for checkboxes:
$("#checkbox[value...]")
However, the # symbol in a selector looks for an element with that ID.
The checkboxes in your PHP loop do not have a specified ID or class, so you could select them with:
#(":checkbox[value...]")

jQuery - Limit groups of labels and checkboxes to a max number

I'm trying to limit a max number selectable for checkboxes and their relative labels. Checkboxes work fine but labels are still selectable more than the limit.
My html input is formed like this:
<div data-toggle="buttons" class="btn-group bizmoduleselect">
<label id="b-<?php echo $term->term_id; ?>" class="btn btn-default <?php echo $labelchk ?>">
<div class="bizcontent">
<input id="youaresure" type="checkbox" name="email_cats[]" <?php echo $chk ?> value="<?php echo $term->term_id ?>" />
<h5><?php echo $term->name ?></h5>
</div>
</label>
</div>
and my jQuery to limit checkboxes and labels is like:
var $checkboxes = $('input[id="youaresure"]');
var $parent = $checkboxes.parent('label');
var max = 5;
$checkboxes.show();
$checkboxes.change(function () {
$(this).prop('checked', function () {
if ($(this).is(':checked')) {
return ($checkboxes.filter(':checked').length <= max) ? true : false;
}
});
});
$parent.show();
$parent.change(function () {
$(this).prop('class', function () {
if ($(this).is('active')) {
return ($parent.filter('active').length <= max) ? true : false;
}
}
Basically, php inserts an active class to labels parents of inputs:checked and I should prevent both labels and inputs to be selected if more than 5.
For checkboxes is fine but parent labels are still selectable and basically are the visible ones.
EDIT: I've forgotten to indicate that it works with bootstrap and each checkbox is threaten like a button!
There is no change event on <label>. Everything should be done in event handler of the <input>
My suggestion is you disable the other checkboxes when limit is reached.
Following will toggle the active class on label as well as disable/enable unchecked inputs
var max = 5;
var $checkboxes = $(':checkbox').change(function(e) {
var maxChecked = $checkboxes.filter(':checked').length === max;
// disable/enable others based on limit
$checkboxes.not(':checked').prop('disabled', maxChecked);
// toggle label active based on checked state
$(this).closest('label').toggleClass('active', this.checked);
});
DEMO
This doesn’t work because of label has no change handler. Maybe you should better to add your some code into your checkbox’s property check function that removes ‘active’ class of parent labels if necessary.

javascript/jquery: how to add/remove variables from array depending on whether a checkbox is selected

I'm outputting order addresses for a takeout restaurant: each individual order is output as a table, each table has a checkbox. I want to put the addresses into an array when the .ordercollected checkbox is ticked, and remove it from the array if it is unticked.
At the moment, rather than appending each new address I get each order address on its own in the array, which updates each time I tick the .ordercollected checkbox.
Really new to programming so any help appreciated!
//get the addresses from selected tables
$('.ordercollected').change(function() {
var activeaddress = [];
//loop through checkboxes with class .ordercollected
$(this).each(function() {
//if checkbox is ticked
if ($(this).is(':checked')) {
//get address from table
var address = $(this).closest('.ordertable').find('.address').text();
//append value of address into activeaddress array
activeaddress.push(address);
};
});
console.log('active address: ', activeaddress);
});
edit to add in the tables I am creating:
<table class="ordertable">
<tr>
<td>
<p>Order #
<?php echo $order_id; ?> —
<time datetime="<?php the_time('c'); ?>">
<?php echo the_time('d/m/Y g:i:s A'); ?>
</time>
</p>
</td>
<td>
<?php echo $order->billing_first_name . ' ' . $order->billing_last_name ?>
</td>
<td>
<?php if ($order->billing_phone) : ?>
Tel.
<?php endif; ?>
</td>
<td>
<p class="address"><?php echo $order->shipping_address_1 . ' ' . $order->shipping_postcode ?></p>
<td/>
<td>
<a class="maps-activate" href="#">Open in Maps</a>
</td>
<td>
<form action="">
<input type="checkbox" class="ordercollected" value="0" />
</form>
</td>
</tr>
</table>
Rather than remake your entire activeaddress array every time a checkbox changes, the best thing to do here would be to add or remove only the selected address when a checkbox changes. To do this activeaddress will have to be available outside of that function. I also think it will be cleaner if you use a JS object instead of an array.
var activeaddress = {};
$('.ordercollected').change(function() {
// get table id
var orderTableID = $(this).closest('.ordertable').attr('id');
// if checkbox is ticked
if($(this).is(':checked')) {
// get address from table
var address = $(this).closest('.ordertable').find('.address').text();
// append value of address into activeaddress object
activeaddress[orderTableID] = address;
} else { // checkbox is NOT ticked
// remove address from object
delete activeaddress[orderTableID];
}
console.log("active address: ", activeaddress);
});
As you can see, this code assumes that each table with class .ordertable has a unique id that can be used as the key in the activeaddress object. This is better than looping over the entire array/object each time because, especially if you have a very big set of orders. If you had included your HTML I would be able to help more, but as the question is this is as far as I can help. Let me know if you have any follow up questions.
A couple of things to note:
Using pascalCase for variable names and class names makes code more readable (e.g. activeAddress instead of activeaddress)
In my opinion, using an object instead of an array is a better way to add and remove a specific item
When asking question on SO, please give as much information as possible, such as including your HTML
Finally some links:
Adding a key value pair to an object
Removing a key value pair from an object
try something like this?
HTML:
<input type="checkbox" class="ordercollected" value="apple" />
<input type="checkbox" class="ordercollected" value="mango" />
JS
$('.ordercollected').change(function() {
var activeaddress = [];
//loop through checkboxes with class .ordercollected
if (this.checked) {
activeaddress.push(this.value);
}
else {
var index = activeaddress.indexOf(this.value);
if (index > -1) {
activeaddress.splice(index, 1);
}
}
console.log('active address: ', activeaddress);
});

Get value of same class but diff id of checkbox, when a button is clicked

I want to get the value of the checkbox when #catDelete is clicked.
Below is the html code
<?php $i=1; do { ?>
<input type="checkbox" value="<?php echo $row_cat['cat']; ?>" class="checkboxcat" id="<?php echo $i; ?>" name="catcheckbox" style="border:#cccccc 1px solid; background-color:#fff;"><?php echo $row_cat['cat']; ?>
<span id="CatDelete" style="position:relative; left:10px; color:#ff0000; font-size:10px;">Delete</span>
<?php $i++; } while ($row_cat = mysql_fetch_assoc($cat)); ?>
jquery code - It gives me the value of the first checkbox
$('#CatDelete').click(function(){
alert($('.checkboxcat').attr('id'));
});
Any help appreciated. Did search if there was a duplicate question, but did not find.
You haven't shown much of your stucture, but it looks like the checkbox is a sibling element prior to the span. If so:
$("#CatDelete").click(function() {
var val = $(this).prevAll('input').first().val();
console.log(val);
});
That starts from the clicked element, works backward through siblings looking for input elements, grabs the first one, and gets its value.
But you've edited the question now to say it's in a loop. You cannot have more than one element with the same id ("CatDelete"). You'll need to change the span to use a class instead, and then change the above to use that class. So for instance, if you change it to use the class "CatDelete", then:
// v--- Note the change
$(".CatDelete").click(function() {
var val = $(this).prevAll('input').first().val();
console.log(val);
});
Live Working Copy | Source
But I think I'd probably adjust the structure slightly so that you're not hunting through sibling elements like that. If you put each pair (checkbox and button) inside a container, like a div, you can do something a bit more straightforward to find the matching input:
var val = $(this).closest('div').find('input').val();
E.g.
$(".CatDelete").click(function() {
var val = $(this).closest('div').find('input').val();
console.log("The value for the checkbox is: " + val);
});
Live Working Copy | Source

Categories