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/
Related
SOLVED! Check below for solution
Hello so I need help on figuring out how this will go. This is the case:
Visualization
Firebase Data
Once the user selects a "Vehicle Number" on the list, the "VIN" and "Plate #" textboxes will automatically update with the corresponding data from the database.
In the example with the mock data, once the user selects "A_012", the VIN readonly textbox should only show "KIA9183891284" and the plate # should only show "KIA-0987".
This is currently the HTML and JS codes I used
HTML:
<div class="form-group">
<label for="vehinum">Vehicle Number</label>
<select class="form-control" name="vehicle_num" id="vehinumInput">
</select>
</div>
<div class="form-group">
<label for="vin">VIN</label>
<input type="text" name="vin" class="form-control" id="vinInput" readonly="true">
</div>
<div class="form-group">
<label for="platenum">Plate #</label>
<input type="text" name="plate_no" class="form-control" id="platenoInput" readonly="true">
</div>
JS:
var database = firebase.database();
database.ref('vehicles').once('value', function(snapshot){
if(snapshot.exists()){
var vehi_list = '';
snapshot.forEach(function(data){
var val = data.val();
vehi_list += '<option value="' + val.vehicle_number + '">' + val.vehicle_number + '</option>';
});
$('#vehinumInput').append(vehi_list);
}
I really don't know how to move forward from here. So I am looking for advice or answers on how this will go.
Thank you for taking your time to read!
So after a ton of research, I finally managed to find the answer
HTML:
<div class="form-group" id="vehi_num_mainte">
<label for="exampleFormControlInput100">Vehicle Number</label>
<select class="form-control" name="vehicle_num1" id="numberInput1" onchange="vehi_num_mainte_event();">
<option>-- Select Vehicle --</option>
</select>
</div>
<div class="form-group">
<label for="exampleFormControlInput101">VIN</label>
<input type="text" name="vin_maintenance" class="form-control" id="vinInput1" readonly="true">
</div>
<div class="form-group">
<label for="exampleFormControlInput102">Plate #</label>
<input type="text" name="plate_no1" class="form-control" id="platenoInput1" readonly="true">
</div>
JS:
function vehi_num_mainte_event()
{
//Get text or inner html of the selected option
var d = document.getElementById("numberInput1");
var selectedText = d.options[d.selectedIndex].text;
firebase.database().ref('vehicles').child('vehicle_number').on('value', function(vehinumSnapshot) {
var vehinumChildSnapshot = vehinumSnapshot.val();
var queryRef = firebase.database().ref('vehicles').orderByChild('vehicle_number').equalTo(selectedText);
queryRef.on('value', function(querySnapshot) {
querySnapshot.forEach(function(dinoSnapshot) {
var vin_mainte = '';
var plate_mainte = '';
var val = dinoSnapshot.val();
vin_mainte += val.vin;
plate_mainte += val.plate_no;
document.getElementById('vinInput1').value = vin_mainte;
document.getElementById('platenoInput1').value = plate_mainte;
});
});
});
}
These were my references:
Javascript HTML element get selected select option text value notepad ++
Firebase Docs (Retrieve Data)
I am having 6 bootstrap cards where the details of the card are id, image, content.on clicking the card I am getting the details of the card into the local storage and from that, I am extracting the ids into another array named styleIds I want these styleIds values to sent as value to the input field as onload of body
My js code:
var styles = []
var styleIds = []
function getStyle(id) {
if (styles.length > 0) {
var data = { id: id, image: $("#img_"+id).attr('src'),content: $("#cont_" + id).text() }
var x = JSON.stringify(data)
var index = styles.indexOf(x)
if (index == -1) {
styles.push(x)
}
else {
styles.splice(index, 1)
}
}
else {
var data = { id: id, image: $("#img_"+id).attr('src'),content: $("#cont_" + id).text() }
var x = JSON.stringify(data)
styles.push(x)
}
localStorage.setItem("styles", JSON.stringify(styles))
styleIds = styles.map(element => JSON.parse(element).id);
console.log(styleIds)
assample();
}
function assample() {
$("#style").val(styleIds);
console.log(styleIds)
}
function initStyles() {
var storedNames = JSON.parse(localStorage.getItem("styles") || '[]');
styleIds = storedNames.map(element => JSON.parse(element).id);
}
My form code is:
<body onload = "sample();initGoals();issample();assample();initStyles();">
<div class="form-group">
<label for="username">Username</label>
<input type="text" name="username" class="form-control" required>
</div>
<div class="form-group">
<input type="text" name="room" id="name" value=" ">
</div>
<div class="form-group" >
<input type="text" name="goal" id="goal" value=" ">
</div>
<div class="form-group" >
<input type="text" name="style" id="style" value=" ">
</div>
<div class="form-group">
<label for="email">Email</label>
<input type="text" name="email" class="form-control" required>
</div>
<div class="form-group">
<label for="password2">Password</label>
<input type="password" name="password" class="form-control" required>
</div>
<input type="submit" value="Register" class="btn btn-secondary btn-block">
</form>
The cards are on one page and the form is the another web page so in the styles page the styleIds array is getting the ids butwhen I navigate to the form page the values are getting as a value for the field in the form what is the mistake I did?
Make sure you're calling the functions in the correct order. Also, I would suggest renaming your function names so that you don't get confused.
You can change your onload to just call one function and later care about the order.
<body onload = "doSomething()">
and in the script:
function doSomething() {
sample();
initGoals();
issample();
initStyles();
assample();
}
I am rendering a HTML form through JS and when the user fills the data and clicks on submit, then I am converting into a JSON. But I am unable to fetch the value of checked radio box. Here's my code for rendering the radio box-
return '<div class="">\
<label class="" for="">Gender</label>\
<div class="">\
<div id="">\
<div class="">\
<label for="" class="radio">Male</label>\
<input id="" type="radio" name = "gender" value="M">\
</div>\
<div class="">\
<label for="" class="radio">Female</label>\
<input id="" type="radio" name = "gender" value="F">\
</div>\
<div class="">\
<label for="" class="radio">Others</label>\
<input id="" type="radio" name = "gender" value="O">\
</div>\
</div>\
</div>\
</div>';
};
Here's my function to convert user filled form to JSON,
var convertIntoJSON = function(elements) {
return [].reduce.call(elements, function(data, element){
data[element.name] = element.value;
return data;
}, {});
};
I am calling the above function, as convertIntoJSON(form.elements), where form is my actual form container.
Please tell me how can I access the checked radio button through this, through this code no matter what I select in gender field, I am getting gender as "O" everytime.
As I said in my comment, you can't use this shorthand to get the value of a radio array. Here's a workaround that still supports your original function for non-radio inputs:
var convertIntoJSON = function(elements) {
return [].reduce.call(elements, function(data, element){
if (element.type === "radio") {
if (element.checked) {
data[element.name] = element.value;
}
} else {
data[element.name] = element.value;
}
return data;
}, {});
};
var logSelected = document.getElementById('logSelected');
var form = document.getElementById('theForm');
logSelected.addEventListener('click',() => {
console.log(convertIntoJSON(form.elements));
})
<form id="theForm">
<label for="" class="radio">Male</label>
<input id="" type="radio" name = "gender" value="M">
<label for="" class="radio">Female</label>
<input id="" type="radio" name = "gender" value="F">
<label for="" class="radio">Others</label>
<input id="" type="radio" name = "gender" value="O">
</form>
<input type="button" value="log selected" id="logSelected"/>
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
I want to set radio buttons values based on drop-down selection,Lets assume i have three values in drop-down(A,B and C) , If A or B is selected i want to set radio button default value to Summary and if C is selected i want set value to Detailed. Also when A & B is selected i want to make it non-editable..
Please help this is first time i am using radios with AngularJS.
main.html
<div class="row">
<div class="form-group col-md-6 fieldHeight">
<label for="cycleName" class="col-md-6 required">Scope Type :</label>
<div class="col-md-6">
<select kendo-drop-down-list k-data-text-field="'text'"
k-option-label="'Select'" k-data-value-field="'id'"
k-data-source="assessmentTypeOptions" name="assessmentType"
required ng-model="riskAssessmentDTO.scopeType" id="assessmentType"
maxlength="256" ng-change="assessmentType()"></select>
<p class="text-danger"
ng-show="addAssessment.assessmentType.$touched && addAssessment.assessmentType.$error.required">Assessment
Type is required</p>
</div>
</div>
<div class="form-group col-md-6 fieldHeight">
<label for="assessmentType" class="col-md-5 required">Assessment Type :</label>
<label class="radio-inline"><input type="radio"
name="summary" id="summary" ng-value="'summary'"
ng-model="riskAssessmentDTO.erhFlag" ng-disabled="disableAssessmentType" >Summary </label>
<label class="radio-inline"><input type="radio"
name="detail" id="detail" ng-value="'N'"
ng-model="riskAssessmentDTO.erhFlag" ng-disabled="disableAssessmentType">Detailed</label>
<p class="text-danger"
ng-show="addAssessment.includeERHFlag.$touched && addAssessment.includeERHFlag.$error.required">Assessment
Name is required</p>
</div>
</div>
main.js
$scope.assessmentType = function() {
$scope.riskAssessmentDTO.assessmentName = '';
$scope.riskAssessmentDTO.erhFlag = 'Y';
$scope.showRefineERH = false;
if ($scope.riskAssessmentDTO.scopeType === 'RA_GEO_LOCAT') {
$scope.disableAssessmentType = true;
$scope.riskAssessmentDTO.erhFlag = 'summary';
} else if ($scope.riskAssessmentDTO.scopeType === 'RA_LEGAL_ENTITY') {
$scope.disableAssessmentType = true;
$scope.riskAssessmentDTO.erhFlag = 'summary';
} else if ($scope.riskAssessmentDTO.scopeType === 'RA_BUS_UNIT') {
$scope.disableAssessmentType = false;
$scope.riskAssessmentDTO.erhFlag = 'detailed';
}
};
Use ng-disabled in Radio buttons and use a scope variable as $scope.selectedIndex to set it as false or true
<input type="radio" ng-disabled="selectedInderx==0">
and set $scope.selectedIndex in the ng-change function in Select by passing $index from html