Repeative values occur in Autocomplete jquery - javascript

I am working in ASP.NET Project.My task is to Prevent the repative values occured in Textbox.Textbox is bound with autocomplete and appending text from checkboxlist as like in the below picture
! https://drive.google.com/file/d/0B5OPwgmPG6QpTHBTdVlFaldRaEE/view?usp=sharing
After i appended the content from checkbox list to textbox means it is repeating value,if i typed it inital time it won't.And my task is to show unique values based on the textbox content.
My project files are in the below link..please help me out guys
https://drive.google.com/file/d/0B5OPwgmPG6QpS3NMNElGN2k4RzQ/view?usp=sharing

Based on my answer I gave you in the other thread (https://stackoverflow.com/a/28828842/4569271) I extended my solution to only display unique values:
$(function() {
$('input[type="checkbox"]').change(function() {
// Reset output:
$("#output").html('');
// remeber all unique values in this array:
var tmpArray = new Array();
// Repeat for all checked checkboxes:
var checkboxes = $('input[type="checkbox"]:checked').each(function() {
// Get value from checkbox:
var textToAppend = $(this).val();
// Check if value from checkbox was added already:
if (jQuery.inArray(textToAppend, tmpArray) == -1) {
// add entry to array so it will be not added again:
tmpArray.push(textToAppend);
var existingText = $("#output").html();
// Append seperator (';') if neccessary:
if (existingText != '') {
existingText = existingText + ";";
}
// Print out append value:
$("#output").html(existingText + textToAppend);
}
});
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<h2>Select:</h2>
<input type="checkbox" value="Jan" />Jan
<input type="checkbox" value="Jan" />Jan
<input type="checkbox" value="Jan" />Jan
<input type="checkbox" value="Feb" />Feb
<input type="checkbox" value="Feb" />Feb
<input type="checkbox" value="Feb" />Feb
<input type="checkbox" value="Mar" />Mar
<input type="checkbox" value="Mar" />Mar
<input type="checkbox" value="Mar" />Mar
<h2>Output:</h2>
<div id="output"></div>
Based on your description, I am not sure if this is the solution you were looking for? But maybe it helps.

Related

jquery value from checkbox in loop not posting

I have a checkbox with the same name and id but different value.
I trying to get the value when I click on the checkbox in order to pass it to a ajax request. What ever I try I get the same result it only returns the first value in the list (it is actually in a php loop)
function checkCheckboxState() {
if ($('.displayme').is(':checked')) {
//tried all of these...
//var id = $('.displayme').first().attr( "value" );
//var id = $('.displayme').val();
//var id = $(this).val();
alert(id);
}
var id = $(":checkbox[name='displayme']:checked").val();
}
<input type="checkbox" name="displayme" value="27" id="displayme" class="displayme" onclick="checkCheckboxState()">
<input type="checkbox" name="displayme" value="28" id="displayme" class="displayme" onclick="checkCheckboxState()">
<input type="checkbox" name="displayme" value="29" id="displayme" class="displayme" onclick="checkCheckboxState()">
You shouldn't have the same id used several times on the same page.
You can bind an event on the change of the checkbox and then get the value with this :
$("checkbox.displayme").on("change",function(){
var checker = $(this).is(':checked');
//your ajax code here
});
And if your checkbox are generated on a php loop, you can use the index of the loop to generate different id (but with the code above you don't need any id).
Your first problem is that you have multiple elements with the same id. They need to be unique. In this case you could even remove them as you have the common class names to identify the elements.
To solve your actual problem you need to get a reference to the clicked checkbox within the event handler. As you're already using jQuery, you could do that using the change event handler. Try this:
$(function() {
$('.displayme').change(function() {
if (this.checked)
console.log(this.value);
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="checkbox" name="displayme" value="27" class="displayme">
<input type="checkbox" name="displayme" value="28" class="displayme">
<input type="checkbox" name="displayme" value="29" class="displayme">
Alternatively you can use map() to build an array of all the selected checkboxes which can then be passed in a single AJAX request:
$(function() {
$('.displayme').change(function() {
var values = $('.displayme:checked').map(function() {
return this.value;
}).get()
console.log(values);
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="checkbox" name="displayme" value="27" class="displayme">
<input type="checkbox" name="displayme" value="28" class="displayme">
<input type="checkbox" name="displayme" value="29" class="displayme">

Insert checkboxes values(name) into input with jQuery

I'm working with Symfony and I have a lot of checkboxes with different id and value, so when I check one, i want to automatically insert its value (name) into an input and when I check other insert its value in the same input:
<input type="checkbox" name="{{ent.username}}" value="{{ent.username}}">
Thanks everyone
That does not depend on Symphony.
jQuery:
$(function() { // when page loads
$("input[type='checkbox']").on("click",function() {
if (this.checked) $("#somefield").val(this.value);
});
});
Plain JS:
window.onload=function() { // when page loads
document.querySelectorAll("input[type='checkbox']").forEach(function() {
this.onclick=function() {
if (this.checked) document.getElementById("somefield").value=this.value;
}
}
}
Steps to follow:
Add change listener on each input field of checkbox type.
Get all the selected fruit by iterating each checkbox.
Set the value of selected fruits in the field.
Running sample code:
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div>
<input type="checkbox" value="Banana">Banana</input>
<input type="checkbox" value="Apple">Apple</input>
<input type="checkbox" value="Mangeo">Mango</input>
<input type="checkbox" value="Orange">Orange</input>
</div>
<div>
Selected Fruit : <input type="text" id="fruit">
</div>
<script>
var fruit = $('#fruit');
$('input[type="checkbox"]').change(function(e){
fruit.val(getSelectedFruits());
});
function getSelectedFruits(){
var fruits = "";
$('input[type="checkbox"]').each(function(i,cb){
if($(this).is(":checked")){
fruits += $(this).val() + " ";
}
});
return fruits;
}
</script>

How to show jquery dialog with radio buttons when checkbox is checked and post value in textbox

I have 41 checkboxes like this
HTML
<input id="1" type="checkbox" onclick="updatebox()" />
<input id="2" type="checkbox" onclick="updatebox()" />
<input id="3" type="checkbox" onclick="updatebox()" />
<input id="4" type="checkbox" onclick="updatebox()" />
Javascript
<script type="text/javascript">
function updatebox()
{
var textbox = document.getElementById("list");
var values = [];
if(document.getElementById('1').checked) {values.push("1");}
if(document.getElementById('2').checked) {values.push("2");}
if(document.getElementById('3').checked) {values.push("3");}
if(document.getElementById('4').checked) {values.push("4");}
textbox.value = values.join(", ");
}
</script>
When checkbox is checked the value is posted in textbox,
now what i want is when the user clicks the checkbox the jquery dialog popups and the user will have two radio buttons with Male or Female options along with ok button so when the user will click on ok the value should be posted on textbox depending on selection M for male F for female along with number like 1M or 1F, 2M or 2F and so on.
P.S user can select multiple checkboxes.
Thanks You!
Here is something that does what you want. HTML:
<body>
<form id="form">
<input id="1" type="checkbox" /> 1
<input id="2" type="checkbox" /> 2
<input id="3" type="checkbox" /> 3
<input id="4" type="checkbox" /> 4
...
<input id="10" type="checkbox" /> 10
...
<input id="41" type="checkbox" /> 41
<input id="list" />
</form>
<div id="prompt" style="display:none;" title="Gender">
<form>
<input type="radio" name="gender" id="radio" value="male" />
<label for="radio">Male</label>
<input type="radio" name="gender" id="radio2" value="female" />
<label for="radio2">Female</label>
</form>
</div>
</body>
The JavaScript:
$(function() {
var form = document.getElementById("form");
var textbox = document.getElementById("list");
var $prompt = $("#prompt");
// We record what is currently checked, and the user's answers in this `pairs` object.
var pairs = [];
// Listen to `change` events.
$("input[type='checkbox']", form).on('change', function (ev) {
var check = ev.target;
if (check.checked) {
// Checked, so prompt and record.
$prompt.dialog({
modal: true,
buttons: {
"Ok": function() {
var gender = $prompt.find("input[name='gender']:checked")[0];
var letter = {"male":"M", "female":"F"}[gender.value];
pairs[check.id] = '' + check.id + letter;
$( this ).dialog( "close" );
refresh();
}
}
});
}
else {
// Unchecked, so forget it.
delete pairs[check.id];
refresh();
}
function refresh() {
// Generate what we must now display in the textbox and refresh it.
// We walk the list.
var keys = Object.keys(pairs);
var values = [];
for (var i = 0, key; (key = keys[i]); ++i) {
values.push(pairs[key]);
}
textbox.value = values.join(", ");
}
});
});
Here is a jsbin with the code above.
Salient points:
This code adds the event handlers using JavaScript rather than use onclick in the HTML. It is not recommended to associated handlers directly in the HTML.
It listens to the change event rather than click. Some clicks can sometimes not result in a change to an input element.
It uses $.dialog to prompt the user for M, F.
The refresh function is what recomputes the text field.
It keeps a record of what is currently checked rather than requery for all the check boxes when one of them changes.
function updatebox()
{
var textbox = document.getElementById("list");
var values = [];
for (var i = 1; i <= 41; ++i) {
var id = '' + i;
if (document.getElementById(id).checked) {
var gender = prompt('Male (M) or female (F)?');
values.push(gender + id);
}
}
textbox.value = values.join(", ");
}
A few things to note:
I got rid of all that code repetition by simply using a for loop from 1 to 41.
I also fixed the strange indentation you had there.
You may want to use a method of getting user input other than prompt, but it'll work the same way.
(If you're going to keep using prompt, you might also want to add input validation as well to make sure the user didn't input something other than M or F.)

How to get all the selected checkboxes after they got unchecked

Let's start from the beginning...
I have checkboxes in the table and they have unique VALUES.
For example:
<input type="checkbox" value="2">
<input type="checkbox" value="3">
I want to have an array which will add and remove all the checkboxes in the list depending if they were checked or unchecked by the user (only click event) because in some point I'm resetting all of the checkboxes and I only want to save values when user clicks on it.
I have tried this so far but my code is not doing what I need, because this is giving me a double values when user checks and unchecks twice or more...
var selected = new Array();
$('tr td input:checked').each(function() {
selected.push($(this).attr('value'));
console.log(selected);
});
Do I need to use change event to track user behavior?
You have to update array on checked changed of the checkboxex, Assign common class to checkbox to make select simply and selectively.
HTML
<input type="checkbox" value="2" class="chk" />
<input type="checkbox" value="3" class="chk" />
Javascript
var selected;
$('.chk').change(function(){
selected = new Array();
$('tr td input:checked').each(function() {
selected.push($(this).attr('value'));
console.log(selected);
});
You can use the click() handler for this
var selected = new Array();
$(':checkbox').click(function(){
selected.splice(0, selected.length); // emptying last array so to avoid multiple values
$('tr td input:checked').each(function() {
selected.push($(this).attr('value'));
console.log(selected);
});
});
You can do like this also, this will remove elements from array by unchecking checkboxes..
var selected = new Array();
$('input:checkbox').change(function() {
if(this.checked)
selected.push($(this).attr('value'));
else
selected.splice(selected.indexOf(this.value),1);
console.log(selected);
});
Fiddle
I'm sure there is a better way to do this but here's some code a threw together real quick that should work for you.
<html>
<head>
<script>
var chkArray = [];
function addCheckBox() {
var chk1 = document.getElementById('1').checked;
var chk2 = document.getElementById('2').checked;
var chk3 = document.getElementById('3').checked;
var chk4 = document.getElementById('4').checked;
if(chk1 == true && chkArray.indexOf(1) == -1) {
chkArray.push(1);
alert('Added 1');
}else if(chk2 == true && chkArray.indexOf(2) == -1) {
chkArray.push(2);
alert('Added 2');
}else if(chk3 == true && chkArray.indexOf(3) == -1) {
chkArray.push(3);
alert('Added 3');
}else if(chk4 == true && chkArray.indexOf(4) == -1) {
chkArray.push(4);
alert('Added 4');
}
}
</script>
</head>
<body onClick="addCheckBox();">
<input type="checkbox" value="2" id="1">
<input type="checkbox" value="3" id="2">
<input type="checkbox" value="4" id="3">
<input type="checkbox" value="5" id="4">
</body>
</html>
You could try this:
HTML:
<input type="checkbox" name="test[]" value="1"/>
<input type="checkbox" name="test[]" value="2"/>
<input type="checkbox" name="test[]" value="3"/>
JS:
var recorder = [];
$('input[type="checkbox"]').change(function(){
var checkboxs = document.getElementsByName("test[]");
recorder=new Array();
for(var i=0;i<checkboxs.length;i++){
if(checkboxs[i].checked){
recorder.push(checkboxs[i].value);
}
}
console.log(recorder);
});
And JSfiddle DEMO
Hope this is helpful for you.

jQuery Store Values of checkboxes in div

How can I get this list of checkboxes to be added to a div prior to their selected state, so if they are selected, they should be added to the div, if not they are removed from the list if not selected.
<div id="selected-people"></div>
<input type="checkbox" value="45" id="Jamie" />
<input type="checkbox" value="46" id="Ethan" />
<input type="checkbox" value="47" id="James" />
<input type="checkbox" value="48" id="Jamie" />
<input type="checkbox" value="49" id="Darren" />
<input type="checkbox" value="50" id="Danny" />
<input type="checkbox" value="51" id="Charles" />
<input type="checkbox" value="52" id="Charlotte" />
<input type="checkbox" value="53" id="Natasha" />
Is it possible to extract the id name as the stored value, so the id value will be added to the div instead of the value - the value needs to have the number so that it gets added to a database for later use.
I looked on here, there is one with checkboxes and a textarea, I changed some parts around, doesn't even work.
function storeuser()
{
var users = [];
$('input[type=checkbox]:checked').each(function()
{
users.push($(this).val());
});
$('#selected-people').html(users)
}
$(function()
{
$('input[type=checkbox]').click(storeuser);
storeuser();
});
So you want to keep the DIV updated whenever a checkbox is clicked? That sound right?
http://jsfiddle.net/HBXvy/
var $checkboxes;
function storeuser() {
var users = $checkboxes.map(function() {
if(this.checked) return this.id;
}).get().join(',');
$('#selected-people').html(users);
}
$(function() {
$checkboxes = $('input:checkbox').change(storeuser);
});​
Supposing you only have these input controls on page I can write following code.
$.each($('input'), function(index, value) {
$('selected-people').append($(value).attr('id'));
});
Edited Due to More Description
$(document).ready(function() {
$.each($('input'), function(index, value) {
$(value).bind('click', function() {
$('selected-people').append($(value).attr('id'));
});
});
});
Note: I am binding each element's click event to a function. If that doesn't work or it isn't a good for what you are supposed to do then change it to on "change" event.
Change:
users.push($(this).val());
to:
users.push($(this).attr('id'));
This is for to bind the comma seperated values to input checkbox list
$(".chkboxes").val("1,2,3,4,5,6".split(','));
it will bind checkboxes according to given string value in comma seperated.

Categories