I'm using jquery-template and i need make an option selected, according json's value.
Javascript:
$.ajax({
type: 'POST',
url: caminho + '/controller/ctrl_usuario.php',
data: 'acao=buscarUsuarioPorId&idUsuario=' + id,
dataType: 'json',
success: function (response) {
if (response.status == 1) {
//$('.cadastro').append(response.dados);
$("#" + id).loadTemplate(caminho + "cadastro/form-usuario.php", response.dados, {error: function (e) {
console.log(e);
}});
}
},
complete: function () {
//code
}
});
json returned:
"dados":[{"nome":"Maria Silva","l_Sexo":"F"}]"
<div class="wrp-inp">
<label for="genero">GĂȘnero:</label>
<span class="icon-chevron-down"></span>
<select name="genero" id="genero" >
<option value="M" {{if l_Sexo == 'M'}}selected{{/if}}>Male</option>
<option value="F" {{if l_Sexo == 'F'}}selected{{/if}}>Female</option>
</select>
</div>
The sample above didn't work.
Just do:
var value = 'M';
$('select[name="genero"]').val(value);
The complete Solution:
Javascript:
$.ajax({
type: 'POST',
url: caminho + '/controller/ctrl_usuario.php',
data: 'acao=buscarUsuarioPorId&idUsuario=' + id,
dataType: 'json',
success: function (response) {
if (response.status == 1) {
$("#" + id).loadTemplate(caminho + "cadastro/form-usuario.php", response.dados, {error: function (e) {
console.log(e);
}});
var sexo = response.dados[0].l_Sexo;
$("#genero").val(sexo);
}
},
complete: function () {
//code
}
});
HTMl:
<div class="wrp-inp">
<label for="genero">GĂȘnero:</label>
<span class="icon-chevron-down"></span>
<select name="genero" id="genero" >
<option value="M">Masculino</option>
<option value="F">Feminino</option>
</select>
</div>
Related
I have a two onchange function for a page called create delivery request. One is when the dropdownlist of receiver changes, then it should show the phone number & address of receiver selected. Another one is when the dropdownlist of delivery item changes, then it should set the max attribute for the quantity.
The url of both these are linked to the customized OnGet method in razor page.
However, usually the above Onget method is hit but the below one is not. And the above OnGet method can't get the dryfood with the passed ID as well, it is null inside. And the two jQuery ajax function doesn't work at all. I'm totally a beginner. Hope that there is someone who can help me. Thanks in advance.
In create.cshtml:
<div class="mb-3">
Receiver Name
<select id="receiver" asp-for="Delivery.ReceiverID" asp-items="Model.ReceiverList" class="form-control">
<option>--Select the Receiever--</option>
</select>
</div>
<div class="mb-3">
Receiver Phone
<span id="receiverphone" class="form-control">----</span>
</div>
<div class="mb-3">
Receiver Address
<div id="receiveradrs1" class="form-control">----</div>
<div id="receiveradrs2" class="form-control">----</div>
</div>
<div class="mb-3">
Delivery Item
<select id="deliveryitem" asp-for="DeliveryItem.DryFoodID" asp-items="Model.DeliveryItemList" class="form-control">
<option>--Select Delivery Item--</option>
</select>
</div>
<div class="mb-3">
Quantity
<input id="quantity" asp-for="DeliveryItem.Quantity" min="1" class="form-control" />
</div>
In create.csthml.cs, two customized OnGet method here:
public async Task<IActionResult> OnGetSetMaxQuantity(int id)
{
List<DryFoodDonation> dfdlist = await _db.DryFoodDonation.ToListAsync();
var dryfood = dfdlist.Where(d => d.Id == id).FirstOrDefault();
Debug.WriteLine(dryfood.DryFoodName + " " + dryfood.DryFoodRemainQuantity);
return new JsonResult(dryfood.DryFoodRemainQuantity);
}
public async Task<IActionResult> OnGetGetPhoneAdrs(int id)
{
List<User> receiverlist = await _db.User.Where(u => u.UserType.TypeID == 3).ToListAsync();
var selectreceiver = receiverlist.Where(d => d.UserID == id).FirstOrDefault();
Debug.WriteLine(selectreceiver.UserName + " " + selectreceiver.UserPhone);
return new JsonResult(selectreceiver);
}
The jQuery AJAX function in a JavaScript file:
$(document).ready(function () {
$("#receiver").change(function () {
alert('Yes receiver here changed.');
var item = $(this).val();
$.ajax({
type: 'GET',
url: 'Create/?handler=GetPhoneAdrs',
beforeSend: function (xhr) {
xhr.setRequestHeader("XSRF-TOKEN",
$('input:hidden[name="__RequestVerificationToken"]').val());
},
data: {
'id': item
},
contentType: 'application/json; charset=utf-8',
dataType: 'json',
success: function (data) {
$('#receiverphone').html(data.UserPhone);
$('#receiveradrs1').html(data.UserAdrs1);
$('#receiveradrs2').html(data.UserAdrs2);
}
});
});
$("#deliveryitem").change(function () {
alert('Yes item here changed.');
var item = $(this).val();
$.ajax({
type: 'GET',
url: 'Create/?handler=SetMaxQuantity',
beforeSend: function (xhr) {
xhr.setRequestHeader("XSRF-TOKEN",
$('input:hidden[name="__RequestVerificationToken"]').val());
},
data: {
"id": item
},
contentType: 'application/json; charset=utf-8',
dataType: 'json',
success: function (data) {
$("#quantity").attr({
"min": 1,
"max": data
});
}
});
});
});
Please help me with this. I can't solve this problem for a few weeks. Thank you!
// cshtml.cs
const sendMe = async function (someData) {
$.ajax({
type: 'POST',
dataType: 'json',
url: '/ControllerName/MethodNameInController',
data: { someData: someData },
success: function (response) {
if (response != null && response.statusCode == 200) {
..
} else {
..
}
}
});
}
//Controller
[HttpPost("MethodNameInController")]
public IActionResult MethodNameInController([FromForm] string someData) {
..
}
I have a Dropdown created in Html as like this.
<label for="filter">Type:</label>
<select class="filter"
id="secquneceDropdownId">
<option value="" selected>All</option>
<option value="INSEQUENCE">In Sequence</option>
<option value="OUTSEQUENCE">Out Sequence</option>
<option value="RECIPES">Sequence Mapping</option>
</select>
I have tried to send selected value in jQuery as same as the Ajax JSON format. but I always get the null value in the backend.
Both ways are here,
Using jQuery:
$(document).ready(function () {
$("#secquneceDropdownId").change(function () {
var dropdownSelected = $(this).val();
console.log('dropdownSelected value is' + dropdownSelected);
$.post("/IdeaOfThings/listSequences", {
isDropdownSelected : dropdownSelected
},
function(data, status) {
});
});
});
In Ajax format:
$(document).ready(function () {
$("#secquneceDropdownId").change(function () {
var dropdownSelected = $(this).val();
console.log('dropdownSelected value is' + dropdownSelected);
$.ajax({
type: "POST",
url: '/IdeaOfThings//listSequences',
data: {isDropdownSelected: dropdownSelected},
dataType: "json",
success: function(data){
if(data.success==true){
alert('success');
}else if(data.success==false){
alert('Failed');
}
}
});
});
});
Why I`m getting null value as always.?
Maybe try changing
data: {isDropdownSelected: dropdownSelected}
to
data: {'isDropdownSelected': dropdownSelected}
html
<label>Customer PO</label>
<select name="Customer_PO" class="form-control" id="Customer_PO" >
<option value="" >Customer PO</option>
</select>
-------------
jquery
$('body').on('click','#Customer_PO',function(e){
id_tosend=$(this).attr("id").toString();
var cust_id=$('#Customer_list').val();
var a=$('#'+id_tosend).select2({
ajax: {
url: 'ajax/report/inspection_report.php?cust_id='+cust_id,
dataType: 'json',
delay: 500,
data: function (params) {
var queryParameters = {
q: params.term
}
return queryParameters;
},
processResults: function (data) {
return {
results: data
};
},
cache:true
}
});
a.data('select2').dropdown.$dropdown.addClass("test");
$(this).select2('open');
});
i attach plugin of Select2 .When i submitted data in my form ,it shown me empty value . How i get this value to set selected initial value in ajax method.
you can try this
HTML
<label>Customer PO</label>
<select name="Customer_PO" class="form-control" id="Customer_PO" >
<option value="" >Customer PO</option>
</select>
JQUERY
$.ajax({
url: 'url',
type: 'POST',
data: { id: id},
dataType: 'JSON',
success: function (resp) {
if(resp.msg == 'Done'){
$("#Customer_PO option:selected").removeAttr("selected");
$.each(resp.yourListData, function (key, value) {
$("#Customer_PO ").append('<option value="'+value.ID+'">'+value.name+'</option>');
});
$("#Customer_PO ").trigger("change", [true]);
}
},
error: function (e) {
console.log("Line 1204");
console.log(e.responseText);
}
});
I have two radio buttons - 'Italian' & 'Spanish'. When one is selected, I wont the autocomplete for 'Main' and 'Starter' inputs to be populated from different files. So when 'Spanish' is checked, it does autocomplete from http://xxx/spanish.php, and when 'Italian' is check, it does it from http://xxx/italian.php.
var radio1 = document.getElementById("radio1");
var radio3 = document.getElementById("radio3");
if (radio1.checked){
alert("radio1 selected");
//Starter Autocomplete (Spanish)
var starterSearchData;
$(function() {
$.ajax({
url: "http://learn.cf.ac.uk/webstudent/sem5tl/javascript/assignments/spanish.php",
dataType: "jsonp",
async: false,
success: function(data) {
starterSearchData = $.map(data, function(item) {
if (item.course == "starter")
return item.name;
});
EnableAutoComplete();
},
error: function(xhr, status, error) {
var err = eval("(" + xhr.responseText + ")");
alert(err.Message);
}
});
function EnableAutoComplete() {
$("#starter").autocomplete({
source: starterSearchData,
minLength: 2,
delay: 010
});
}
});
//Main Autocomplete (Spanish)
var mainSearchData;
$(function() {
$.ajax({
url: "http://learn.cf.ac.uk/webstudent/sem5tl/javascript/assignments/spanish.php",
dataType: "jsonp",
async: false,
success: function(data) {
mainSearchData = $.map(data, function(item) {
if (item.course == "main")
return item.name;
});
EnableAutoComplete();
},
error: function(xhr, status, error) {
var err = eval("(" + xhr.responseText + ")");
alert(err.Message);
}
});
function EnableAutoComplete() {
$("#main").autocomplete({
source: mainSearchData,
minLength: 2,
delay: 010
});
}
});
}else if (radio3.checked) { .... same code, except url changed to http://xxx/italian.php... }
HTML:
<div id="radio">
<input type="radio" id="radio1" name="radio"><label for="radio1">Spanish</label>
<input type="radio" id="radio3" name="radio"><label for="radio3">Italian</label>
</div>
<label for="starter">Choose starter</label>
<input type="text" name="starter" id="starter"><br>
<label for="main">Choose main</label>
<input type="text" name="main" id="main"><br>
The ajax call, etc, works, but when i try the if statement, the fields do not populate/autocomplete.
Thanks.
You could use the value of the radio as the url in ajax. And retrieve checked value via jquery selector.
//Starter Autocomplete (Spanish)
var starterSearchData;
$(function() {
$.ajax({
url: $("#radio input:checked").val(),
dataType: "jsonp",
async: false,
success: function(data) {
starterSearchData = $.map(data, function(item) {
if (item.course == "starter")
return item.name;
});
EnableAutoComplete();
},
error: function(xhr, status, error) {
var err = eval("(" + xhr.responseText + ")");
alert(err.Message);
}
});
function EnableAutoComplete() {
$("#starter").autocomplete({
source: starterSearchData,
minLength: 2,
delay: 010
});
}
});
//Main Autocomplete (Spanish)
var mainSearchData;
$(function() {
$.ajax({
url: $("#radio input:checked").val(),
dataType: "jsonp",
async: false,
success: function(data) {
mainSearchData = $.map(data, function(item) {
if (item.course == "main")
return item.name;
});
EnableAutoComplete();
},
error: function(xhr, status, error) {
var err = eval("(" + xhr.responseText + ")");
alert(err.Message);
}
});
function EnableAutoComplete() {
$("#main").autocomplete({
source: mainSearchData,
minLength: 2,
delay: 010
});
}
});
HTML:
<div id="radio">
<input type="radio" id="radio1" name="radio" value="http://learn.cf.ac.uk/webstudent/sem5tl/javascript/assignments/spanish.php"><label for="radio1">Spanish</label>
<input type="radio" id="radio3" name="radio" value="http://learn.cf.ac.uk/webstudent/sem5tl/javascript/assignments/italian.php"><label for="radio3">Italian</label>
</div>
<label for="starter">Choose starter</label>
<input type="text" name="starter" id="starter"><br>
<label for="main">Choose main</label>
<input type="text" name="main" id="main"><br>
I have tried a lot of ways to fix this problem.
At a dynamic list loaded via ajax, I can't make allowClear work.
Here is my jsFiddle
HTML:
<select id="first" class="init-select2" data-placeholder="First dropdown" data-allowclear="true">
<option></option>
<option>First option</option>
<option>Second option</option>
</select>
<select id="second" class="init-select2" data-placeholder="Second Dropdown" data-allowclear="true" disabled="disabled">
<option></option>
</select>
Javascript:
$(function() {
$('.init-select2').removeClass('init-select2').each(function(){
if ($(this).attr("data-allowclear") && $(this).attr("data-allowclear") == "true"){
$(this).select2({
allowClear: true
});
} else if ($(this).attr("data-allowclear") && $(this).attr("data-allowclear") == "false") {
$(this).select2({
allowClear: false
});
}
});
$('#first').change(function () {
var options = [];
$.ajax({
type: "POST",
url: "/echo/json/",
data: {"json":JSON.stringify({"one":"first","two":"second","three":"third"})},
cache: false,
success: function(data) {
$.each(data, function (index, value) {
options.push("<option>" + value + "</option>");
$("#second").find('option').remove().end().append(options).attr("disabled", false).select2({ allowClear: true });
});
}
});
});
});
in jsfiddle are already added the select2 javascript and css, please have a look there
Fixed by adding an "<option></option>" to second dropdown each time I change the value of first dropdown. See success handler below:
$('#first').change(function () {
var options = [];
$.ajax({
type: "POST",
url: "/echo/json/",
data: {
"json": JSON.stringify({
"one": "first",
"two": "second",
"three": "third"
})
},
cache: false,
success: function (data) {
options.push("<option></option>");
$.each(data, function (index, value) {
options.push("<option>" + value + "</option>");
$("#second").find('option').remove().end().append(options).attr("disabled", false).select2({
allowClear: true
});
});
}
});
});
Example of one of my own, as you can see I don't use "option" tags within my loop.
function companyURL() {
if ($.isNumeric($('#supplier_select').val())) {
return company_url + '/' + $('#supplier_select').val() + '/';
} else {
return company_url;
}
}
var results = [];
$('.company_select').select2({
ajax: {
url: function () {
return companyURL();
},
dataType: 'json',
quietMillis: 100,
data: function (term) {
return {
term: term
};
},
results: function (data) {
results = [];
results.push({
id: '',
text: 'Select a company'
});
$.each(data, function (index, item) {
results.push({
id: item.company_id,
text: item.company_name
});
});
return {
results: results
};
}
}
});