I am close but missing something. Im trying to pass variables of multiple checkboxes to a php page with jquery. My code:
<div id="students">
<div class="field">
<label>
<input type="checkbox" name="pupil[a]" value="a" id="pupil"/>
Pupil A
</label>
</div>
<div class="field">
<label>
<input type="checkbox" name="pupil[b]" value="b" id="pupil"/>
Pupil B
</label>
</div>
<div class="field">
<label>
<input type="checkbox" name="pupil[c]" value="c" id="pupil"/>
Pupil C
</label>
</div>
</div>
<br /><br />
<div id="occupation">
<div class="field">
<label>
<input type="checkbox" name="occupation[Software]" value="Software" id="occupation"/>
Software
</label>
</div>
<div class="field">
<label>
<input type="checkbox" name="occupation[Marketing]" value="Marketing" id="occupation"/>
Marketing
</label>
</div>
<div class="field">
<label>
<input type="checkbox" name="occupation[Teacher]" value="Teacher" id="occupation"/>
Teacher
</label>
</div>
</div>
My jquery:
$(document).ready(function(){
$(":checkbox").on('change', function() {
var val = [];
var myval = []; //defining to pass with AJAX
var theval =[]; //defining to pass with AJAX
$(':checkbox:checked').each(function(i){
myval[i] = $(this).attr('id');
theval[i] = $(this).attr('name');
var newval = myval[i] +"="+ myval[i];
$.ajax({
type: "POST",
url: 'draftdata.php',
data : { newval}, //tried this and
data : {myval : theval}, // and tried this too
success: function(data){
$("#result").html(data);
}
});
});
});
});
I only want to pass the data that was checked in the checkboxes to php. There may be multiple group of checkboxes so the $_POST['desiredValue'] cannot be defined. So I can only check if its set by if(isset($_POST['desiredValue'])).
When I check Software, Marketing and Teacher and on draftdata.php do a print_r($_POST[]),I get:
Array
(
[myval] => Array
(
[0] => Software
[1] => Marketing
[2] => Teacher
)
)
What i want to get is:
Array
(
[0] => 'occupation' = 'Software'
[1] => 'occupation' = 'Marketing'
[2] => 'occupation' = 'Teacher'
)
What am I missing?
Thanks.
I modified your html code in this way,
<form id="myform" class="" action="draftdata.php" method="post">
<div id="students">
<div class="field">
<label>
<input type="checkbox" name="pupil[]" value="a" id="pupil" /> Pupil A
</label>
</div>
<div class="field">
<label>
<input type="checkbox" name="pupil[]" value="b" id="pupil" /> Pupil B
</label>
</div>
<div class="field">
<label>
<input type="checkbox" name="pupil[]" value="c" id="pupil" /> Pupil C
</label>
</div>
</div>
<br />
<br />
<div id="occupation">
<div class="field">
<label>
<input type="checkbox" name="occupation[]" value="Software" id="occupation" /> Software
</label>
</div>
<div class="field">
<label>
<input type="checkbox" name="occupation[]" value="Marketing" id="occupation" /> Marketing
</label>
</div>
<div class="field">
<label>
<input type="checkbox" name="occupation[]" value="Teacher" id="occupation" /> Teacher
</label>
</div>
</div>
<button type="button" name="button" id="fsubmit">Submit</button>
</form>
by adding a form and
<button type="button" name="button" id="fsubmit">Submit</button>
and then using the id of the button #fsubmit into our jquery.
<script type="text/javascript">
$(document).ready(function() {
$("#fsubmit").click(function(e) {
var val = [];
var id = []; //defining to pass with AJAX
var name = []; //defining to pass with AJAX
var val = [];
$('input:checkbox:checked').each(function(i, v){
id[i] = $(this).attr('id');
name[i] = $(this).attr('name');
val[i] = $(this).val();
});
var url = $('#myform').attr('action');
$.ajax({
url: url,
type: "POST",
dataType: 'json',
data : {
'id': id,
'name': name,
'val': val
},
success: function(data) {
// $("#result").html(data);
console.log(data);
}
});
});
});
</script>
notice that I change some of the variable, change this according to your needs,
var val = [];
var id = []; //defining to pass with AJAX
var name = []; //defining to pass with AJAX
var val = [];
and also added with this
var url = $('#myform').attr('action');
and, dataType: 'json',
what the jquery do, when the user click on the button, get the link from the form action and look for the checked values and sent it to the php.
here the sample of the php
<?php
if ( isset($_POST['id']) ) {
$temp['id'] = $_POST['id'];
}
if ( isset($_POST['name']) ) {
$temp['name'] = $_POST['name'];
}
if ( isset($_POST['val']) ) {
$temp['val'] = $_POST['val'];
}
$data['data'] = $temp;
echo json_encode($data);
check your log for the result,
hope this help
Related
In short, if a user selects yes to a radio option, I'm trying to obtain the data-name attribute from that input and push it to an array called accepted_array.
If a user selects no, then store data-name to declined_array.
Here is a visual to the markup:
<div class="guest__options-group">
<input id="attending-yes-0" type="radio" name="attendance-0" value="yes" data-name="John" required />
<label for="attending-yes-0">Yes</label>
</div>
<div class="guest__options-group">
<input id="attending-no-0" type="radio" name="attendance-0" value="no" data-name="John" required />
<label for="attending-no-0">No</label>
</div>
<!-- options for Alex -->
<div class="guest__options-group">
<input id="attending-yes-1" type="radio" name="attendance-1" value="yes" data-name="Alex" required />
<label for="attending-yes-1">Yes</label>
</div>
<div class="guest__options-group">
<input id="attending-no-1" type="radio" name="attendance-1" value="no" data-name="Alex" required />
<label for="attending-no-1">No</label>
</div>
Here are 2 approaches I've experimented with:
First approache.
(function ($) {
$( ".guest__attendance-input" ).each(function(index) {
$(this).on("click", function(){
var $this = $(this);
var checkedVal = $this.val();
var accepted_array = [];
var declined_array = [];
if( checkedVal == "yes" ) {
var name = $this.data("name");
accepted_array.push(name);
} else {
declined_array.push(name);
}
console.log("accepted " + accepted_array.join(","));
console.log("declined " + accepted_array.join(","));
});
});
}) (jQuery);
This only executes for the selected user and adds the name to both arrays.
Second approache.
(function ($) {
$( ".guest__attendance-input" ).each(function(index) {
$(this).on("click", function(){
var $this = $(this);
var data = [];
var checked = $this.is(':checked');
var name = $this.attr('data-name');
if (checked) {
if (!data[name]) {
data[name] = []
}
data[name].push($this.val())
}
console.log(data);
});
});
}) (jQuery);
Which only adds the user to a single array.
If both select yes, I need both names in the accepted_array. If someone selects yes initially and then selects no I need to remove them from the accepted_array and vice versa.
You can use splice with inArray to remove value from array if someone selects yes initially and then selects no and vice versa.
Example:
var accepted_array = [];
var declined_array = [];
$('.guest__options-group > input[type=radio]').on('change', function() {
var $this = $(this);
var name = $this.data("name");
var checkedVal = $this.val();
var name = $this.data("name");
if (checkedVal == "yes") {
accepted_array.push(name);
declined_array.splice($.inArray(name, declined_array), 1);
} else {
declined_array.push(name);
accepted_array.splice($.inArray(name, accepted_array), 1);
}
console.log("accepted " + accepted_array.join(","));
console.log("declined " + declined_array.join(","));
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<!-- options for John -->
<div class="guest__options-group">
<input id="attending-yes-0" type="radio" name="attendance-0" value="yes" data-name="John" required />
<label for="attending-yes-0">Yes</label>
</div>
<div class="guest__options-group">
<input id="attending-no-0" type="radio" name="attendance-0" value="no" data-name="John" required />
<label for="attending-no-0">No</label>
</div>
<!-- options for Alex -->
<div class="guest__options-group">
<input id="attending-yes-1" type="radio" name="attendance-1" value="yes" data-name="Alex" required />
<label for="attending-yes-1">Yes</label>
</div>
<div class="guest__options-group">
<input id="attending-no-1" type="radio" name="attendance-1" value="no" data-name="Alex" required />
<label for="attending-no-1">No</label>
</div>
I have a form with dynamic input. Inputs have same name attributes. So I want to make array for each row.
Like this;
[{'company':'Apple'},{'address':'USA'}],
[{'company':'Samsung'},{'address':'Korea'}]
I am using this simple form (it's dynamic);
<form id='companies'>
<input name='company[]'>
<input name='address[]'>
</form>
And this;
$('form').submit(function(event) {
var newFormData = $('#companies').serializeArray();
console.log(newFormData);
event.preventDefault();
});
Console Log; (All inputs in same array)
[{'company':'Apple'},{'address':'USA'},{'company':'Samsung'},{'address':'Korea'}]
This is an example of solution of your problem :)
<form id='companies'>
<div class='container-input'>
<input name='company[]'>
<input name='address[]'>
</div>
<div class='container-input'>
<input name='company[]'>
<input name='address[]'>
</div>
... -> Now you have dynamic containers
</form>
You could use this approach to solve the problem with jQuery.
$('#companies').submit(function(event) {
var $data = [];
var $containers = $(".container-input");
$containers.each(function() {
var $contenedor = $(this);
var $inputCompany = $contenedor.find('input[name^="company"]');
var $inputAddress = $contenedor.find('input[name^="address"]');
var $objectInput = [{
'company': $inputCompany.val()
}, {
'address': $inputAddress.val()
}];
$data.push($objectInput);
});
console.log($data);
});
May help :) more dynamically.
$('#companies').submit(function(event) {
var $data = [];
$.each($(this).children("div"),function(){
obj={};
$.each($(this).find(":input"),function(){
obj[$(this).attr("name").replace("[]","")]=$(this).val();
$data.push(obj);
});
})
console.log($data);
event.preventDefault();
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<form id='companies'>
<div class="input">
<input name='company[]'>
<input name='address[]'>
<input name='phone[]'>
</div>
<div class="input">
<input name='company[]'>
<input name='address[]'>
</div>
<div class="input">
<input name='company[]'>
<input name='address[]'>
</div>
<input type="submit"/>
</form>
Example code:
<form method="get">
<input type="checkbox" name="anythingOne[]" value='one'> <!-- checked -->
<input type="checkbox" name="anythingOne[]" value='two'>
<input type="checkbox" name="anythingOne[]" value='three'> <!-- checked -->
<input type="checkbox" name="otherThingTwo[]" value='Forty'>
<input type="checkbox" name="otherThingTwo[]" value='Fifty'> <!-- checked -->
</form>
On form submission the URL should look like:
http://some-website.tld/action?anythingOne=one,three&otherThingTwo=Fifty
What I am observing now is,
http://some-website.tld/action?anythingOne=one&anythingOne=three&otherThingTwo=Fifty
The serialize() or serializeArray() is not working in this case. Any ideas?
You could grab the result of .serializeArray and transform it into the desired format:
$(function() {
$('form').on('submit', function(e) {
e.preventDefault();
var data = $(this).serializeArray();
var dataByKey = data
.reduce((result, entry) => {
var name = entry.name.replace(/\[\]$/, '');
(result[name] || (result[name] = [])).push(entry.value);
return result;
}, {});
Object.keys(dataByKey)
.forEach((key, _) => dataByKey[key] = dataByKey[key].join(','));
console.log(dataByKey);
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form method="get">
<fieldset>
<input type="checkbox" name="anythingOne[]" value='one'>1
<input type="checkbox" name="anythingOne[]" value='two'>2
<input type="checkbox" name="anythingOne[]" value='three'>3
</fieldset>
<fieldset>
<input type="checkbox" name="otherThingTwo[]" value='Forty'>40
<input type="checkbox" name="otherThingTwo[]" value='Fifty'>50
</fieldset>
<input type="submit" />
</form>
If you want, you can also use pure javascript without jQuery to get all the checked checkboxes' value, http://jsfiddle.net/jx76dpkh/1/
<form id="myForm" method="get">
<input type="checkbox" name="anythingOne[]" value='one'>1
<input type="checkbox" name="anythingOne[]" value='two'>2
<input type="checkbox" name="anythingOne[]" value='three'>3
<input type="checkbox" name="otherThingTwo[]" value='Forty'>40
<input type="checkbox" name="otherThingTwo[]" value='Fifty'>50
<input type="submit" />
</form>
JS:
const myForm = document.getElementById('myForm');
myForm.addEventListener('submit', (e) => {
e.preventDefault();
let checkboxes = Array.from(myForm.querySelectorAll('input[type="checkbox"]:checked');// build the array like element list to an array
let anythingOne = checkboxes.filter( box => box.name === 'anythingOne[]').map(item => item.value);
let otherThingTwo = checkboxes.filter( box => box.name === 'otherThingTwo[]').map(item => item.value);
});
In case, you are allowed to change html, here is a solution using hidden fields.
function updateChecks() {
$.each(['anythingOne', 'otherThingTwo'], function(i, field) {
var values = $('input[type=checkbox][data-for=' + field + ']:checked').map(function() {
return this.value;
}).get().join(',');
$('input[type=hidden][name=' + field + ']').val(values);
});
}
$(function() {
$('form').on('submit', function(e) {
updateChecks();
});
updateChecks();
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form method="get">
<input type="hidden" name="anythingOne" value='' />
<input type="hidden" name="otherThingTwo" value='' />
<input type="checkbox" data-for="anythingOne" value='one' checked='' />
<input type="checkbox" data-for="anythingOne" value='two' />
<input type="checkbox" data-for="anythingOne" value='three' checked='' />
<input type="checkbox" data-for="otherThingTwo" value='Forty' />
<input type="checkbox" data-for="otherThingTwo" value='Fifty' checked='' />
</form>
You could get query string parameters using by serializeArray() method. Then use reduce() to group parameter values by name, and map() to get array of key-value pairs. Then it is possible to concatenate the pairs separated by & using join() method. For example the following snippet creates a target URL using actual value of the form action (current URL by default) and values of checked checkboxes:
$('form').submit(function() {
var queryString = $(this).serializeArray()
.reduce(function(transformed, current) {
var existing = transformed.find(function(param) {
return param.name === current.name;
});
if (existing)
existing.value += (',' + current.value);
else
transformed.push(current);
return transformed;
}, [])
.map(function(param) {
return param.name + '=' + param.value;
})
.join('&');
var action = $(this).prop('action');
var delimiter = (~action.indexOf('?')) ? '&' : '?';
$(this).prop('action', action + delimiter + queryString);
// Only for display result. Remove on real page.
var url = $(this).prop('action');
console.log(url);
return false;
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form method="GET">
<input type="checkbox" name="anythingOne" value='one'>
<input type="checkbox" name="anythingOne" value='two'>
<input type="checkbox" name="anythingOne" value='three'>
<input type="checkbox" name="otherThingTwo" value='Forty'>
<input type="checkbox" name="otherThingTwo" value='Fifty'>
<button type="submit">Show target URL</button>
</form>
The latest 3 lines are used only to prevent the form sending and display resulted URL.
Also it is possible to solve the question using only serialize() mathod and regular expressions, but it requires lookbehind assertion support in browsers.
You can collect all the checked boxer and join the different parts of the strings.This may not be the most neat or efficient solution, but it works. I used a button to trigger the concatenation. See my comments within the code.
$(document).ready(function(){
$("button").click(function(){
/* concatenate anythingOne form*/
//collect anythingOne input
var joined_serialized = []
var anythingOne = [];
$.each($("input[name='anythingOne[]']:checked"), function(){
anythingOne.push($(this).val());
});
//join otherThingTwo input
var anythingOne_serialized = "";
if(anythingOne.length > 0){ //only collect if checked
anythingOne_serialized = "anythingOne=" + anythingOne.join(",");
joined_serialized.push(anythingOne_serialized)
}
/* concatenate otherThingTwo form*/
//collect otherThingTwo input
var otherThingTwo = []
$.each($("input[name='otherThingTwo[]']:checked"), function(){
otherThingTwo.push($(this).val());
});
//join otherThingTwo input
var otherThingTwo_serialized = "";
if(otherThingTwo.length > 0){ //only collect if checked
otherThingTwo_serialized = "otherThingTwo=" + otherThingTwo.join(",");
joined_serialized.push(otherThingTwo_serialized)
}
/*join different form names*/
var joined_serialized = joined_serialized.join("&")
if(joined_serialized.length == 1){ //remove last & if only one form is checked
joined_serialized = joined_serialized.slice(0, -1)
}
/*concatenated forms with website*/
var result = "http://some-website.tld/action?"+joined_serialized
console.log(result) //E.g. when Two, Three and Forty are checked: http://some-website.tld/action?anythingOne=two,three&otherThingTwo=Forty
})
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form method="get">
<input type="checkbox" name="anythingOne[]" value='one'> <!-- checked -->
<input type="checkbox" name="anythingOne[]" value='two'>
<input type="checkbox" name="anythingOne[]" value='three'> <!-- checked -->
<input type="checkbox" name="otherThingTwo[]" value='Forty'>
<input type="checkbox" name="otherThingTwo[]" value='Fifty'> <!-- checked -->
</form>
<button>submit<button/>
My problem is that I have one form with some fields and three inputs type button, they all represents one message. I want to make chooseing one of three messages required. My code is bellow:
<input id="poruka1" type="button" class="hm_datumibtn poruka" name="poruka1" value="Pored mene, sve želje " >
<input id="poruka2" type="button" class="hm_datumibtn poruka" name="poruka2" value="Pored sebe, sve želje " >
<input id="poruka3" type="button" class="hm_datumibtn poruka" name="poruka3" value="Pored tebe, sve želje " >
Do you have any idea how can I solve this kind of problem?
<script>
function upis(){
//var datum = $(this).find('.datum').val();
//var poruka = $(this).find('.poruka').val();
//var poruka = $(this).attr('value');
if (poruka_forma.poruka1.value == '' && poruka_forma.poruka2.value == ''&& poruka_forma.poruka3.value == '') {
alert('You have to choose message.');
return false;
}
else {
myForm.submit();
}
var ime = document.getElementById("ime").value;
var ime_slavljenik = document.getElementById("ime_slavljenik").value;
var elementsdate = document.getElementsByClassName("selected_date");
var datum = elementsdate[0].value;
var elements = document.getElementsByClassName("selected");
var poruka = elements[0].value;
//var poruka = document.getElementById("poruka").value;
//var datum = document.getElementById("datum").value;
//var poruka = document.getElementById("poruka").value;
//var email = document.getElementById("email").value;
//var dataString = "ime="+encodeURIComponent(ime)+"&ime_slavljenik="+encodeURIComponent(ime_slavljenik);
$.ajax({
type:"post",
url: "upis.php",
cashe: false,
//data: dataString+'&datum='+datum+'&poruka='+poruka,
data: {ime:ime,ime_slavljenik:ime_slavljenik,datum:datum, poruka:poruka},
success: function(data){
//window.alert(data);
document.getElementById("placefortableanketa").innerHTML = data;
},
error: function (req, status, err) {
console.log('Something went wrong', status, err);
}
})
return false;
}
</script>
I think you might want to use <input type="radio" /> instead. Example:
<form>
<input type="radio" id="radio_btn_1" name="radio_btn" value="choice_1" required="required" checked="checked" /><label for="radio_btn_1">Choice 1</label><br />
<input type="radio" id="radio_btn_2" name="radio_btn" value="choice_2" required="required" /><label for="radio_btn_2">Choice 2</label><br />
<input type="radio" id="radio_btn_3" name="radio_btn" value="choice_3" required="required" /><label for="radio_btn_3">Choice 3</label><br />
</form>
You can add required attributes to make them required. Also, adding checked attributes will make a radio button selected by default.
You can also use <label> with for attribute. When that label is clicked, it selects a radio button that it refers to by id in its for attribute.
Edit: I saw your comment that you don't want to use radio buttons because of the design. You can actually hide the radio buttons, and just use <label> with for attributes. Example:
<style>
#radio_btn_1:checked + label{background-color:red;}
#radio_btn_2:checked + label{background-color:red;}
#radio_btn_3:checked + label{background-color:red;}
</style>
<form>
<input style="display:none;" type="radio" id="radio_btn_1" name="radio_btn" value="choice_1" required="required" checked="checked" /><label for="radio_btn_1">Choice 1</label><br />
<input style="display:none;" type="radio" id="radio_btn_2" name="radio_btn" value="choice_2" required="required" /><label for="radio_btn_2">Choice 2</label><br />
<input style="display:none;" type="radio" id="radio_btn_3" name="radio_btn" value="choice_3" required="required" /><label for="radio_btn_3">Choice 3</label><br />
</form>
Currently I have been using ajax to post to a few methods in my code igniter installation. I now have a form that has a checkbox array with other inputs and am having problems passing the value into post. Currently it returns the last value of the the last checkbox even if it's not checked.
.js
$('.flagPost').on('submit', function() {
var that = $(this), url = that.attr('action'), type = that.attr('method'), data = {};
that.find('[name]').each(function(index, value) {
var that = $(this), name = that.attr('name'), value = that.val();
data[name] = value;
});
$.ajax({
url : url,
type : type,
data : data,
success : function(response) {
$('#flagSuccess').empty().append(response).fadeIn('slow').delay(3000).fadeOut(800);
}
});
return false;
});
.html
<div class="form-group">
<label for="email" class="col-sm-4 control-label">Email</label>
<div class="col-sm-8">
<input type="email" class="form-control input-sm" name="email" id="email" placeholder="Email Address" value="<?php echo set_value('email');?>">
</div>
<span class="help-block"></span>
</div>
<div class="form-group">
<label class="control-label col-sm-4">Issues/Problems</label>
<div class="col-sm-8">
<label class="checkbox" for="problems-0">
<input type="checkbox" name="problem[]" id="problems-0" value="Adult Content">
Adult Content
</label>
<label class="checkbox" for="problems-1">
<input type="checkbox" name="problem[]" id="problems-1" value="Spam">
Spam
</label>
<label class="checkbox" for="problems-2">
<input type="checkbox" name="problem[]" id="problems-2" value="Non-existent">
Non-existent
</label>
<label class="checkbox" for="problems-3">
<input type="checkbox" name="problem[]" id="problems-3" value="Language">
Language
</label>
<label class="checkbox" for="problems-4">
<input type="checkbox" name="problem[]" id="problems-4" value="Other">
Other
</label>
</div>
<span class="help-block"></span>
</div>
<!-- Textarea -->
jQuery has a serialize method for grabbing all the data from a form (following the normal rules for what controls count as successful)
data = that.serialize()
Since the checkboxes have the same value for the name attribute they are overwriting the same property on the data object.
that.find('[name]').each(function(index, value) {
var that = $(this), name = that.attr('name'), value = that.val();
data[name] = value; //This overwrites the property
});
Look at using jQuery's serialize function instead of building your own object to pass.
JS fiddle: http://jsfiddle.net/7Aysb/