I've dynamically loading check box fields, how can I send those to server based on user selection.
For example I've following doc,
<label>Set1</label>
<input type="checkbox" name="set_199[]" value="Apple" />
<input type="checkbox" name="set_199[]" value="Mango" />
<input type="checkbox" name="set_199[]" value="Grape" />
<label>Set2</label>
<input type="checkbox" name="set_200[]" value="Red" />
<input type="checkbox" name="set_200[]" value="Blue" />
<input type="checkbox" name="set_200[]" value="Orange" />
Suppose if user selected first two values for each of them, then I need to send like
response[0][0]=199; // Id
response[0][1]=['Apple','Mango']; //values
response[1][0]=200
response[1][1]=['Red','Blue'];
I've tried some approaches suggested in existing posts but failed to implement how I want.
You can make some minor changes in the html then use .map()
<label class="set" data-id="199">Set1</label>
<input type="checkbox" name="set_199[]" value="Apple" />
<input type="checkbox" name="set_199[]" value="Mango" />
<input type="checkbox" name="set_199[]" value="Grape" />
<label class="set" data-id="200">Set2</label>
<input type="checkbox" name="set_200[]" value="Red" />
<input type="checkbox" name="set_200[]" value="Blue" />
<input type="checkbox" name="set_200[]" value="Orange" />
then
var array = $('.set').map(function () {
var $this = $(this),
id = $this.data('id'),
array = [id];
array.push($('input[name="set_' + id + '\\[\\]"]').filter(':checked').map(function () {
return this.value;
}).get())
return [array]
}).get()
Demo: Fiddle
Yet another solution:
<lable>Set1</lable>
<input type="checkbox" name="set_199[]" value="Apple" />
<input type="checkbox" name="set_199[]" value="Mango" />
<input type="checkbox" name="set_199[]" value="Grape" />
<input type="button" value="check" class="js-submit">
Js:
$(".js-submit").on("click", function(){
var a = $("input[type='checkbox']:checked");
var values = {};
a.each(function(){
var value = $(this).val();
var name = $(this).attr("name");
if(!values[name]) values[name] = [];
values[name].push(value)
});
console.log(values)
});
Demo
To expand on my comment a little, here's how I'd do this... given that you're sending this as an ajax request, I'd still wrap these elements in a form element, and use that as a starting-point to build the object we'll be sending...
var myForm = document.getElementById('formID').elements,//get all input nodes
data = {},temp;
for (var i=0;i<myForm.length;++i)
{
temp = myForm.item(i).name.replace(/[[]]/g,'');//replace square brackets
if (!data[temp])
data[temp] = [];//create array if key does not exist
if (myForm.item(i).checked)//for checkboxes
data[temp].push(myForm.item(i).value);
}
That's the basic setup. If you want, you can add checks and further tailor this, so you can deal with various types of input fields, but in essence, it'll boil down to this.
You might also want to use Array.prototype.forEach on the myForm.elements NodeList, and use a callback to keep your code nice and clean.
Here's an example of a slightly more usable version of the same code:
btn.addEventListener('click', function()
{
var data = {};
Array.prototype.forEach.call(frm.elements, function(item)
{
var temp;
if (item === btn) return;//don't includ the button element
if (item.type === 'checkbox' && !item.checked ) return;//not checked, ignore
if (item.name.match(/[[]]/))
{
temp = item.name.replace(/[[]]/g, '');
if (!data[temp]) data[temp] = [];//if property does not exist, make an array
data[temp].push(item.value);
return;
}
//normal elements:
data[item.name] = item.value;
});
//ajax request using data variable goes here!
console.log(data);
},false);
And here's the fiddle of it
First of all thanks for all who have given answers to this question. I've derived my own solution for this issue but it is not possible without your help, especially this
var checkBoxArray = {};
$.each($("input[name^='set_'][type='checkbox']:checked"), function(i, item) {
var Id = item.name.replace(/^(set_)|[\[\]]/g, "");
var value = $(item).val();
if(!checkBoxArray[Id])
checkBoxArray[Id] = [];
checkBoxArray[Id].push(value)
});
$.map(checkBoxArray, function(value, index) {
reponse.push([index, value]);
});
Its worked for me, suggest if anything not proper in above code snippet.
Related
What I'm trying to achieve is this:
Default state of page = no checkboxes ticked, no link shown
User ticks one (or more) checkboxes
Link appears, dynamically generated from the checkbox values, in the following format: http://example.com/?subject=Products&checked=Blue,Green,Purple (where the selected checkbox values are "Blue", "Green" and "Purple")
Thus far, based on advice from another question (Using JavaScript to load checkbox Values into a string), I've been able to get the values in the proper format (as part of the required url) printed to console.log via a button:
$("button").on("click", function(){
var arr = []
$(":checkbox").each(function(){
if($(this).is(":checked")){
arr.push($(this).val())
}
})
var vals = arr.join(",")
var str = "http://example.com/?subject=Products&" + vals
console.log(str)
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.3/jquery.min.js"></script>
<input type="checkbox" id="selected" name="selected" value="Blue" class="products"> Blue<br>
<input type="checkbox" id="selected" name="selected" value="Green" class="products"> Green<br>
<input type="checkbox" id="selected" name="selected" value="Purple" class="products"> Purple
<br>
<button>button</button>
However, they're not loading dynamically based on the selected checkboxes (it requires you to press the button in order to generate the url) and the link hasn't been printed to the page for use by visitors (it's stuck in console.log, visible but not usable).
I've been advised that .change() might be the way to go here, in terms of generating the link dynamically. Something like: jQuery checkbox change and click event.
How can I merge the two approaches to achieve the result I'm looking for?
This would work to give you a url of
http://example.com/?subject=Products&checked=Blue,Green,Purple
(see below for a possibly better way):
$(document).on("change", ".mod-link", function() {
var arr = []
$(".mod-link:checked").each(function() {
arr.push($(this).val());
})
var vals = arr.join(",")
var str = "http://example.com/?subject=Products&checked=" + vals;
var link = arr.length > 0 ? 'Click me': '' ;
$('.link-container').html(link);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="checkbox" class="mod-link" name="selected" value="Blue" class="products">Blue
<br>
<input type="checkbox" class="mod-link" name="selected" value="Green" class="products">Green
<br>
<input type="checkbox" class="mod-link" name="selected" value="Purple" class="products">Purple
<br>
<div class="link-container"></div>
However
I would do it a bit different.
I would opt for the following url structure:
http://example.com/?subject=Products&checked[]=Blue&checked[]=Green&checked[]=Purple
When that is recieved by PHP, checked will be an array like ['Blue','Green','Purple'] instead of a string like 'Blue,Green,Purple'
$(document).on("change", ".mod-link", function() {
var arr = []
$(".mod-link:checked").each(function() {
arr.push($(this).val());
})
var vals = 'checked[]=' + arr.join("&checked[]=")
var str = "http://example.com/?subject=Products&" + vals;
var link = arr.length > 0 ? 'Click me': '' ;
$('.link-container').html(link);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="checkbox" class="mod-link" name="selected" value="Blue" class="products">Blue
<br>
<input type="checkbox" class="mod-link" name="selected" value="Green" class="products">Green
<br>
<input type="checkbox" class="mod-link" name="selected" value="Purple" class="products">Purple
<br>
<div class="link-container"></div>
I believe that you were on the right track, if I understood your question correctly. I added the change event on you checkboxes as you suggested. Try the modified code below.
HTML
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.3/jquery.min.js"></script>
<input type="checkbox" name="selected" value="Blue" class="products"> Blue<br>
<input type="checkbox" name="selected" value="Green" class="products"> Green<br>
<input type="checkbox" name="selected" value="Purple" class="products"> Purple
<br>
<span class="link"></span>
JavaScript
$("input[type=checkbox]").on("change", function(){
var arr = []
$(":checkbox").each(function(){
if($(this).is(":checked")){
arr.push($(this).val())
}
})
var vals = arr.join(",")
var str = "http://example.com/?subject=Products&checked=" + vals
console.log(str);
if (vals.length > 0) {
$('.link').html($('<a>', {
href: str,
text: str
}));
} else {
$('.link').html('');
}
})
Working CodePen
Your button is no longer being used. Is this what you were looking for?
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.
I have the following series of checkboxes coming from the datatables in the form like below:
<input id="list-chk_1" type="checkbox" />
<input id="list-chk_2" type="checkbox" />
<input id="list-chk_3" type="checkbox" />
How can I separate that id from list-chk. Do I have to include data-id parameter?
As per my understanding, Try that
$('input[id^="list-chk"]').click(function(){
$(this).attr("id"); //Getting click control ID
$(this).val(); //Getting Value
});
You can use split if you know the ID always has that format.
var ins = document.getElementsByTagName('input');
for (var i = 0; i < ins.length; i++) {
document.write(ins[i].id.split('_')[1]);
}
// jQuery
$('input').each(function() {
$('body').append(this.id.split('_')[1]);
});
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<input id="list-chk_1" type="checkbox" />
<input id="list-chk_2" type="checkbox" />
<input id="list-chk_3" type="checkbox" />
Split will make an array from the given string, splitting it where you tell it to.
"list-chk_1".split('_') // results in ["list-chk", "1"]
Other methods could be using var idnr = this.id.replace('list-chk_', '');
I have a simple web form that uses JavaScript for building a POST statement. In Chrome, I can use a simple line of code...
var form = document.forms['myForm'];
var env = form.env.value;
The form itself looks like this...
<form name="myForm" action='JavaScript:xmlhttpPost("/path/to/some/pythoncode.py")'>
<input type="radio" name="env" id="env" value="inside">Inside
<input type="radio" name="env" id="env" value="outside" checked="checked">Outside
<input type="radio" name="env" id="env" value="both">Both
<input type="radio" name="env" id="env" value="neither">Neither
I have some text boxes on the form that I can use the same technique to find the value (
var name = form.fname.value
with a
<input type="text" name="fname" id="fname">
However, when I submit the form and build my post, the value for the radio buttons is always undefined. It works fine in Chrome, but nothing in IE or FireFox.
I tried var env = document.getElementById('env').value, but for some reason that always defaults to the first value (inside) no matter what I select. That method also does not return a value when using Chrome.
Is there something I'm missing for reading the checked value of a radio input in FF or IE?
Try this
function getValueFromRadioButton(name) {
//Get all elements with the name
var buttons = document.getElementsByName(name);
for(var i = 0; i < buttons.length; i++) {
//Check if button is checked
var button = buttons[i];
if(button.checked) {
//Return value
return button.value;
}
}
//No radio button is selected.
return null;
}
IDs are unique so you should not use the same ID for multiple items. You can remove the all the radio button IDs if you use this function.
You are using the same ID for multiple Elements, ID is unique for element on the page.
use different IDs.
edit: names can be the same. because then the radio buttons are as a group.
As stated, the IDs should be different to be valid, but you could accomplish this by eliminating the IDs all together and using just the input name:
var form = document.forms['myForm'];
var radios = form.elements["env"];
var env = null;
for(var i=0;i<radios.length;i++) {
if(radios[i].checked == true) {
env = radios[i].value;
}
}
<form name="myForm">
<input type="radio" name="env" value="inside">Inside
<input type="radio" name="env" ivalue="outside" checked="checked">Outside
<input type="radio" name="env" value="both">Both
<input type="radio" name="env" value="neither">Neither
</form>
Short & clear on ES-2015, for use with Babel:
function getValueFromRadioButton( name ){
return [...document.getElementsByName(name)]
.reduce( (rez, btn) => (btn.checked ? btn.value : rez), null)
}
console.log( getValueFromRadioButton('payment') );
<div>
<input type="radio" name="payment" value="offline">
<input type="radio" name="payment" value="online">
<input type="radio" name="payment" value="part" checked>
<input type="radio" name="payment" value="free">
</div>
You can try this:
var form = document.querySelector('form#myForm');
var env_value = form.querySelector('[name="env"]:checked').value;
Ok so I do this:
<input type="checkbox" class="checkBoxClass" value="0" />
<input type="checkbox" class="checkBoxClass" value="1" />
<input type="checkbox" class="checkBoxClass" value="2" />
Then in javascript/jquery I'm trying to do something like this:
$('#btnHtml').click(function(){
for( var checks=''; $('.checkBoxClass:checked').val() ){
var checks = checks+', ';
}
});
Let's say all of those checkboxes are checked, how can I get var checks to be a string of '0, 1, 2' ?
Still trying to get used to the for() in JS, it might be the completely wrong way of going about it. Not sure how to do this.
Functional programming:
var str = $('.checkBoxClass:checked').map(function() {
return this.value;
}).get().join();
Reference: .map, .get, .join