I have gotten pretty far with this in jsFiddle, though I can't figure out why it's not adding a bullet to the first value..
http://jsfiddle.net/dvCmR/128/
<div id="checkboxes">
<input id="chkbx_0" type="checkbox" name="one" />Option 1
<input id="chkbx_1" type="checkbox" name="two" />Option 2
<input id="chkbx_2" type="checkbox" name="three" />Option 3
<input id="chkbx_3" type="checkbox" name="four" />Option 4
</div>
<div class="content"></div>
<script>
$("input").click(function(e) {
var selected = $("#checkboxes input:checked").map(function(i, el) {
return el.name;
}).get();
$('.content').empty();
$(".content").append(selected.join("<li>"));
});
</script>
Thanks!!!
As #Pointy said, join will not add li when you have a single element. Also, you don't need to use join at all, simply add the elements with a single loop:
$("input").click(function(e) {
var $content = $('.content').empty();
$("#checkboxes input:checked").each(function(i, el) {
$("<li>" + el.name + "</li>").appendTo($content);
});
});
DEMO.
The .join() function only puts the string between elements. The result is therefore
name1<li>name2<li>name3
when you need
<li>name1<li>name2<li>name3
Also, dropping <li> elements into a <div> is pretty questionable.
You can still use .join(), but you should add another <li> to the beginning of the result string when (after the join) it's not empty.
Try this:
$("input").click(function(e) {
var selected = $("#checkboxes input:checked").map(function(i, el) {
return "<li>"+el.name+"</li>"
}).get();
$(".content").html(selected.join(""));
});
Fiddle
Related
I want to display all the cheked values of a chekbox, this is my attempt:
<p>jQuery is :</p>
<input type="checkbox" id="s" name="super"> Super !<br>
<input type="checkbox" id="g" name="genial"> Génial<br>
<input type="checkbox" id="j" name="joli"> Joli<br>
<input type="button" value="display" id="disp">
<script>
$('#disp').click(function(data){
$("input[type=checkbox]").is(":checked");
alert($("this").val());
});
</script>
Certainly you could try a little bit harder to solve this on your own, no?
Regardless, your checkboxes don't have value attributes defined: name & value are different attributes.
$('this') would try to make a collection of <this> elements, and $(this) would refer to the button in that event handler.
You're looking for something along these lines:
http://jsbin.com/luyaweqaqe/1/edit?html,js,output
HTML
<input type="checkbox" value="super"> Super !<br>
<input type="checkbox" value="genial"> Génial<br>
<input type="checkbox" value="joli"> Joli<br>
<button id="bt">Check</button>
JS
$('#bt').on('click', function () {
var arr = [];
$('input[type="checkbox"]:checked').each(function () {
arr.push($(this).val());
});
alert(arr);
});
Here's some reading material:
jQuery API
HTML Attributes
It cannot get the value with .val because there is no value. Try something like this:
<p>jQuery is :</p>
<input class="box" type="checkbox" value="Super">Super</br>
<input class="box" type="checkbox" value="Génial">Génial</br>
<input class="box" type="checkbox" value="Joli">Joli</br>
<input type="button" value="display" id="disp">
$('#disp').click(function () {
$(".box:checked").each(function () {
alert($(this).val());
});
});
JS fiddle: https://jsfiddle.net/ms14eLz0/1/
Hi you can try something like this. You do not need data in your function as your not passing anything in it. What this should do is find all the boxes which are checked and then loop through them and add them to the array. Then alert it at the end.
$('#disp').click(function () {
var array = [];
$(".box:checked").each(function () {
array.push($(this).val());
});
alert(array + ' checked');
});
**I have a form containing a list of checkboxes. I wish to display some text corresponding to each check box in the order of selection of the check box in another block.And when I deselect a checkbox that text should disappear and if I reselect it it should appear below the existing text. I already checked though many questions in this site. Everywhere there's explanation for the text to appear but not in the order in which the checkbox is checked rather in the order of the checkboxes themselves. I want to do this using html and jquery. Any help towards the direction would be appreciable **
http://jsfiddle.net/jinal1482/Lfuzkkvz/
You can replace 'a' and 'b' with your value or you can retrieve value by other attribute as well.
Html code :
<input type='checkbox' onclick="updateList('a',this)" />
<input type='checkbox' onclick="updateList('b',this)" />
Javascript code :
var options = [];
function updateList(obj,source){
if($(source).attr('checked')){
options.push(obj);
}
else{
options= $.grep(options, function( a ) {
return a !== obj;
});
}
console.log(options);
}
Use a combination of id tag and attribute data-id with the same value in order to connect checkbox and text
http://jsfiddle.net/edobs5cf/
HTML:
<div id="checkbox_div">
<input type='checkbox' data-id="#txt-1" />text 1<br/>
<input type='checkbox' data-id="#txt-2" />text 2<br/>
<input type='checkbox' data-id="#txt-3" />text 3<br/>
<input type='checkbox' data-id="#txt-4" />text 4<br/>
</div>
<div id="text">
<div id="txt-1">text 1</div>
<div id="txt-2">text 2</div>
<div id="txt-3">text 3</div>
<div id="txt-4">text 4</div>
</div>
CSS:
#text div{display:none}
JQ:
$('#checkbox_div input[type="checkbox"]').click(function () {
var $ch = $(this);
var $id = $ch.data('id');
if ($ch.is(':checked')) {
// ensures that the text appears at the end of the list
$($id).appendTo($('#text'));
$($id).show();
} else $($id).hide();
})
Here's a simple example:
HTML:
<input type="checkbox" value="Apple">Apple</input>
<input type="checkbox" value="Banana">Banana</input>
<input type="checkbox" value="Mango">Mango</input>
<input type="checkbox" value="Orange">Orange</input>
<input type="checkbox" value="Grape">Grape</input>
<ul></ul>
JavaScript (jQuery):
$("input").on("change", function (e) {
$("ul").html("");
$("input:checked").each(function () {
$("ul").append("<li>" + this.value + "</li>");
});
});
Given the details in the OP this should be what you're looking for. Basically when one of the inputs (checkboxes) change, we update our list by looping through each checked input. Depending on what you actually want the text to be you would need to modify this example. For each input I would consider putting the text you want to display when an input is clicked in a data attribute. Something like:
<input type="checkbox" value="Apple" data-text="Apples are yummy">Apple</input>
That way in the loop you could grab each inputs data-text attribute and display that instead.
I have checkbox html.
<label><input type="checkbox"><span>Air Conditioning</span></label>
<label><input type="checkbox"><span>Cable TV Service</span></label>
<label><input type="checkbox"><span>Private Bathroom</span></label>
I need to have seperate value for each checkbox, so I can get those values from all and store in variable. For example
<label><input type="checkbox" data="1"><span>Air Conditioning</span></label>
<label><input type="checkbox" data="2"><span>Cable TV Service</span></label>
<label><input type="checkbox" data="3"><span>Private Bathroom</span></label>
So if all the 3 are selected I will need my variable as
room_features = '1-2-3';
If any one is then unchecked, variable will be updated as
room_features = '2-3';
So on every change on checkbox, variable should be updated. I am confused if either adding data="1" etc is fine for checkboxes? I normally do for anchors when there is single double quotes.
Live Demo
You should use value in each checkbox. for ex:
HTML:
<input type="checkbox" value="1" checked />
<input type="checkbox" value="2" checked />
<input type="checkbox" value="3" />
JQuery:
var searchIDs = $("input:checkbox:checked").map(function(){
return this.value;
}).toArray();
html
<label><input type="checkbox" checked="checked" data="1"><span>Air Conditioning</span></label>
<label><input type="checkbox" checked="checked" data="2"><span>Cable TV Service</span></label>
<label><input type="checkbox" data="3"><span>Private Bathroom</span></label>
JS
var selectedvalue=[];
$(":checkbox:checked").each(function(){
selectedvalue.push($(this).attr("data"));
});
alert(selectedvalue.join("-"));// your desired result
demo
reference Arrays and checked-selector
You can use .map() method, note that I have added value attribute to the element instead of data as an input should have a value otherwise what's the point of using it? If you want to use data-* attributes, you should specify an identifier. Something like <input type="checkbox" data-id="1">, then you can get the value using jQuery data() method: $(elem).data('id');.
<label><input type="checkbox" value="1"><span>Air Conditioning</span></label>
...
var vals = $('input[type=checkbox]:checked').map(function(){
return this.value; // return $(this).data('whatever');
}).get().join('-');
get() returns an array, if you need an array you can remove the .join() method which returns a string.
try this dynamic one
var room_features = "";
$('[type=checkbox]').change(function () {
var data = "-" + $(this).attr('data');
if (room_features.indexOf(data) != -1) {
room_features = room_features.replace(data, "");
alert(room_features);
} else {
room_features = room_features + data;
alert(room_features);
}
});
Demo Fiddle
javascript
getElementById("chkbox1").checked=true;
jquery
$("#chkbox1").prop("checked");
or
$("#chkbox1").attr("checked");
check this Jsfiddle
$("#btn").click(function(event){
var selectedvalue=[];
$(":checkbox:checked").each(function(){
selectedvalue.push($(this).attr("data"));
});
alert(selectedvalue.join("-"));// your desired result
})
How can I get the value of the closest textbox and assign it into a variable? Then after getting the value, change the current value of that textbox by multiplying it by the value of previous textbox. I have three instances of divs with the same input elements so I think .closest() or .next() can help me. Here is a snippet of my code
HTML
<div class="box">
<b>1</b>
<input type="text" name="quantity" value="1"/>
<input type="checkbox" name="ignoreThisCheckbox" checked="checked"/>
<input type="text" name="price" value="10"/>
</div>
<div class="box">
<b>2</b>
<input type="text" name="quantity" value="1"/>
<input type="checkbox" name="ignoreThisCheckbox" checked="checked"/>
<input type="text" name="price" value="10"/>
</div>
<div class="box">
<b>3</b>
<input type="text" name="quantity" value="1"/>
<input type="checkbox" name="ignoreThisCheckbox" checked="checked"/>
<input type="text" name="price" value="10"/>
</div>
JS
$("input[name=quantity]").each(function(){
$(this).bind("change keyup", function(){
var q = $(this).val();
var p = parseFloat($(this).closest("input[name=price]").val()).toFixed(2);
var amount = q * p;
$(this).closest("input[name=price]").val(amount)
console.log(amount);
})
})
non working demo
http://jsfiddle.net/c6yfS/
Thank you for responses
/* NOTE */
The purpose of the checkbox is just to show that I have a checkbox in between the two elements concerned.
As mentioned by other posters, you can use .siblings as .closest searches up the DOM tree (i.e. parent elements). However there is also a logic error in your code as the price you retrieve is never the right per unit price if quantity is changed. You will need a separate unit price hidden value perhaps to facilitate this
Check out the updated code here: http://jsfiddle.net/c6yfS/1/
it's better to use data attribute in order to calculating correctly:
HTML:
<div class="box">
<b>1</b>
<input type="text" name="quantity" value="1"/>
<input type="checkbox" name="ignoreThisCheckbox" checked="checked"/>
<input type="text" name="price" data-value="10"/>
</div>
JS:
$('input[name=quantity]').on("change keyup", function(){
var q = 0;
var p = 0;
var amount = 0;
q = parseInt($(this).val(), 10);
p = parseInt($(this).siblings("input[name='price']").data('value'), 10);
amount = q * p;
if (amount) {
$(this).siblings("input[name='price']").val(amount)
console.log(amount);
} else {
$(this).siblings("input[name='price']").val('Please specify the quantity')
}
})
DEMO
.closest is used to find the closest element up the DOM tree. What you are looking for is siblings or next | prev.
http://api.jquery.com/siblings/
http://api.jquery.com/prev/
http://api.jquery.com/next/
So
$(this).siblings("input[name='price']").val(amount);
Edit
Here is the full working JS:
$("input[name=quantity]").each(function(){
$(this).bind("change keyup", function(){
var $thi,q,$p,p;
$thi = $(this);
q = $thi.val();
$p = $(this).siblings("input[name='price']");
p = parseFloat($p.val()).toFixed(2);
$p.val(q * p);
});
});
for clarity I've just add a total field
You can solve it with this code :
$("input[name=quantity], input[name=price]")
.each( function(){ $(this).on( {'keyup': function(){ var j0=$(this).nextAll("input[name=total]"); j0.val( j0.prevAll("input[name=quantity]").val() * j0.prevAll("input[name=price]").val() ) } } ) } );
Click here to see the working "Fiddle"
I have a problem, and I can't seem to work out how to solve it. I have two checkboxes, both of them have a value of 5. I just need to add the value of 5 to a variable when a checkbox is checked, and deduct 5, when it is unchecked. I've been using jQuery, but so far I've only managed to add 5 and it adds 10, when both of them are checked. It doesn't deduct anything as of now. Since I have a some radio buttons which I properly check, the code I have is this.
$(":checked").each(function(){
if ($(this).attr("type") == "checkbox"){
pricediff += 5;
}
}
as the function each is used, it adds 10 when both of them are checked. This, of course, is not wanted. And it still has to deduct 5 when the checkbox is unchecked. I have no idea how to do that - I'm a bit of a noob to jQuery and JavaScript. Can anyone assist me? Thanks
P.S. this is not the exact code but just the jist of it.
#rahul has a good answer, but this implies all checkboxes must have a value of 5.
Try this demo: http://jsfiddle.net/2WJZ4/
HTML:
<input type="checkbox" class="test" value="5" />
<input type="checkbox" class="test" value="7" />
<input type="checkbox" class="test" value="2" />
<input type="checkbox" class="test" value="1" /><br />
<span id="result">0</span>
Script:
$(function(){
$("input.test").change(function(){
var $this = $(this);
var value = $this.val();
var checked = $this.is(":checked");
if (checked) value = -value;
var $r = $('#result');
$r.text( (+$r.text()) - value)
});
});
PS. #rahul Awesome fiddle page!!!
Sample HTML
<input type="checkbox" class="test" />
<input type="checkbox" class="test" />
<input type="checkbox" class="test" />
<input type="checkbox" class="test" /><br />
<span id="result">0</span>
Script
$(function(){
$("input:checkbox.test").click(function(){
var checked = $("input:checkbox.test:checked").length;
var checkedValue = checked * 5;
$("#result").text(checkedValue)
});
});
See a working demo
try something like this
var placediff;
function calc()
{
var n = $("input:checked").length;
pricediff = n*5;
}
$(":checkbox").click(calc);