I'm trying to get information from a form and passing it to mysql. Here is my method:
var form = [];
$("input").each(function(){
var id = $(this).attr("name");
var value = $(this).val();
alert(id);
var item = {};
item ["name"] = id;
item ["value"] = value;
form.push(item);
});
return JSON.stringify(form);
The problem is when i try to get the checked and unchecked values from the radio buttons. The query string that I want to pass to mysql outputs like this:
insert into contatos (nome, rua, sexo, sexo, ncasa, civil, civil, civil, bairro, aniversario, cidade, rg, cpf, usuario, telefone, senha, email, confirmasenha) values ('', '', 'M', 'F', '', 'S', 'C', 'D', '', '', '', '', '', '', '', '', '', '')
The fields "sexo" and "civil" are repeating. How do I make the input to read the radio buttons only 1 time?
It is because you are iterating over each text field and if you have 3 radio button you are pushing all 3 values to array so I took 2 radio fields sexo and civil outside loop so It will be pushed only 1 time and not be repeated.
$("input").each(function(){
if(id!='sexo' || id!='civil'){
var id = $(this).attr("name");
var value = $(this).val();
var item = {};
item ["name"] = id;
item ["value"] = value;
form.push(item);
}
});
var value1 =$('input:radio[name=sexo]:checked').val();
var value2 =$('input:radio[name=civil]:checked').val();
var item = {};
item ["name"] = "sexo";
item ["value"] = value1;
form.push(item);
var item = {};
item ["name"] = "civil";
item ["value"] = value2;
form.push(item);
return JSON.stringify(form);
If you call serializeArray on a jQuery form element you'll get an array of objects, similar to the one you are creating, and will avoid duplicates:
$('form').serializeArray();
will return:
[
{
name: "firstfield",
value: "1"
},
{
name: "secondfield",
value: "2"
}
]
Related
I am trying to show/hide form fields in a Squarespace form based upon the value selected in a dropdown menu. The dropdown menu has a list of values from 1-10. The intent is to display 2 form fields for each number selected from the dropdown menu. For value 1, I want the form fields titled "Serial Number" and "Confirm Serial Number" to ALWAYS be displayed. For value 2, I want to show "Serial Number 2" and "Confirm Serial Number 2". And so on for values 3-10.
Here is a screenshot of the form as it is now with everything displayed.
enter image description here
You can get the serial element with document.getElementById(`serial-input-${index}`)
You can get the serial confirm element with document.getElementById(`serial-input-confirm-${index}`)
<p>Number of products</p>
<select id="select" onChange="create.input()"></select>
<div id="input"></div>
const create = {
select: () => {
let select = document.getElementById('select')
// Create 1-10 number of products
new Array(10).fill(0).forEach((x, i) => {
let option = document.createElement('option')
option.innerHTML = (i+1)
option.value = (i+1)
select.appendChild(option)
})
},
input: () => {
let input = document.getElementById('input')
let select = document.getElementById('select')
console.log(select.value)
// Remove all child
input.innerHTML = ''
// Create the same number of input has you select in select ...
const size = parseInt(select.value, 10)
new Array(size).fill(0).forEach((x, i) => {
console.log(i)
let p_input = create.p_input(i)
p_input.forEach(x => input.appendChild(x))
})
},
p_input: index => {
let name = `erial number` + (index > 0 ? ' ' + (index+1) : '')
let serial_p = document.createElement('p')
serial_p.innerHTML = 'S' + name
serial_p.id = 'p-serial-' + index
serial_p.class = 'p-serial'
let serial_p_confirm = document.createElement('p')
serial_p_confirm.innerHTML = 'Confirm s' + name
serial_p_confirm.id = 'pc-serial-' + index
serial_p_confirm.class = 'pc-serial'
let serial_input = document.createElement('input')
serial_input.type = "text"
serial_input.id = "serial-input-" + index
serial_input.class = 'serial-input'
let serial_input_confirm = document.createElement('input')
serial_input_confirm.type = "text"
serial_input_confirm.id = "serial-input-confirm-" + index
serial_input_confirm.class = 'serial-input'
return [serial_p, serial_input, serial_p_confirm, serial_input_confirm]
}
}
create.select()
create.input()
for exemple here its what i get when i click on 5.
i have a list of horse race result in my database.
In my database, i have 3 table :
horse (cheval in french) with : id, name ...
race (course in french) with : id, name ...
and resultrace (resultatcourse in french) the id of the horse (cheval) and the id of the race (course) and position in the race(first, second ...)
When i want to use it in a NgFor to do a list of all my race, who can i can use only the race's name, the horse's name and his position ?
My JSON:
[
{id: 1, nom: "Valdack", place: 2, course: 1},
{id: 5, nom: "Flying fox", place: 1, course: 1},
{id: 17, nom: "Dane Dream", place: 4, course: 1}
]
My html code :
<ion-item *ngFor="let item of items; ">
<h2>{{ item.nom (name of the race) }} | {{ item.nom (name of the horse) }} | N°{{ item.place }} </h2>
</ion-item>
My php :
try {
$stmt = $pdo->query('SELECT course.id, course.nom , cheval.id, cheval.nom , resultatcourse.place, resultatcourse.course, resultatcourse.place FROM course, cheval, resultatcourse WHERE resultatcourse.course = course.id AND resultatcourse.cheval = cheval.id');
while($row = $stmt->fetch(PDO::FETCH_OBJ))
{
// Assign each row of data to associative array
$data[] = $row;
}
// Return data as JSON
echo json_encode($data);
}
catch(PDOException $e)
{
echo $e->getMessage();
}
And my java :
load() : void
{
this.http.get('http://localhost/wequida/retrieve-resultatcourse.php').subscribe((data : any) =>
{
console.dir(data);
this.items = data;
},
(error : any) =>
{
console.dir(error);
});
}
My table horse and my table race have 2 same columns : id and name, maybe it's the problem ?
I find the solution ! (Thk user184994 !)
In my php :
try {
$stmt = $pdo->query('SELECT course.id, course.nom as coursenom, cheval.id, cheval.nom as chevalnom, resultatcourse.place, resultatcourse.course, resultatcourse.place FROM course, cheval, resultatcourse WHERE resultatcourse.course = course.id AND resultatcourse.cheval = cheval.id');
while($row = $stmt->fetch(PDO::FETCH_OBJ))
{
// Assign each row of data to associative array
$data[] = $row;
}
// Return data as JSON
echo json_encode($data);
}
catch(PDOException $e)
{
echo $e->getMessage();
}
I had an as to differentiate horse's name and race's name
In my html :
<ion-item *ngFor="let item of items; ">
<h2>{{ item.coursenom }} | {{ item.chevalnom }} | N°{{ item.place }} </h2>
</ion-icon></button>
</ion-item>
I use the as name
I have scriptet me a maps with markers based on a MySQL Table.
The position is in the Table.
Now, i would like to write with HTML in the InfoWindow, because it not show HTML on the InfoWindow on the Map.
downloadUrl('inc/map_bridge.php', function(data) {
var xml = data.responseXML;
var markers = xml.documentElement.getElementsByTagName('marker');
Array.prototype.forEach.call(markers, function(markerElem) {
var name = markerElem.getAttribute('name');
var ide = markerElem.getAttribute('id');
var desc = markerElem.getAttribute('beschreibung');
var type = markerElem.getAttribute('art');
var link = '<p>Klicke für weitere infos: Hier';
var point = new google.maps.LatLng(
parseFloat(markerElem.getAttribute('lat')),
parseFloat(markerElem.getAttribute('lng')));
var infowincontent = document.createElement('div');
var strong = document.createElement('strong');
strong.textContent = 'ID' + ide + ': ' + name
infowincontent.appendChild(strong);
infowincontent.appendChild(document.createElement('br'));
var text = document.createElement('text');
text.textContent = desc + link
infowincontent.appendChild(text);
var icon = customLabel[type] || {};
var marker = new google.maps.Marker({
map: map,
position: point,
label: icon.label
});
marker.addListener('click', function() {
infoWindow.setContent(infowincontent);
infoWindow.open(map, marker);
});
});
});
}
It show only so:
show example picture
the following i have in the MySQL-Table
first line<br>second line
If 'beschreibung' were the result of SELECT SQL, the reason is escaped SELECT
SQL result.
(I'm in short of reputation, so write in answer form.)
I have a simple SOQL query in java for extracting Salesforce standard object as follows -
String soqlQuery = "SELECT FirstName, LastName FROM Contact";
QueryResult qr = connection.query(soqlQuery);
I want to get the datatype of the object fields.
I have written a small function below which will provide the list of Phone fields and its label present in a Custom or Standard Object of your Salesforce ORG. I hope this might help you in writing the business logic for your code.
public list<String> getFieldsForSelectedObject(){
selectedPhoneNumber = ''; //to reset home number field
list<String> fieldsName = new list<String>();
selectedObject = 'Object Name' // This should have the object name for which we want to get the fields type
schemaMap = Schema.getGlobalDescribe(); //Populating the schema map
try{
if(selectedObject != null || selectedObject != '' || selectedObject != '--Select Object--'){
Map<String, Schema.SObjectField> fieldMap = schemaMap.get(selectedObject).getDescribe().fields.getMap();
for(Schema.SObjectField sfield : fieldMap.Values()){
schema.describefieldresult dfield = sfield.getDescribe();
schema.Displaytype disfield= dfield.getType();
system.debug('#######' + dfield );
if(dfield.getType() == Schema.displayType.Phone){// Over here I am trying to findout all the PHONE Type fields in the object(Both Custom/Standard)
fieldsName.add('Name:'+dfield.getName() +' Label:'+ dfield.getLabel ());
}
}
}
}catch(Exception ex){
apexPages.addMessage(new ApexPages.message(ApexPages.severity.ERROR,'There is no Phone or Fax Field Exist for selected Object!'));
}
return fieldsName;
}
Sample OUTPUT List of String::
Name: Home_Phone__c Label: Home Phone
Name: Office_Phone__c Label: Office Phone
Say that we have the below soql.
select FirstName,LastName from Contact limit 2
The query result in the QueryResult object looks like below.
{
[2]XmlObject
{
name={urn:partner.soap.sforce.com}records, value=null, children=
[
XmlObject{name={urn:sobject.partner.soap.sforce.com}type, value=Contact, children=[]},
XmlObject{name={urn:sobject.partner.soap.sforce.com}Id, value=null, children=[]},
XmlObject{name={urn:sobject.partner.soap.sforce.com}FirstName, value=Bill, children=[]},
XmlObject{name={urn:sobject.partner.soap.sforce.com}LastName, value=Gates, children=[]}
]
},
XmlObject
{
name={urn:partner.soap.sforce.com}records, value=null, children=
[
XmlObject{name={urn:sobject.partner.soap.sforce.com}type, value=Contact, children=[]},
XmlObject{name={urn:sobject.partner.soap.sforce.com}Id, value=null, children=[]},
XmlObject{name={urn:sobject.partner.soap.sforce.com}FirstName, value=Alan, children=[]},
XmlObject{name={urn:sobject.partner.soap.sforce.com}LastName, value=Donald, children=[]}
]
},
}
In order to parse the QueryResult and to take column names, I have implemented the below method that will return the column names in comma separated String. I have mentioned the logic inside the code.
public String getColumnNames(QueryResult soqlResponse)
{
String columns = ""
try
{
// We are looping inorder to pick the 1st record from the QueryResult
for (SObject record : soqlResponse.getRecords())
{
Iterator<XmlObject> xmlList = record.getChildren();
int counterXml = 0;
while(xmlList.hasNext())
{
XmlObject xObj = xmlList.next();
// Since the 1st 2 nodes contains metadata of some other information, we are starting from the 3rd node only
if(counterXml > 1)
{
columns += xObj.getName().getLocalPart() + ",";
}
counterXml++;
}
// Since we can get the column names from the 1st record, we are breaking the loop after the data of 1st record is read
break;
}
// We are removing the last comma in the string
columns = columns.substring(0, columns.length() - 1);
}
catch(Exception ex)
{
}
return columns;
}
I have been combing through the wiki for the jqgrid and i can't seem to figure out how to change the logic in my controller for the jqgrid to search.
I assume the search will use the same URL specified in the jqgrid. Here is the action logic called by my jqgrid. I am using spring 3.0 and its a java controller.
#RequestMapping(value = "studentjsondata", method = RequestMethod.GET)
public #ResponseBody String studentjsondata(HttpServletRequest httpServletRequest) {
Format formatter = new SimpleDateFormat("MMMM dd, yyyy");
String column = "id";
if(httpServletRequest.getParameter("sidx") != null){
column = httpServletRequest.getParameter("sidx");
}
String orderType = "DESC";
if(httpServletRequest.getParameter("sord") != null){
orderType = httpServletRequest.getParameter("sord").toUpperCase();
}
int page = 1;
if(Integer.parseInt(httpServletRequest.getParameter("page")) >= 1){
page = Integer.parseInt(httpServletRequest.getParameter("page"));
}
int limitAmount = 10;
int limitStart = limitAmount*page - limitAmount;
List<Person> students = Person.findStudentPeopleOrderByColumn(true, column, orderType, limitStart, limitAmount).getResultList();
long countStudents = Student.countStudents();
double tally = Math.ceil(countStudents/10.0d);
int totalPages = (int)tally;
long records = countStudents;
StringBuilder sb = new StringBuilder();
sb.append("{\"page\":\"").append(page).append("\", \"records\":\"").append(records).append("\", \"total\":\"").append(totalPages).append("\", \"rows\":[");
boolean first = true;
for (Person s: students) {
sb.append(first ? "" : ",");
if (first) {
first = false;
}
sb.append(String.format("{\"id\":\"%s\", \"cell\":[\"%s\", \"%s\", \"%s\", \"%s\", \"%s\", \"%s\"]}",s.getId(), s.getId(), s.getFirstName(), s.getLastName(), formatter.format(s.getDateOfBirth().getTime()), s.getGender(), s.getMaritalStatus()));
}
sb.append("]}");
return sb.toString();
}
and here is my navGrid decleration
$("#studentGrid").jqGrid('navGrid', "#pager", {edit:false,add:false,del:false,search:true},{ },{ },{ },
{
sopt:['eq', 'ne', 'lt', 'gt', 'cn', 'bw', 'ew'],
closeOnEscape: true,
multipleSearch: true,
closeAfterSearch: true
}
);
Here is my colModel and colNames
colNames:['id','First Name', 'Last Name', 'Date Of Birth', 'Gender', 'Marital Status'],
colModel:[
{name:'id',index:'id', width:15},
{name:'firstName',index:'firstName', width:30, formoptions:{elmprefix:'(*) '}, editable:true, edittype: 'text', editrules:{required:true}},
{name:'lastName',index:'lastName', width:30, formoptions:{elmprefix:'(*) '}, editable:true, edittype: 'text',editrules:{required:true}},
{name:'dateOfBirth',index:'dateOfBirth', width:30, formoptions:{elmprefix:'(*) '},editrules:{required:true}, editable:true, edittype: 'text',
editoptions: {
dataInit: function(element) {
$(element).datepicker({dateFormat: 'MM dd, yy'})
}
}
},
{name:'gender',index:'gender', width:30, formoptions:{elmprefix:'(*) '}, editable:true, editrules:{required:true}, edittype: 'select',
editoptions:{value:{}}
},
{name:'maritalStatus',index:'maritalStatus', width:30, formoptions:{elmprefix:'(*) '}, editable:true, editrules:{required:true}, edittype: 'select',
editoptions:{value:{}}
}
]
As it is, by default the search uses trhe searchGrid method. In the post array the _search: true and filters: {"groupOp":"AND","rules":[{"field":"firstName","op":"eq","data":"Anil"}]} are present.
The searchField, searchOper and searchString are all empty but present in th epost array.
What do I have to do to get the search working?
Do I have to parse the json into Java using the json parser and the filters array, then change my query by adding a where clause and use the values form the Json object?
Does the jqgrid query its own data object insted of going back to the server and launch a new query ?
I am not too sure what I have to do, please offer some form of guidance.
I am not use Spring myself, but the post seems to me contain the information which you need.
In general if you use Advance Searching dialog (multipleSearch: true) or Toolbar Searching with stringResult: true the jqGrid send to the server additional parameter filters which format described here. The one parameter filters can contain information about multiple filters. So you have to covert JSON string to an object and analyse the object to construct some kine of WHERE part of the SELECT statement. The exact implementation is depend from the technology which you use to assess to the database.