Check Box Values to List Jquery - javascript

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);
})

Related

Iterating over dynamically generated input field ids and using keyup to get their values in a separate input field

The mandatory div id gets different numbers of inputs field displayed in it dynamically. Each input field starting from the first gets an id attr1, then attr2,..attr[n]. I need a way to get this into an array that gets the value of each input field with keyup and puts them into a separate input field with id detail.
This code works but returns undefined in some case when the hard coded input field ids exceed the generated input field ids. Thanks.
<div id="attributes"> <!--Start of Div Refreshed on Ajax Page Refresh-->
<div id="mandatory">
</div>
</div>
var total = '#attr1, #attr2';
$("#attributes").on('keyup', total, function(){
update();
})
function update() {
$("#detail").val($('#attr1').val() + "," $('#attr2').val());
}
If I understood right your question I think you're looking for something like that:
var fields = $("#mandatory").find("input"),
ids = [];
fields.each(function(){
$(this).on("keyup", function(){
var val = "";
ids = [];
fields.each(function(){
val += $(this).val() + (fields.length === ($(this).index() + 1) ? "": ", ");
ids.push($(this).get(0).id);
});
$("#detail").val(val);
console.log(ids)
});
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="attributes">
<div id="mandatory">
<input id="one" class="one" value="54"/>
<input id="two" class="two" value="55"/>
<input id="three" class="three" value="587"/>
</div>
</div>
<input id="detail" type="text" />
I'm not sure if this is what you're looking for, but I think it'll take you down the right path. In this example, any time a text input field is generated, an input event handler is attached to it that changes the value of a main textarea. If this isn't quite what you're looking for, please let me know and I'll be happy to try to work it out more.
document.getElementById('adder').onclick = function() {
var dynamicTextbox = document.createElement('input');
dynamicTextbox.setAttribute('type', 'text');
dynamicTextbox.setAttribute('class', 'dynamicText');
dynamicTextbox.addEventListener("input", function() {
var allTextboxes = document.getElementsByClassName('dynamicText');
var allValues = '';
for (var i=0; i < allTextboxes.length; i++) {
allValues += allTextboxes[i].value;
}
document.getElementById('detail').value = allValues;
});
document.getElementById('textboxes').appendChild(dynamicTextbox);
}
<textarea id="detail"></textarea>
<input id="adder" type="button" value="Add Text Field" />
<div id="textboxes"></div>

Adding/Removing Search filters dynamically with jQuery

I'm currently trying to build a post filter section into a website and need some help with the JavaScript/jQuery that goes along with it. Below you can see an example of the layout visually and the html layout.
The sequence of events will go as follows:
User selects from the top list of filters (bottom tags are not visible until selected)
Once selected the "selected tag filter disappears from the top list and is added to the bottom ("circular tags")".
the user can also delete the tags and they will return to the top list of filters.
The way I imagined this working:
Selecting a filter
check for "checked checkbox"
add selected "checkbox" label + value attribute to an array
get the last values added to the array and create new filter tag underneath under content tag container
Removing a Filter
user clicks the small x on the tag they wish to remove
the tag is removed added back to the top list of filters and removed from the array
<div class="blog-feed-filters">
<h5>FILTER</h5>
<div class="checkbox">
<input class="checkbox-active" id="check1" type="checkbox" name="filter" value="1">
<label for="check1">Turas Application Updates</label>
<br>
<input class="checkbox-active" id="check2" type="checkbox" name="filter" value="2">
<label for="check2">General News</label>
<br>
<input class="checkbox-active" id="check3" type="checkbox" name="filter" value="3">
<label for="check3">Organisation Updates</label>
<br>
<input class="checkbox-active" id="check4" type="checkbox" name="filter" value="4">
<label for="check4">UI Updates</label>
</div>
<hr />
<div id="content-tag-container">
<div class="content-tag">Update ✕</div>
<div class="content-tag">Mobile Applications ✕</div>
<div class="content-tag">New website update ✕</div>
<div class="content-tag">Update ✕</div>
</div>
</div>
JavaScript/ Jquery Please excuse the mess. I'm a noob:D
$('.checkbox-active').click(function () {
//check to see if the checkbox has been "checked"
if (document.getElementById('check1').checked) {
var filtersSelected = [];
//get the item that has been checked and add it to an array
$.each($("input[name='filter']:checked"), function () {
filtersSelected.push($(this).val() + $("label[for='checkbox-active']").innerText);
});
//find the last item in the array
if (!Array.prototype.last) {
Array.prototype.last = function () {
return this[this.length - 1];
};
};
//create a new filter tag and add it to the content-tag-container div
for (var c in filtersSelected.last()) {
var newElement = document.createElement('div');
newElement.className = "content-tag";
newElement.innerHTML = "<a href=''>" + "✕" + "</a>";
document.getElementById("content-tag-container").appendChild(newElement);
};
}
});
Any help is appreciated. Cheers
I made some changes in your javascript :
$(document).ready( function() {
$('.checkbox-active').click(
function() {
//console.log("Hi");
//check to see if the checkbox has been "checked"
var filtersSelected = [];
//console.log($("input[name='filter']:checked"));
//get the item that has been checked and add it to an array
var pushed=false;
$.each($("input[name='filter']:checked"), function() {
//console.log( );
filtersSelected.push($(this).val() + $("label[for='"+$(this).attr('id')+"']").text());
$("label[for='"+$(this).attr('id')+"']").remove();
$(this).remove();
pushed=true;
});
console.log(filtersSelected);
//find the last item in the array
if (!Array.prototype.last) {
Array.prototype.last = function() {
return this[this.length - 1];
};
}
;
//create a new filter tag and add it to the content-tag-container div
if(pushed){
var c = filtersSelected.last();
var newElement = document.createElement('div');
newElement.className = "content-tag";
newElement.innerHTML = c + "<a href=''>" + "X" + "</a>";
document.getElementById("content-tag-container")
.appendChild(newElement);
}
});
});
Above code is partially running to add checked values in filtered list.
Replace your javascript with above code.

Dynamically Update DIV information based on CHECKBOX input value

I am trying to have a list of input checkboxes (which will be generated by PHP at a later time) but for now the content is static. So based off of the input, be able to select an employee, populates my div based on the selection and when unchecking the input, remove that same employee. I also need to be able to select multiple employees, instead of just one. Currently it updates the div with an employee but I cannot remove said employee. I can also only select one employee at a time (need to be able to click as many employees as needed all at once).
Here is what I got:
HTML
<div id="employee-list">
</div>
<div class="small-2 columns bord-right3 check-box">
<input type="checkbox" class="boxid" value="Joe Smith" name="employees">
<label class="checkbox-select">Select</label>
</div>
<div class="small-10 columns bord-right3">
<span class="employee-name">Joe Smith</span>
</div>
<div class="small-2 columns bord-right3 check-box">
<input type="checkbox" class="boxid" value="John Smith" name="employees">
<label class="checkbox-select">Select</label>
</div>
<div class="small-10 columns bord-right3">
<span class="employee-name">John Smith</span>
</div>
JS
$('input[name="employees"]').change(function () {
var inputVal = $('input[name="employees"]:checked').map(function () {
return this.value;
}).get();
console.log(inputVal);
if ($(this).prop('checked')) { //which checkbox was checked
if ($(this).val() == inputVal ) {
$("#employee-list").append('<span class="employee-name2_1">X ' + inputVal + '</span>');
}
} else {
$('.li_'+$(this).val()).remove();
console.log('item removed');
}
});
Any help is greatly appreciated! Please let me know if I have missed anything.
If I understand the goal correctly some of your code inside the change listener was unnecessary. You don't have to use map to get the value of the checkbox, $(this).val() is sufficient. From there a single if/else can add or remove the information as necessary.
Fiddle
$('input[name="employees"]').change(function () {
var inputVal = $(this).val();
var className = inputVal.replace(/ /g, '_');
if ($(this).prop('checked')) { //which checkbox was checked
$("#employee-list").append('<span class="span_' + className + '">X ' + inputVal + '</span>');
} else {
$('.span_'+className).remove();
console.log('item removed');
}
});

Div Like search Using dat filter Property

I am trying to implement search using data-filter property of div.
Here one issue with this.I want to implement a like search.Currently it is looking exact match.Where i need to make change to make it a like search
<label for="search">Search Input:</label>
<input type="search" name="filter" id="search" value="" />
<div data-filter="vehicle1">vehicle1</div>
<div data-filter="vehicle2">vehicle2</div>
<div data-filter="vehicle3">vehicle3</div>
<div data-filter="vehicle4">vehicle4</div>
<div data-filter="vehicle5">vehicle5</div>
$(document).ready(function() {
$('#search').on('keyup', function() {
var val = $.trim(this.value);
if (val) {
$('div[data-filter]').hide();
$('div[data-filter=' + val + ']').show();
}
if(val.length == 0)
{
$('div[data-filter]').show();
}
});
});
Have a look here: CSS selectors, this is what jQuery's selectors are based on.
jQuery adds to that with the Attribute Contains Selector
Which in your case would work like this:
$('div[data-filter*="' + val + '"]').show();
Maybe this will work:
var $divs=$("div");
for(var i=0;i<$divs.length;i++){
console.log("div's data-filter",$divs[i]["data-filter"]);
console.log("value",val);
if($divs[i]["data-filter"]
&&($divs[i]["data-filter"].indexOf(val)!==-1)){
$($divs[i]).show();
}
}

javascript print array values dynamic

hi everyone i have a problem in javascript i can print array if fix them in html but whn i try to print them on clic they are not working just print the array names
if i print seriesre simple it print values that is fine but when i check any checkbox and want to print one or tow of them it just showing array name not values
thanks for help
check this example
$(document).ready(function() {
Comment = [['2011-01-29',7695],['2011-02-02',19805]];
WallPost = [['2011-01-29',11115],['2011-02-02',8680]];
Likes = [['2011-01-29',5405],['2011-02-02',10930]];
var seriesre= [Comment,WallPost,Likes];
var mygraphs = new Array();
alert(seriesre);
$("#testCheck").click(function() {
i=0;
$("#testCheck :checked").each(function() {
mygraphs[i]= $(this).val();
i++;
});
newseriesre = "["+mygraphs+"]";
alert(newseriesre);
});
});
<div class="activity">
<form method="POST" id="testCheck" name="myform">
Likes
<input type="checkbox" value="Likes" name="box2">
Comments
<input type="checkbox" value="Comment" name="box3">
Wall Post
<input type="checkbox" value="WallPost" name="box4">
</form>
</div>
You can use
alert(myarray.join())
to alert your array's values
You should use a associative array instead of an array, so that you can look up the data based on the name as a string instead of trying to find the variable. All objects in Javascript are associative arrays, so just put the data in an object.
Also:
Create the mygraphs array inside the event handler, otherwise it can not shrink when you uncheck options.
Catch the click on the checkboxes inside the form, not on the form itself.
Put a label tag around the checkbox and it's label, that way the label is also clickable.
You don't need an index variable to put values in the mygraphs array, just use the push method to add items to it.
http://jsfiddle.net/cCukJ/
Javascript:
$(function() {
Comment = [['2011-01-29',7695],['2011-02-02',19805]];
WallPost = [['2011-01-29',11115],['2011-02-02',8680]];
Likes = [['2011-01-29',5405],['2011-02-02',10930]];
var seriesre = {
'Comment': Comment,
'WallPost': WallPost,
'Likes': Likes
};
$("#testCheck :checkbox").click(function() {
var mygraphs = [];
$("#testCheck :checked").each(function() {
mygraphs.push(seriesre[$(this).val()]);
});
alert("["+mygraphs+"]");
});
});
HTML:
<div class="activity">
<form method="POST" id="testCheck" name="myform">
<label>
Likes
<input type="checkbox" value="Likes" name="box2">
</label>
<label>
Comments
<input type="checkbox" value="Comment" name="box3">
</label>
<label>
Wall Post
<input type="checkbox" value="WallPost" name="box4">
</label>
</form>
</div>
I understand that you want to alert the selected values when clicking anywhere on the form? If that's true correct code with minimal changes to your existing code will be:
var mygraphs = [];
$("#testCheck").click(function() {
$("#testCheck :checked").each(function() {
mygraphs.push($(this).val());
});
alert("Selected values are: " + mygraphs.join(", "));
});
You can try this.
alert($("#testCheck :checked")
.map( function(i, field) { return field.value}
).get());
Check your working example in http://jsfiddle.net/dharnishr/d37Gn/

Categories