I am new to web development and currently experimenting with HTML forms. I am using Chrome to test out how to show JSON data in a div based on a selection from a tag using jQuery, and my code is not working. When I inspect my webpage, it shows the div for the JSON to load, but the data itself is not there after selecting an element from the dropdown menu. Also, I'm using a stylesheet if that makes any difference. Am I going about this incorrectly?
<json>
{
"firstName": "Jason",
"lastName": "Bourne"
},
{
"firstName": "John",
"lastName": "McClane"
}
<html>
<div id="names">
<select id ="drop-list">
<option value="" disabled="disabled" selected="selected">--Select A Name--</option>
<option>Jason Bourne</option>
<option>John McClane</option>
</select>
</div>
<javascript>
$(function() {
let names = $('#names');
dropList.on('select', getDataViaAjax);
function getDataViaAjax(evnt) {
let request = $.ajax({
method: 'GET',
url: 'people.json',
dataType: 'json',
});
request.done(function(data) {
console.log(data);
let dropList = $('#drop-list');
for (let person of data) {
let newParagraph = $('<p>');
newParagraph.text(person.firstName + ' last name ' + person.lastName);
dropList.append(newParagraph);
}
});
request.fail(function(response) {
console.log('ERROR:' + response.statusText);
});
}
});
I used to use this structure, I thinks its simple but efective, hope it works:
//in your html
<form>
<select id="filterAgendas">
</select>
</form>
//In app,js
$.ajax({
url: 'YourJsonFileLocation',
type: 'GET',
success: function(response) {
console.log(response);
const list = JSON.parse(response);
let filter = '';
list.forEach(list => {
filter += `<option value="${list.id}"> ${list.name}</option>`
});
$('#filterAgendas').html(filter);
}
});
//your json file
{
{
id: 1,
name: name1
},
{
id: 2,
name: name2
},
}
Related
I have a Questionnaire page which is dynamically created via the back end. I need to serialize the form data but the form.serialize array takes the name attribute I want to assign my own key for the data I send. I'm very new to javascript.
I need to put the question data-id in place of the key and the selected input value is this possible?
I'm using AJAX to post the form.
The back end is Flask.
The html page
<h4 class="text-edit" id="question-{{key}}" data-id="{{key}} //will be numeric">1. Does the lecturer Communicate clearly?</h4>
<!-- I need the data-id of the h4 tag-->
<input type="radio" name="options1" id="options" value="1" >
<!-- And the value of the value in the radio button-->
<label class="radio-inline mg" for='options'> Yes</label>
<input type="radio" name="options1" id="options" value="2">
<label class="radio-inline mg" for='options'> No</label>
The Javascript I'm using
var dataset = {
"stream": $("#stream_id").data("name"),
"subject": $('#subject_select option:selected').val(),
"teacher": $('#teacher_select option:selected').val()
};
// IF I COULD Even append the data to the above thing that also would work
$.ajax({
url: "{{url_for('question.gen_teacher')}}",
data: $('form#questionform').serialize(),
type: 'POST',
success: function(response) {
console.log(response);
},
error: function(error) {
console.log(error);
}
});
1. With .serialize()
Actually, .serialize() method will make your form key it's value to be like :
key1=value1&key2=value2
so just append some string to your .serialize() method :
var dataset = {
"stream": $("#stream_id").data("name"),
"subject": $('#subject_select option:selected').val(),
"teacher": $('#teacher_select option:selected').val()
};
$.ajax({
url: "{{url_for('question.gen_teacher')}}",
data: $('form#questionform').serialize() + "&data-id=value",
type: 'POST',
success: function(response) {
console.log(response);
},
error: function(error) {
console.log(error);
}
});
2. With .serializeArray()
var formData = $('form#questionform').serializeArray();
formData.push({ name: "data-id", value: "somevalue" });
and put formData variable inside your $ajax data
Requested Answer ?
with
HTML :
<h4 h-id="1" class="text-edit" id="question-{{key}}" data-id="{{key}} //will be numeric">1. Does the lecturer Communicate clearly?</h4>
<select answer-id="1">
<option value="1">Yes</option>
<option value="0">No</option>
</select>
JavaScript :
var formData = {};
$("h4[h-id]").each(function(){
var hid = $(this).attr("h-id");
var id = $(this).attr("id");
var answer = $('select[answer-id="'+hid+'"]');
formData.push({id:answer});
})
// ... ajax
data: formData,
i have select2 dropdown like:
<select class="form-control validateblank txtSelectChallan" id="txtSelectChallan" />
and i am setting dropdown data by ajax call like:
$.ajax({
type: "POST",
url: "/Account/MaterialSheet.aspx/GetMaterialSheetByLedgerId",
data: '{LedgerId: "' + AccId + '"}',
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (data) {
if (data.d.Result == "OK") {
var challanresults = [];
$.each(data.d.Records, function (index, challn) {
challanresults.push({
id: challn.MaterialSheet_ID,
text: challn.Challan_No,
Amount: challn.Total_Amount
});
});
eachtr.find('.txtSelectChallan').select2({
placeholder: "Select Challan",
data: challanresults,
multiple: true
});
swal.close();
challanresults = null;
}
},
error: function (err) {
swal(
'Oops...',
'Error occured while retrieving data',
'error'
);
}
});
and i get dropdown like :
<select class="form-control validateblank txtSelectChallan select2 hidden-accessible" id="txtSelectChallan" tabindex="-1" aria-hidden="true" multiple="">
<option value="1006">123123</option>
<option value="1007">32123</option>
i have tried to set option attribute using:
challanresults.push({
id: challn.MaterialSheet_ID,
text: challn.Challan_No,
Amount: challn.Total_Amount
});
but i cant get amout as option attribute any idea how to set custom attribute for all option in select2?
Try like this inside foreach loop, and set the trigger after that.
var data = {
id: challn.MaterialSheet_ID,
text: challn.Challan_No
};
var newOption = new Option(data.text, data.id, false, false);
$('#txtSelectChallan').append(newOption).trigger('change');
Check this link for further solution on custom attributes
Or Simply you can do like this in a loop for the result set
var option = "<option value="+challn.MaterialSheet_ID+" amount="+challn.Total_Amount+">"+challn.Challan_No+"</option>
This is what Select2 Official Site has to say about custom-data-fields
$('#mySelect2').select2({
// ...
templateSelection: function (data, container) {
// Add custom attributes to the <option> tag for the selected option
$(data.element).attr('data-custom-attribute', data.customValue);
return data.text;
}
});
// Retrieve custom attribute value of the first selected element
$('#mySelect2').find(':selected').data('custom-attribute');
Click here for the above reference link
I am using select multiple control using selectsize.js here is my control
<div class="default selectize-control multi">
<select multiple id="select-email" class="selectize-input items has-options has-items full">
#*<option value="0">Zero</option>
<option value="1">One</option>
</select>
</div>
I am trying to bind this control through ajax
here is my Ajax code
var selectemailemail = $("#select-email");
selectemailemail.empty().append('<option selected="selected" value="0" disabled = "disabled">Loading.....</option>');
$.ajax({
type: "GET",
url: "/api/Customer/GetCustomerList",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (data)
{
console.log('response', data);
for(var i=0;i<data.length;i++)
{
console.log('data[i].email' + data[i].Email);
$("<option value=" + data[i].TokenId + ">" + data[i].Email + ")</option>").appendTo(selectemailemail);
}
selectemailemail.multipleSelect('refresh');
},
failure: function (response)
{
alert(response.responseText);
},
error: function (response) {
alert(response.responseText);
}
});
};
while running ajax codei am getting data in an array
here is the data in an array
{Id: 0, ContactNo: null, FirstName: null, LastName: null, Email: "verveshivam#gmail.com ", …}
and i want to try to bind the email value in that selected multiple control using code here is my code
for(var i=0;i<data.length;i++)
{
console.log('data[i].email' + data[i].Email);
$("<option value=" + data[i].TokenId + ">" + data[i].Email + ")</option>").appendTo(selectemailemail);
}
but it is not binding the value
in console it is not showing error in console alsoso how can i bind the value in selected multiple control.
I have a Select 2 drop down search function. I am trying to load the results from an ajax call as the selected/default values. I am not sure where I am going wrong? What is the syntax I need to change here so that when I click my modal it shows results preset.
$(document).ready(function() {
$('.editApptModal-button').click(function() {
var appointmentID = $(this).attr('data-appointmentID');
$('#editApptModal').find('input[name="appointmentID"]').val(appointmentID);
$.ajax({
type: 'ajax',
method: 'get',
url: '/ajax',
async: false,
dataType: 'json',
success: function(response) {
console.log(JSON.stringify(response));
$.each(response.employees.data, function(key, value) {
$('select').append($("<option selected></option>",
//<HERE Selected is not working.
//If I remove selected results load in dropdown
{
value: value.id,
text: value.name
}));
});
$('#editApptModal').modal('show');
},
error: function(response) {
alert('Could not displaying data' + response);
}
});
$('#editApptModal').modal('show');
});
});
<select multiple="multiple" name="employees[]" id="form-field-select-4" class="form-control search-select">
<option selected value=""></option>
First you should try to append only once because it's an heavy operation.
And by setting attributes directly seems to work here.
var datas = [
{value: 'toto', text: 'Toto'},
{value: 'titi', text: 'Titi'}
];
var options = '';
$.each(datas, function(key, value) {
options += '<option selected>'+value.text+'</option>';
});
$('#select').append(options);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select multiple id="select"></select>
You have to issue the refresh command after you are done. Here a quick snippet of it working doing the same thing for one of my projects. TransportRecord_TransportCarrierID is the ID for my select element.
$('#TransportRecord_TransportCarrierID').empty();
$.each(jsonResponse, function (key, item) {
var option = $('<option selected>').text(item.Text).val(item.Value);
$('#TransportRecord_TransportCarrierID').append(option);
});
$('#TransportRecord_TransportCarrierID').selectpicker('refresh');
Html
<select class="form-control selectpicker" data-live-search="true" data-style="btn-defaultWhite" multiple="multiple" id="TransportRecord_TransportCarrierID" name="TransportRecord.TransportCarrierID">//your initial options</select>
I'm not sure how to refresh data after I use AJAX. Here's what I already have:
Frontend:
#model TFU.Model.DB_USER
<div id="listTelNumbers">
#foreach (var item in Model.DB_USER_PHONES)
{
<dl class="dl-horizontal">
<dt>
#item.PHONE
</dt>
<dd>
<button id="removeButton" class="btn btn-default" onclick="sendRequestToRemove('#item.USER_ID', '#item.PHONE')">Usuń</button>
</dd>
</dl>
}
</div>
Script - fadeOut works fine but I don't know what should I fadeIn. So I guess is missing a small part of code there.
Also how can I fadeOut only the record which I currently removing instead all list.
<script>
function sendRequestToRemove(id, phone) {
var data = {
"USER_ID": id,
"PHONE": phone
}
$.ajax({
url: '/User/RemoveTelNumber',
data: JSON.stringify(data),
type: 'POST',
contentType: 'application/json; charset=utf-8',
error: function (err) {
alert('Error: ' + err.statusText);
},
success: function (result) {
$('#listTelNumbers').fadeOut(800, function () {
form.html('#listTelNumbers').fadeIn().delay(2000);
});
},
async: true,
processData: false
});
}
</script>
Backend:
public bool RemoveTelNumber(DB_USER_PHONES model)
{
var user = db.DB_USER_PHONES.First(x => x.USER_ID == model.USER_ID && x.PHONE == model.PHONE);
db.DB_USER_PHONES.Remove(user);
db.SaveChanges();
return true;
}
Firstly, your loop is generating duplicating invalid html because of the duplicate id attributes. And you should not be polluting your markup with behavior - use Unobtrusive JavaScript. Change the html to remove the id attribute, add a class name for selection and add data-* attributes for the values to be posted
#foreach (var item in Model.DB_USER_PHONES)
{
<dl class="dl-horizontal">
<dt>#item.PHONE</dt>
<dd><button class="btn btn-default delete" data-id="#item.USER_ID" data-phone="#item.PHONE">Usuń</button></dd>
</dl>
}
Then change the script to
var url = '#Url.Action("RemoveTelNumber", "User")'; // always use Url.Action()
$('.delete').click(function() {
var container = $(this).closest('dl');
var data = { user_Id: $(this).data('id'), phone: $(this).data('phone') };
$.post(url, data, function(response) {
if (response) {
// fadeout, then remove
container.fadeOut(800, function() { $(this).remove(); })
} else {
// Oops - display an error message?
}
}).fail(function() {
// Oops
});
});
And finally, change the action method to return a JsonResult indicating success or otherwise
[HttpPost]
public JsonResult RemoveTelNumber(DB_USER_PHONES model)
{
var user = db.DB_USER_PHONES.First(x => x.USER_ID == model.USER_ID && x.PHONE == model.PHONE);
db.DB_USER_PHONES.Remove(user);
db.SaveChanges();
return Json(true);
// or if something went wrong, return Json(null);
}
I also recommend you rename you classes and properties to follow conventional naming practices - UserPhone, not DB_USER_PHONES, UserId, not USER_ID etc.
Partially reload that div
$("#listTelNumbers").load(location.href + " #dl-horizontal");
Or reload the entire page w/o refreshing it
$(document.body).load(location.href);
For a complete reference I found a demo here Partially load a div without refreshing page in javascript and php.
You can use jQuery to find the <dt> element which was marked for deletion and fade it out(or remove it completely from the DOM):
$.ajax({
url: '/User/RemoveTelNumber',
data: JSON.stringify(data),
type: 'POST',
contentType: 'application/json; charset=utf-8',
error: function (err) {
alert('Error: ' + err.statusText);
},
success: function (result) {
var dtCollection = $("dt");
for (var i = 0; i < dtCollection.length; i++) {
var text = $(dtCollection[i]).text();
text = text.trim();
if (text == phone) {
$(dtCollection[i]).parent().fadeOut('slow');
//$(dtCollection[i]).parent().remove();
}
}
},
async: true,
processData: false
});