jquery .each not working in IE - javascript

I have a list of checkbox
<input type="checkbox" name="box1" id="box1" value="x1">X1
<input type="checkbox" name="box1" id="box1" value="x2">X2
<input type="checkbox" name="box1" id="box1" value="x3">X3
The name of the checkbox and the count of checkbox is dynamic.
To retrieve the values of selected checkbox i am using the function as
var urls = "";
var values = "";
var fldname = "box"+i;
$('#'+fldname+':checked').each(function() {
values += $(this).val() +"|";
});
Say I have selected X1 and X3 then in Mozilla the value of "values" is
X1 | X3
While in IE it is just X1.
Please help.

I don't know how your code worked in Mozilla because your syntax is wrong.
You've given all your checkboxes names, but are querying for them using IDs
You need something like
$('[name="' + fldname + '"]:checked');
This basically looks for elements with the given name. You can make it more specific
$('input[name="' + fldname + '"]:checkbox:checked');
Here's an example that doesn't use your iteration : http://jsbin.com/ikifi5

Related

jQuery - Count number of checked checkboxes with a given Id value

I have a page with a table on it. Two of the columns in the table are checkbox columns. Each has a different Id value. I'm trying to count, via jQuery, the number of rows in the table where one of the checkbox columns (which has an Id value of 'InChecklist') is checked. My JS function looks as follows:
function UpdateCount() {
var totalRows = $('#checklistTable tbody tr:visible').length;
var totalSeen = $(":input#InChecklist[checked='checked']").length;
$("#rowCount").text(totalRows.toString() + " species / " + totalSeen + " seen")
}
The total row count is fine. But I must not have the syntax correct for the total seen because I cannot get it to count correctly (the value is always zero). If I remove the '#InChecklist', I do get a value greater than zero, but in this case, it's counting the total checked in both checkbox columns, not the one with an Id of 'InChecklist'.
If it helps, the portion of my HTML that renders the checkboxes look as follows. It's MVC5.
<td>
<input id="InChecklist" name="item.HasBeenSeenChecklist" type="checkbox" value="true" /><input name="item.HasBeenSeenChecklist" type="hidden" value="false" />
</td>
<td>
<input id="InLifelist" name="item.HasBeenSeenLifelist" type="checkbox" value="true" /><input name="item.HasBeenSeenLifelist" type="hidden" value="false" />
</td>
Specify the ID before the :input like this
var totalSeen = $("#InChecklist:input[checked='checked']").length;
Edit
var totalSeen = $("input#InChecklist:checked").length;
EDITED:
you can try:
var totalSeen = $("#InChecklist input:checked").length;
selects all the children inputs of #InChecklist
alternatively you can use this:
var totalSeen=0;
$("#InChecklist input").each(function(){
if($(this).is('checked')){
totalSeen++;
}
});

check checkbox if another checkbox is checked

I want the checkbox with the value 2 to automatically get checked if the checkbox with the value 1 is checked. Both have the same id so I can't use getElementById.
html:
<input type="checkbox" value="1" id="user_name">1<br>
<input type="checkbox" value="2" id="user_name">2
I tired:
var chk1 = $("input[type="checkbox"][value="1"]");
var chk2 = $("input[type="checkbox"][value="2"]");
if (chk1:checked)
chk2.checked = true;
You need to change your HTML and jQuery to this:
var chk1 = $("input[type='checkbox'][value='1']");
var chk2 = $("input[type='checkbox'][value='2']");
chk1.on('change', function(){
chk2.prop('checked',this.checked);
});
id is unique, you should use class instead.
Your selector for chk1 and chk2 is wrong, concatenate it properly using ' like above.
Use change() function to detect when first checkbox checked or unchecked then change the checked state for second checkbox using prop().
Fiddle Demo
Id should be unique, so that set different ids to your elements, By the way you have to use .change() event to achieve what you want.
Try,
HTML:
<input type="checkbox" value="1" id="user_name1">1<br>
<input type="checkbox" value="2" id="user_name2">2
JS:
var chk1 = $("input[type='checkbox'][value='1']");
var chk2 = $("input[type='checkbox'][value='2']");
chk1.change(function(){
chk2.prop('checked',this.checked);
});
You need to change the ID of one. It is not allowed by W3C standard (hence classes vs ID's). jQuery will only process the first ID, but most major browsers will treat ID's similar to classes since they know developers mess up.
Solution:
<input type="checkbox" value="1" id="user_name">1<br>
<input type="checkbox" value="2" id="user_name_2">2
With this JS:
var chk1 = $('#user_name');
var chk2 = $('#user_name2');
//check the other box
chk1.on('click', function(){
if( chk1.is(':checked') ) {
chk2.attr('checked', true);
} else {
chk2.attr('checked', false);
}
});
For more information on why it's bad to use ID's see this: Why is it a bad thing to have multiple HTML elements with the same id attribute?
The error is probably coming here "input[type="checkbox"]
Here your checkbox is out of the quotes, so you query is looking for input[type=][value=1]
Change it to "input[type='checkbox'] (Use single quote inside double quote, though you don't need to quote checkbox)
http://api.jquery.com/checked-selector/
first create an input type checkbox:
<input type='checkbox' id='select_all'/>
$('#select_all').click(function(event) {
if(this.checked) {
$(':checkbox').each(function() {
this.checked = true;
});
}
});

Adding checkbox values with different input names

I have the following code which adds together checkboxes when they are selected and produces a total at the bottom of the page. This function uses the following code:
<script type="text/javascript">
function checkTotal() {
document.listForm.total.value = '';
var sum = 68.50;
for (i=0;i<document.listForm.choice.length;i++) {
if (document.listForm.choice[i].checked) {
sum = sum + parseFloat(document.listForm.choice[i].value);
}
}
document.listForm.total.value = sum.toFixed(2);
}
</script>
These checkboxes are within a form, and I need the form to send through to an email account. At the moment because all the checkboxes share the same input name 'choice' the PHP will only send the last checked box value.
I need to change the checkboxes input name code to name the different checkboxes 'choice1' 'choice2' 'choice3'. What would I have to change in the javascript to in order for the function to calculate all the checkboxes names 'choice1' 'choice2' 'choice3' etc rather than just adding together all checkboxes named'choice'? I have little Javascript and PHP knowledge so any help would be grateful. Thanks.
Rather than make the checkbox names unique, it would be better to append "[]" to their name. This will cause PHP to convert the values into an array, rather than just keep the last value.
So you would want a name of choice[] rather than choice.
You can also find some sample code in this answer.
The code below works ok (a self contained web page). The problem is how to get the array (group) of checkboxes when they're called different names. If you use jquery you could give them all the same class, then get hold of them by that class, but if you're using bare javascript then you can get the elements by Tag name ("input" in the case of the checkbox), and check each one has a name attribute that starts with "choice", inoring those that don't start with "choice", like buttons (also an input) or maybe other checkboxes with different names. It's a bit inefficient if the page is huge, unless you group the checkboxes some way.
To group them, you cold put them in a tag like
`<div id="checkboxes"> (checkboxes go here) </div>`
then use
`var cb = document.getElementById("checkboxes");`
`var arrInputs =cb.getElementsByTagName("input");`
for the line to get the arrInputs array. This would just get input type elements from within the Div. Hwever I dind't want to assume the page layout allows your checkboxes to be put in one div
Hope this helps
Doug
<script type="text/javascript">
function checkTotal() {
document.forms.listForm.total.value = '';
var sum = 68.50;
var frm=document.forms.listForm; // wasnt sure what your original listForm element was so I've put this form into a variable, frm
frm.total.value = '';
var arrInputs =document.getElementsByTagName("input"); // get all Input type elements on the form
for (i=0; i < arrInputs .length;i++) {
if (arrInputs[i].name.substr(0,6) == "choice") { // if the name starts with "choice"
if (arrInputs[i].checked) {
sum = sum + parseFloat(arrInputs[i].value);
}
}
}
frm.total.value = sum.toFixed(2);
}
</script>
</head>
<body>
<form name="listForm">
<a href='javascript:checkTotal()'>check</a><br>
<input type=checkbox name="choice1" value="1"><br>
<input type=checkbox name="choice2" value="2"><br>
<input type=checkbox name="choice3" value="3"><br>
<input type=checkbox name="choice4" value="4"><br>
<input type=checkbox name="choice5" value="5"><br>
<input type=checkbox name="choice6" value="6"><br>
<br>
<input type=text name=total value=""><br>
</form>
</body>
</html>

How do I use two .siblings with the same input type?

I want to get "The walking dead" also but it only gets the first hidden. Can i put a class on .this or how should I do?
$(".articel input[type='button']").click(function(){
var price = $(this).siblings("input[type='hidden']").attr("value");
var quantity = $(this).siblings("input[type='number']").attr("value");
var name = $(this).siblings("input[type='hidden']").attr("value");
var ul = document.getElementById("buylist");
var prod = name + " x " + quantity + " " + price + "$";
var el = document.createElement("li");
el.innerHTML = prod;
ul.appendChild(el);
<form class="articel">
Quantity: <input type="number" style="width:25px;"><br>
Add to cart: <input type="button" class="btn">
<input type="hidden" value="30">
<input type="hidden" value="The walking dead">
</form>
The conventional way to identify form fields is by the name property.
HTML:
<input type="hidden" name="title" value="The walking dead">
jQuery:
var name = $(this).siblings('input[name=title]').val();
Your current selector, siblings("input[type='hidden']"), selects all hidden field siblings, but since you have no way to discern them, attr will always just yield the value of the first match.
You could also have iterated over your collection of elements, or accessed them by index siblings('input[type=hidden]:eq(1)') or siblings('input[type=hidden]').eq(1), for instance, but it is a poor design that will break your code if you add another hidden field for something else. You really should prefer to name your elements so that you can access them in a meaningful way and know your data. That way you'll be free to move around and modify your markup according to new requirements, without breaking your script.
By the way, I'm using .val() above, which is shorthand for .attr('value').
One option is to use special selectors, e.g. :first and :last:
var price = $(this).siblings("input[type='hidden']:first").attr("value");
var name = $(this).siblings("input[type='hidden']:last").attr("value");
However, you always can set a class name to the elements:
<input type="hidden" class="price" value="30">
<input type="hidden" class="name" value="The walking dead">
var price = $(this).siblings(".price").attr("value");
var name = $(this).siblings(".name").attr("value");
I would add an class name to your hidden inputs (price, name). This way the html source code is more readable and also the js code will be more readable.

Check Box Values to List Jquery

Hi all I am struggling to achieve my my goal and I really need some help.
I have a list of single check boxes that I need to be able to get the values and be able to put them in to a list
So for example 3 check boxes on the screen there could be more, the user clicks on one one or all of the them, and I want to be able to output the following:
<ul>
<li>Checkbox1 Value</li>
<li>Checkbox2 Value</li>
<li>Checkbox13Value</li>
</ul>
I also need to be able to save the selected values to a hiiden field as well like this if possible:
Checkbox1 Value | Checkbox2 Value | Checkbox3 Value
There will be 2 sections on the page with where I will need this functionality so I assume I will be looking into the div tags that contain the check boxes.
I have found some code but I get it to do what I need
function updateTextArea() {
var allVals = [];
$('#c_b :checked').each(function() {
allVals.push($(this).val());
});
$('#EXCUR').val(allVals)
$('#t').val(allVals)
}
$(function() {
$('#c_b input').click(updateTextArea);
updateTextArea();
});
My HTML will be like this:
<div id="c_b">
<div>
<input type="checkbox" value="one_name">
<input type="checkbox" value="one_name1">
<input type="checkbox" value="one_name2">
</div>
</div>
<div id="c_G">
<div>
<input type="checkbox" value="one_name" checked>
<input type="checkbox" value="one_name1">
<input type="checkbox" value="one_name2">
</div>
</div>
<textarea id="t"></textarea> <!-- UL LIST SHOULD GO HERE -->
<input type="hidden" id="EXCUR" />
<div id="OP"></div>
Any help with this would be great, I just cant get it to work
Many thanks in advance
Jason
Here is a fiddle of what I think you're looking for but if you answer my comment above I'll be able to help you further.
You can use jQuery's map() to extract the values you want into an array and then join the items in the array however you want.
Something like this:
function updateTextArea() {
var items = $.map($('#c_b :checked'),function(el, ix) {
return 'Checkbox' + (ix+1) + ' ' + $(el).val();
});
if(items.length > 0) {
$('#t').val('<ul><li>' + items.join('</li><li>') + '</li></ul>');
$('#EXCUR').val(items.join(' | '))
} else {
$('#t').val('');
$('#EXCUR').val('');
}
}
$(function() {
$('#c_b input').click(updateTextArea);
updateTextArea();
});
Fiddle to demonstrate
function updateTextArea(){
var vals = []
var str="<ul>";
//iterate over checked boxes
$("input:checked").each(function(){
var v = $(this).val()
vals.push(v)
str += "<li>" + v + "</li>"
})
str+="</ul>"
$("#EXCUR").val(vals.join("|"));
$("#t").val(str);
}
$(function(){
//bind click to all checkboxes in the page
$(":checkbox").click(updateTextArea);
})

Categories