How to pass values of selected checkboxes to the javascript function? - javascript

I need to pass values of selected check boxes to the javascript method but it does not detect the checkbox.
<form name="cat" method="POST" action="myaction">
<c:forEach items="${items}" var="item">
<input type="checkbox" id="pro" name="pro" value="${item.id}"/>
</c:forEach>
...
<input type="button" value="getItem" onclick="getItem(this.form)"/>
</form>
Javascript
function getItem(frm) {
alert("size:" + frm.pro.length); <<< it returns size:unidentified
var values = "";
for (var i = 0; i < frm.pro.length; i++)
{
if (frm.pro[i].checked)
{
values = frm.pro[i].value + ",";
}
}
alert(values); << it is empty
....
//pass values to the back-end

I think your approach is old fashioned. Here's a jQuery version.
NOTE: you are adding multiple id="pro" and this is just wrong remove it
First add id="form" to your form
Here you can find a fiddle. :D
http://jsfiddle.net/SXffG/3/
HTML:
<form id="form" name="cat" method="POST" action="myaction">
<input type="checkbox" name="pro" value="1"/>
<input type="checkbox" name="pro" value="2"/>
<input type="checkbox" name="pro" value="3"/>
<input type="checkbox" name="pro" value="4"/>
<input type="checkbox" name="pro" value="5"/>
<input type="checkbox" name="pro" value="6"/>
<input type="button" class="getItem" value="getItem"/>
</form>
<div id="info">Click the button</div>
JavaScript
var allVals = [];
$(function() {
$('#form .getItem').click(function() {
allVals = []
$('#form :checked').each(function() {
allVals.push($(this).val());
});
//alert("Values " + allVals);
$.ajax({
type: "POST",
url: "http://localhost:8080/example/ajaxSubmit.action",
data: "allVals=" + allVals,
success: function(response){
$('#info').html("OK! Data [" + allVals + "] Sent with Response:" + response);
},
error: function(e){
$('#info').html("OH NOES! Data[" + allVals +"] Not sent with Error:" + e);
}
});
});
});

var check = document.getElementsByName("pro");
var textArray = [];
for(var c = 0; c < check.length;c++){
if(check[c].checked){
textArray .push(check[c].value);
}
}
textArray = textArray .join("~");
you will get the data as tilde separated. Hope this helps you.

Related

Multiple checkbox submit php form with 1 click

Is there a way to improve this? Can't find a way to improve..
var $submit = $('#submit-form');
$submit.off('click').on('click', function(e) {
e.preventDefault();
var checkedBOX = $('#checkboxes').find('input:checked');
var servers = [];
$.each(checkedBOX, function(k, v) {
var v = $(v);
servers.push(v.val());
v.prop("checked", false);
});
var doneCount = 0;
$.each(servers, function(key, server) {
$.ajax({
type: "POST",
url: window.location.href,
data: $('#form').serialize() + '&server=' + server + '&submit=',
success: function (data) {
doneCount++;
if (doneCount >= servers.length) {
window.location.reload();
}
}
})
});
});
Can't figure it out what is the best way to make it faster..
Could anyone help me out here?
try this way , remove loop
$(document).on('submit','#submit-form',function(e){
e.preventDefault();
var checkedBOX = $('#checkboxes').find('input:checked');
var servers = [];
$("input:checkbox[name=checkbox]:checked").each(function(){
servers.push($(this).val());
});
console.log(servers);
$.ajax({
type: "POST",
url: window.location.href,
data: $('#submit-form').serialize() + '&server=' + servers + '&submit=',
success:function(data){
window.location.reload();
}
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<form method="POST" id="submit-form">
<input type="text" name="name" placeholder="NAME"/>
<br/>
<input type="text" name="email" placeholder="EMAIL"/>
<br/>
<input type="checkbox" name="checkbox" value="1" />
<input type="checkbox" name="checkbox" value="2" />
<input type="checkbox" name="checkbox" value="3" />
<input type="checkbox" name="checkbox" value="4" />
<br/>
<button type="submit">SUBMIT</button>
</form>

How to determine if the input is of array type in javascript?

<input type="text" name="members[0].name">
<input type="text" name="members[0].address">
Javascript code :
var input_text;
var inputs=document.querySelectorAll("input[type=text],textarea, select");
_.each(inputs, function(e, i) {
var keyName = $(e).attr("name");
if (typeof keyName != "undefined") {
var text = $(e).parent().find('label').text();
if ($(e).is('select')) {
input_text = input_text + "<tr><td>" + text + "</td><td> " + $(e).find(':selected').text() + "</td></tr>";
}
else {
input_text = input_text + "<tr><td>" + text + "</td><td> " + $(e).val() + "</td></tr>";
}
}
});
console.log(input_text);
As You can see, I m getting the values of all the inputs in $(e).val() except those above mentioned inputs.
Those inputs aren't an "array" in the browser. They just use a naming convention in their name which is used by some server-side handling (for instance, in PHP) to organize the form data for you when it's submitted.
I don't know what you mean by "previewing," but you can see the values of those elements by simply looping through the elements of your form (yourForm.elements), or by using yourForm.querySelectorAll("input[type=text]") (or $(yourForm).find("input[type=text]") using jQuery — I missed the jquery tag on your question at first).
Example of theForm.elements:
document.querySelector("form input[type=button]").addEventListener("click", function() {
var form = document.getElementById("the-form");
Array.prototype.forEach.call(form.elements, function(element) {
if (element.type === "text") {
console.log(element.name + " = " + element.value);
}
});
});
<form id="the-form">
<input type="text" name="members[0].name" value="name 0">
<input type="text" name="members[0].address" value="address 0">
<input type="text" name="members[1].name" value="name 1">
<input type="text" name="members[1].address" value="address 1">
<input type="text" name="members[2].name" value="name 2">
<input type="text" name="members[2].address" value="address 2">
<div>
<input type="button" value="Show">
</div>
</form>
Example of theForm.querySelectorAll:
document.querySelector("form input[type=button]").addEventListener("click", function() {
var form = document.getElementById("the-form");
Array.prototype.forEach.call(form.querySelectorAll("input[type=text]"), function(element) {
console.log(element.name + " = " + element.value);
});
});
<form id="the-form">
<input type="text" name="members[0].name" value="name 0">
<input type="text" name="members[0].address" value="address 0">
<input type="text" name="members[1].name" value="name 1">
<input type="text" name="members[1].address" value="address 1">
<input type="text" name="members[2].name" value="name 2">
<input type="text" name="members[2].address" value="address 2">
<div>
<input type="button" value="Show">
</div>
</form>
Example of $(theForm).find:
$("form input[type=button]").on("click", function() {
var form = document.getElementById("the-form");
$(form).find("input[type=text]").each(function() {
console.log(this.name + " = " + this.value);
});
// Of course, we could have just used `$("#the-form input[type=text]").each`...
// but I was assuming you'd already have `form`
});
<form id="the-form">
<input type="text" name="members[0].name" value="name 0">
<input type="text" name="members[0].address" value="address 0">
<input type="text" name="members[1].name" value="name 1">
<input type="text" name="members[1].address" value="address 1">
<input type="text" name="members[2].name" value="name 2">
<input type="text" name="members[2].address" value="address 2">
<div>
<input type="button" value="Show">
</div>
</form>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
So many ways to get the input type values using formID
$('#formId input, #formId select').each(
function(index){
var input = $(this);
}
);
OR
var formElements = new Array();
$("form :input").each(function(){
formElements.push($(this));
});
OR
var $form_elements = $("#form_id").find(":input");
hope it helps you.
You can use serializeArray or serialize for it .
$("form").serializeArray();
The .serializeArray() method creates a JavaScript array of objects, ready to be encoded as a JSON string. Doc

Get checked values of checkbox list using jquery

I have a couple of checkbox with the name etapes. I'd like to get all the checked etapes's value and store it in a single string.
So tried this :
$('[name="etapes"]:checked').each(function() {
indexer = indexer + 1;
if (indexer == 1) selectedEtapes = $(this).val();
else selectedEtapes = selectedEtapes + "," + $(this).val();
});
but it didn't work. SO how can I fix this issue?
Easier solution is to use jQuery.map
var mapped = $('[name="etapes"]:checked').map(function() {
return this.value;
}).get();
console.log(mapped.join(','));
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
<input type="checkbox" name="etapes" value="Ouverte1" checked>
<input type="checkbox" name="etapes" value="Ouverte2">
<input type="checkbox" name="etapes" value="Ouverte3" checked>
Fix for your code:
You never accepted index argument,
var selectedEtapes = '';
$('[name="etapes"]:checked').each(function(index) {
if (!index) selectedEtapes += $(this).val();
else selectedEtapes += "," + $(this).val();
});
You can do it using map() method like following.
var str = $('[name="etapes"]:checked').map(function() {
return $(this).val();
}).get().join();
console.log(str)
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="checkbox" name="etapes" value="Ouverte1" checked="checked">
<input type="checkbox" name="etapes" value="Ouverte2">
<input type="checkbox" name="etapes" value="Ouverte3" checked="checked">
<input type="checkbox" name="etapes" value="Ouverte4" checked="checked">

Make a matrix with input inside a DIV by mixing input values

Take a look at this:
<div id="main">
<div id="a">
<input value="1" />
<input value="2" />
<input value="3" />
</div>
<div id="b">
<input value="4" />
<input value="5" />
</div>
</div>
I need to get each input value inside div#a and each input value in div#b and build a matrix/mixing of those values, taking the same example as before, this is what the code should return:
<div id="mixed">
<input value="1" /><input value="4" />
<input value="1" /><input value="5" />
<input value="2" /><input value="4" />
<input value="2" /><input value="5" />
<input value="3" /><input value="4" />
<input value="3" /><input value="5" />
</div>
I have tried to move inside div#main using this code:
$("#main div").each(function() {
var that = $(this);
console.log("that.attr('id')");
});
But console.log() never logs something so I must doing something wrong. This is a advanced topic for me and need some help, any?
UPDATE
At this point I have this maded:
$("#choices div").each(function() {
var that = $(this);
that.each(function() {
var thati = $(this);
console.log(thati);
});
});
And I think in the second .each() is where I can get the input values and try to build the matrix
Should help:
var arr = [];
$('#a input').each(function () {
var that = $(this);
$('#b input').each(function () {
arr.push(that.val());
arr.push($(this).val());
});
});
Then go through the array and dynamically generate the HTML. You can treat this like a matrix by stepping every 2 values.
var a = $('#a input');
var b = $('#b input');
var html = '';
a.each(function () {
var first = this;
b.each(function () {
html += '<div>' + first.outerHTML + this.outerHTML + '</div>'
});
});
$('#mix').html(html);
jsFiddle here
update: code for what's asked for in comments.
var divs = $('#main > div');
var html = '';
divs.each(function (index) {
var divsLength = divs.length,
inputs = $('input', divs[index]),
inputsLength = inputs.length;
for (var i = 0; i < divsLength; i++) {
if (i === index) {
continue;
}
for (var j = 0; j < inputsLength; j++) {
$('input', divs[i]).each(function () {
html += inputs[j].outerHTML + this.outerHTML + '<br />';
});
}
}
});
$('#mix').html(html);

return all values of input fields within div

I need to form a string with the all values input fields within a div layer - using jquery
<div id="selection">
<input class="field" id="1" type="hidden" value="A"/>
<input class="field" id="2" type="hidden" value="B"/>
<input class="field" id="3" type="hidden" value="C"/>
<input class="field" id="4" type="hidden" value="D"/>
</div>
<input type="button" id="button" value="generate"/>
in this form:
id[1]=val[A]&id[2]=val[b]...so on
jquery:
$(function() {
$('#button').click(function() {
//function goes here...
});
});
If you use name instead of (or in addition to) id:
<input class="field" name="1" type="hidden" value="A"/>
<input class="field" name="2" type="hidden" value="B"/>
<input class="field" name="3" type="hidden" value="C"/>
<input class="field" name="4" type="hidden" value="D"/>
you can use serialize:
$('#button').click(function() {
alert($('#selection input').serialize());
});
which gives you
1=A&2=B&3=C&4=D
If you really want to have the id[x] structure, you can give the elements the names id[1], id[2] etc.
Edit: Oh, somehow I overlooked that you want val[x] as well. This would not be possible with serialize, only if you really put val[x] as value in the fields. But why do you need such an obfuscated structure?
Btw. you are missing type="button" at your button.
<script>
$(function() {
$('#button').click(function() {
var str = new Array();
var count = 0;
$('.field').each(
function()
{
str[count] = 'id['+$(this).attr('id')+']=val['+$(this).val()+']';
count++;
}
);
alert(str.join('&'))
});
});
</script>
<div id="selection">
<input class="field" id="1" type="hidden" value="A"/>
<input class="field" id="2" type="hidden" value="B"/>
<input class="field" id="3" type="hidden" value="C"/>
<input class="field" id="4" type="hidden" value="D"/>
</div>
<input id="button" value="generate" type="button"/>
Another solution that gives the exact specified output and handles missing attributes gracefully:
See it in action at jsFiddle:
$(function() {
$('#button').click(function() {
var ResStr = $('#selection input.field');
ResStr = ResStr.map (function () {
var jThis = $(this);
var ID = jThis.attr ("id");
if (!ID) ID = "null";
var VAL = jThis.val ()
if (!VAL) VAL = "null";
return 'id[' + ID + ']=val[' + VAL + ']';
} ).get () .join ('&');
alert (ResStr);
} );
} );
this returns all the html combined of all the inputs inside the div
var h = '';
var c = 0;
$('#selection input.field').each(function(){
h += '&id['+(++c)+']=val['+$(this).val()+']';
});
h = h.slice(1);
alert(h);

Categories