On page load call change events? - javascript

On page load I need to call change events for the drop down list. Currently what happens is in my Jquery code below when you select a value from the professions drop down list i.e. GP a Help text then below the drop down shows in a DIV area shows, however once you submit the form and if validation is thrown the help text goes from the view.
I need to call change events for the drop down list #profession but not exactly sure how to do this. Please advise
$('#profession').on('change', function (e) { //Gets the ID of profession drop down list
var selectedVal = $(this).val(); //Variable selectedVal this . value
$.ajax({ //Ajax declared
type: 'GET', //Its a get
url: "#Url.Action("GetenquiryTypes", "UnauthEnquiry")", //It goes to the enquiry controller method GetenquiryTypes
dataType: 'json', //Datatypes JSON
data: { SelectedProfession: selectedVal }, //data is SelectedProfession: selectedVal
success: function (json) { //Jquery Parse Json data from server on ajax success
if (json.helptext != undefined && json.helptext != '')
{
$('#ProfHelp').html(json.helptext)
$('#ProfHelpAlert').show(); ///////
}
else
$('#ProfHelpAlert').hide(); ///////
var targetDropdown = $('#enquirytype') //Var targetDropDropdown goes to dropdown ID enquiry type
targetDropdown.empty(); //target empty dropdown
$("<option />", {
val: "",
text: "Please select enquiry type" //Select enquiry type
}).appendTo(targetDropdown); //add to the target dd
if (json.enquiryTypes.length > 0) { //if JASON data from server greater then 0
for (var EnquiryType in json.enquiryTypes) { //go through each EnquiryType in JSON
$("<option />", {
val: json.enquiryTypes[EnquiryType].EnquiryId, //mapping
text: json.enquiryTypes[EnquiryType].Enquiryname //mapping
}).appendTo(targetDropdown); //add to drop down
};
}
targetDropdown.change();
}
});
});

Try this:
$(document).ready(function() {
$('#profession').trigger('change');
});

Related

Display sub-category data from database to cascading dropdown list

I got a cascading dropdown list in my "Create" view, which after the first dropdown #regions is selected, the second dropdown #districts will render a list of districts in that region.
How can I return the "District" value from the DB to the #districts dropdown list in the "Edit" view when it is first loaded? I can only have my Region value showing, but blank for District value.
The problem of my code is that the "District" dropdown list is only populated when the "Region" dropdown list is changed/selected.
I searched through a lot of post about this but all of them are talking about how to make a cascading dropdown list, but not displaying data from DB.
In Edit controller:
var item = await _context.Items
.Include(i => i.District)
.SingleOrDefaultAsync(i => i.ID == id);
var model = new ViewModel { Title = item.Title, RegionID = item.District.RegionID, DistrictID = item.DistrictID };
List<Region> regions = new List<Region>();
regions = await _context.Regions.ToListAsync();
regions.Insert(0, new Region { ID = 0, Name = "-- Select a region --" });
List<District> districts = new List<District>();
ViewBag.RegionList = new SelectList(regions, "ID", "Name");
ViewBag.DistrictList = new SelectList(districts, "ID", "Name");
return View(model);
In Edit View:
<script type="text/javascript">
$(function () {
if ($("#regions").val() == '0') {
var districtDefaultValue = "<option value=''>-- Select a district --</option>";
$("#districts").html(districtDefaultValue).show();
}
$("#regions").change(function () {
var selectedItemValue = $(this).val();
var ddlDistrict = $("#districts");
$.ajax({
cache: false,
type: "GET",
url: '#Url.Action("GetDistrictByRegionId", "Items")',
data: { "id": selectedItemValue },
success: function (data) {
ddlDistrict.html('');
$.each(data, function (id, option) {
ddlDistrict.append($('<option></option>').val(option.id).html(option.name));
});
},
error: function (xhr, ajaxOptions, thrownError) {
alert('Error occurred in loading corresponding districts.');
}
});
});
});
I have no idea why there is someone votes -ve for my question rather than offering help or idea. Anyway I figure out a way to solve it. Hope this could help someone else.
In the javascript I simply get the DistrictID from the Model that passed to the view.
var selectedDistrict = #Model.DistrictID;
Then in the $.each function I make a conditional statement to make the saved district as selected:
$.each(data, function (id, option) {
if (option.id == selectedDistrict) {
ddlDistrict.append($('<option selected="selected"></option>').val(option.id).html(option.name));
} else {
ddlDistrict.append($('<option></option>').val(option.id).html(option.name));
}
});
Then it works like a charm.

If contains help text display on view?

Currently I have a div class by default displaying none, however I want the value from help text if it contains the help text. I think something like if value from dropdown contains help text display.show
Below is my div
<div class="alert alert-info col-md-12" id="ProfHelpAlert" role="alert" style="display:none">
<i class="fa fa-info-circle" aria-hidden="true"></i>
<strong class="notification" id="ProfHelp"></strong>
</div>
This is my JavaScript
$('#profession').on('change', function (e) { //Gets the ID of profession drop down list
var selectedVal = $(this).val(); //Variable selectedVal this . value
$.ajax({ //Ajax declared
type: 'GET', //Its a get
url: "#Url.Action("GetenquiryTypes", "UnauthEnquiry")", //It goes to the enquiry controller method GetenquiryTypes
dataType: 'json', //Datatypes JSON
data: { SelectedProfession: selectedVal }, //data is SelectedProfession: selectedVal
success: function (json) { //Jquery Parse Json data from server on ajax success
$('#ProfHelp').html(json.helptext);
var targetDropdown = $('#enquirytype') //Var targetDropDropdown goes to dropdown ID enquiry type
targetDropdown.empty(); //target empty dropdown
$("<option />", {
val: "",
text: "Please select enquiry type" //Select enquiry type
}).appendTo(targetDropdown); //add to the target dd
if (json.enquiryTypes.length > 0) { //if JASON data from server greater then 0
for (var EnquiryType in json.enquiryTypes) { //go through each EnquiryType in JSON
$("<option />", {
val: json.enquiryTypes[EnquiryType].EnquiryId, //mapping
text: json.enquiryTypes[EnquiryType].Enquiryname //mapping
}).appendTo(targetDropdown); //add to drop down
};
}
}
});
});
Are you saying you want to show your help message when the ajax method succeeds? If so, is this what you are looking for?
success: function(json) {
//... add to end of method
if(json.helptext) {
$('#ProfHelpAlert').show();
}
}
Do you need a comparison to the value of the select?
success: function(json) {
//... add to end of method
if(json.helptext == selectedVal) {
$('#ProfHelpAlert').show();
}
}

On page load call change of events for both dropdown

On first time page load, help text and announcements are displayed, on refresh after validation the help text and announcement don't show again on the view. I think I need to on page load call change event for both drop down, I'm not quiet sure how to do this. The first dropdown Div id is #profession and the second drop down is div id is #enquirytype.
$('#profession').on('change', function (e) { //Gets the ID of profession drop down list
var selectedVal = $(this).val(); //Variable selectedVal this . value
$.ajax({ //Ajax declared
type: 'GET', //Its a get
url: "#Url.Action("GetenquiryTypes", "UnauthEnquiry")", //It goes to the enquiry controller method GetenquiryTypes
dataType: 'json', //Datatypes JSON
data: { SelectedProfession: selectedVal }, //data is SelectedProfession: selectedVal
success: function (json) { //Jquery Parse Json data from server on ajax success
if (json.helptext != undefined && json.helptext != '')
{
$('#ProfHelp').html(json.helptext)
$('#ProfHelpAlert').show(); ///////
}
else
$('#ProfHelpAlert').hide(); ///////
var targetDropdown = $('#enquirytype') //Var targetDropDropdown goes to dropdown ID enquiry type
targetDropdown.empty(); //target empty dropdown
$("<option />", {
val: "",
text: "Please select enquiry type" //Select enquiry type
}).appendTo(targetDropdown); //add to the target dd
if (json.enquiryTypes.length > 0) { //if JASON data from server greater then 0
for (var EnquiryType in json.enquiryTypes) { //go through each EnquiryType in JSON
$("<option />", {
val: json.enquiryTypes[EnquiryType].EnquiryId, //mapping
text: json.enquiryTypes[EnquiryType].Enquiryname //mapping
}).appendTo(targetDropdown); //add to drop down
};
}
targetDropdown.change();
}
});
});
$('#enquirytype').on('change', function (e) { //onlick of professions DD
var selectedVal = $(this).val(); //Variable selectedVal this .value
$('#enquiryTypeHelpAlert').hide(); ///////
$('#EnquiryTypeAnnouncements').empty();
if (selectedVal != undefined && selectedVal != '') {
$.ajax({
type: 'GET', //Get
url: "#Url.Action("GetEnquiryTypeAndAnnoncements", "UnauthEnquiry")", //It goes to the enquiry controller method GetenquiryTypes
dataType: 'json', //Datatypes JSON
data: { SelectedEnquiryType: selectedVal }, //data is SelectedProfession: selectedVal
success: function (json) { //Jquery Parse Json data from server on ajax success
if (json.helptext != undefined && json.helptext != '') {
$('#enquiryTypeHelp').html(json.helptext)
$('#enquiryTypeHelpAlert').show(); ///////
}
else
$('#enquiryTypeHelpAlert').hide(); ///////
var announcement = $('.EnquiryTypeAnnouncement:first').clone();
$('#EnquiryTypeAnnouncements').empty();
$('#enquiryTypeHelp').html(json.helptext);
for (var i in json.announcements) {
var announcementCopy = announcement.clone();
announcementCopy.find(".notification").html(json.announcements[i]);
$(announcementCopy).appendTo($('#EnquiryTypeAnnouncements')).show();
$('#EnquiryTypeAnnouncements').show();
}
}
});
}
});
That seems correct as on change will keep your DD help text loaded.
$(document).ready(function () {
$('#profession').change(); //Keeps profession dropdown list help text displayed
});
As its not in the Jquery you have to get it from the model.
var EnquiryType ='#Model.EnquiryType
Then get it in the change event.
In the beginning of ypur script call your Professions dropdown in a function such as
$(document).ready(function () {
$('#profession').change(); //Keeps profession dropdown list help text displayed
});
Next as the enquiry type is not available in Jquery. you have get that from Model. By using
var EnquiryType ='#Model.EnquiryType
Then get it in the change event.

Javascript works fine with a hard-coded string but not with variable

I have a problem I have bee struggling over all morning so I felt it was time to get some help! I have a javascript function which gets the value entered by a user into an autocomplete box, uses AJAX to send that value to a php script which queries the database and then populates the following box with the possible options. The problem is this all works fine when I hard-code in the selected option as so:
var selected="Ed Clancy";
but not when it pulls it from the box, as so:
var selected = this.getValue();
I have tried debugging this using an alert box and both boxes come up with the same string in them so I am completely puzzled! Any ideas? Full code below:
$(riderSelected).on('selectionchange', function(event){
var selected = this.getValue();
//var selected="Ed Clancy";
alert(selected);
$('#nap4').removeAttr('disabled');
$('#nap4').empty();
$('#nap4').append($("<option>-select-</option>"));
$.ajax({
type: "GET",
url: 'getbiketype.php',
data: { name: selected },
success: function(data) {
console.log(data);
$('#nap4').append(data);
}
});
});
Based on magicsuggest documentation - http://nicolasbize.com/magicsuggest/doc.html , you probably could do this
var selected = this.getValue()[0];
IF you do not allow multiple selection
Change your code as I have written below for you .
Code
$(riderSelected).on('change', function (event) {
var selected = this.value;
alert(selected);
$('#nap4').removeAttr('disabled');
$('#nap4').empty();
$('#nap4').append($("<option>-select-</option>"));
$.ajax({
type: "GET",
url: 'getbiketype.php',
data: {name: selected},
success: function (data) {
console.log(data);
$('#nap4').append(data);
}
});
});

post multiple checkbox with $.ajax

i'm trying to post a form containing an input text, a textarea, and 14 checkbox with ajax. The idea is to insert some data according to the number of checked checkbox into table dbdata.
Here is the script.js :
$(document).on('click', '#save', function(event) {
//action
var url = "aksi.php";
//an input text
var v_id = $('input:text[name=id]').val();
//a textarea
var v_note = $('#note').val();
//some checkboxes
var v_checkbox =[]
$("input[name='checkbox[]']:checked").each(function ()
{
v_checkbox.push(parseInt($(this).val()));
});
//ajax
$.ajax({
url: url,
type: "POST",
data: {id: v_id,note: v_note,checkbox:v_checkbox },
success: function (data, status){
alert("success!")
},
error: function(xhr,err){
alert("readyState: "+xhr.readyState+"\nstatus: "+xhr.status);
alert("responseText: "+xhr.responseText);
}
});
});
This is the aksi.php :
require "../../config/db.php";
$id=$_POST['id'];
$checkbox= $_POST['checkbox'];
$note=$_POST['note'];
foreach ($checkbox as $key => $check_box) {
mysqli_query($con,"INSERT INTO dbdata(id, checkbox, note) VALUES($id, $check_box, '$note')");
}
The problem is the data never posted. The ajax thrown error (readyState=0, status=0) and data not inserted. The url also changed to :
index.php?checkbox[]=3&checkbox[]=4&checkbox[]=5
depend on which checkbox are checked. Any idea?
Can you put one echo statement at the last in php file for resolving the error issue. like
echo 1;
Update the first line like this if save is the submit button:
$(document).on('click', '#save', function(event) {
event.preventDefault();
.....
});
For resolving the db insertion issue, try include the full path of the required file instead of relative path.

Categories