On page load call change of events for both dropdown - javascript

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.

Related

Binding a dynamically populated <select> to produce a third

I am trying to create a chain of drop downs in a form. The first select is populating the second form, but I can't call a third from the results. I have figured out (I think) that it is a binding issue, but how would I go about correcting this.
The JavaScript on the page:
<script>
var selected_form_div = null;
var frm_submit_event = function(e){
var $this = $(this); // the button
//var frm = $this.closest(form);
var frm = $('#'+selected_form_div + " form");
console.log(frm);
console.log(frm.serialize());
e.preventDefault();
$.ajax({
type: "POST",
url: "classes/forms/ajaxPost.php",
data: frm.serialize(),
dataType: "text",
success: function($result) {
//var obj = jQuery.parseJSON(data); if the dataType is not specified as json uncomment this
$('#'+selected_form_div).html($result);
},
error: function() {
alert('error handing here');
}
});
}
function loadSubSelects(value,form,select)
{
$.post("classes/forms/update_form.php",{catid : value,form : form,select : select},function(data)
{
jQuery('#sub_categories').html(data);
});
}
$(document).ready(function(){
$('._form_selector').click(function(e){
e.preventDefault();
var $this = $(this);
$.get('classes/forms/forms.php', {
form: $(this).attr('form_data')
},
function($result){
$('#'+$this.attr('form_div')).html($result);
//selected_form_div = $this.closest("form");
selected_form_div = $this.attr('form_div');
//console.log($result);
});
console.log($(this).attr('form_data'));
});
$(document).on("click", '.frm_submit_btn', frm_submit_event);
$('._pay').click(function(){
var $this = $(this);
console.log($this.attr('form_id'));
$('._form_pay').css('display', 'none');
$('#form_'+$this.attr('form_id')+'_pay').css('display','block');
});
});
function showForms(form,click_listen) {
jQuery.noConflict();
jQuery('form').hide();//hide initially
jQuery("#click_listen").click(function(e){
jQuery(form).toggle('fast');//or just show instead of toggle
});
}
function reportError(request) { alert("Something Went Wrong, Please Submit A Support Ticket.");}
</script>
and LoadSubSelects is the function in question, and the PHP results:
What I am trying to bind in the results (I think)
the PHP code:
$query="SELECT letter_id,letter_title FROM letter_template where letter_category_id = $catid";
$result = mysql_query ($query) or die(mysql_error());
echo'<select name="sselect1" class="e1" style="width:100% !important; height: 1.85em !important; color: #a8a8a8 !important; border-color:#d7d7d7 ! onChange="loadSubSelects(this.value,\'write_letter\',this.name)"><option value="0">Please Select A Letter</option>';
// printing the list box select command
while($catinfo=mysql_fetch_array($result)){
//Array or records stored in $nt
echo "<option value=\"".htmlspecialchars($catinfo['letter_id'])."\">".$catinfo['letter_title']."</option>";
}
echo"</select>";
echo htmlspecialchars($catinfo['letter_id']);
Any help would be most appreciated, thanks so much guys :)

On page load call change events?

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');
});

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();
}
}

Dropdown in IE does not refresh in click event

I have a dropdown which has a 'click' event where I call a rest service and update the options in the dropdown using jquery, So the problem is that the options are not getting updated in IE. It works fine in chrome & others.
sample code
<select class="dropdown">
<option value="1">Column1</option>
<option value="2">Column2</option>
</select>
$(.dropdown).click(function () {
var $dropdown = $(this);
var contrId = $(this).attr('id');
var selectedVal = $(this).val();
$($dropdown).empty();
$.ajax({
url: '#Url.Content("~/FakeAPI/GETDATA")',
dataType: "json",
method: 'POST',
data: { 'id': '10' },
}).done(function (data) {
// Clear drop down list
$($dropdown).empty();
// Fill drop down list with new data
var $option = $("<option />");
$option.attr("value", '').text('Select Column');
$($dropdown).append($option);
$(data).each(function () {
// Create option
var $option = $("<option />");
// Add value and text to option
$option.attr("value", this.Text).text(this.Value);
if (selectedVal == this.Text) {
$option.attr("selected", "selected");
}
// Add option to drop down list
$($dropdown).append($option);
});
});
});
}
Any suggestion would be helpful.
Working in I.E 9,10 and 11 tested
$(document).ready(function () {
$(".dropdown").click(function () {
var $dropdown = $(this);
var contrId = $(this).attr('id');
var selectedVal = $(this).val();
$($dropdown).empty();
$.ajax({
url: '#Url.Content("~/FakeAPI/GETDATA")',
dataType: "json",
method: 'POST',
data: {'id': '10'},
}).done(function (data) {
// Clear drop down list
$($dropdown).empty();
// Fill drop down list with new data
var $option = $("<option />");
$option.attr("value", '').text('Select Column');
$($dropdown).append($option);
$(data).each(function () {
// Create option
var $option = $("<option />");
// Add value and text to option
$option.attr("value", this.Text).text(this.Value);
if (selectedVal == this.Text) {
$option.attr("selected", "selected");
}
// Add option to drop down list
$($dropdown).append($option);
});
});
});
});
I think the issue is IE cache requests by mistake. Add cache:false to your ajax request and probably it fix the issue by adding _={timestamp} at the end of your requests.
$.ajax({
cache:false,
url: '#Url.Content("~/FakeAPI/GETDATA")',
dataType: "json",
method: 'POST',
data: { 'id': '10' },

Value posts firstly and then only it finishes input (if clicked). needed backwards(code is corect)

I have dropdown list of country suggestions and input above. When i click on one of them - AJAX should work(and it does) and add value to #msg_native. HTML:
echo '<div class="search_native"><input type="text" name="native_input" id="native"/>';
echo "<div id='output'></div></div>";
All JQUERY :
<script type="text/javascript">
$(document).ready(function() {
$("input").keyup(function(){
$array = ['usa','france','germany'];
$input_val = $("input[name='native_input']").val();
$('#output').text('')
r = new RegExp($input_val)
for (i = 0; i < $array.length; i++) {
if ($array[i].match(r)) {
$('#output').append('<p class="match">' + $array[i] + '</p>')
}
}
});
$(document).on('click', '.match', function(){
$value = $(this).text();
$('#native').val($value);
});
});
</script>
<script type="text/javascript">
$(function() {
$('#native').change(function() {
alert('cl');
$.ajax({
type: "POST",
url: "home.php",
dataType: 'json',
encode: true,
data: {native_input: $("input[name='native_input']").val()},
cache: false,
success: function(data){
alert(data);
$("#msg_native").after(data);
}});
return false;
});
});
</script>
The problem is that the value that gets posted is only what Ive typed myself, regardless on clicked element. But I want complete value- not only typed letters...so it firstly posts value and then 'finishes' the input (if clicked)
What can you practically advice to me?
data: {native_input: $value},
returns empty string
Some of this might be debatable but I put those in place for maintainability of the code and/or to match the most recent jQuery.
Only use one document ready handler (if possible)
Remove all the global objects (put var in front of them)
Use the native id when possible as fastest selector (not $("input[name='native_input']") for instance)
use this in the event handler, not the full selector (see next item)
If I enter "France" not "france" match does not work so need to case that input to equality var $input_val = $(this).val().toLowerCase();
You start with an empty field, might be good to show the match for that - simply trigger the keyup on startup to show all the array: }).trigger('keyup'); Now they are available for your clicking.
Attach the click handler on the wrapper for the "match" elements: $('#output').on('click', '.match', function() {
Use the promise form of the ajax .done(
Create a new custom event instead of the "change" on the native. We can then trigger that event as/when needed (the real issue you describe) Example: $('#native').trigger('myMatch'); and as I use it here:
trigger the event on a full match:
if (jQuery.inArray($input_val, $array) !== -1) {
$(this).trigger('myMatch');
}
Revised code:
$(document).ready(function() {
$("#native").on('keyup', function() {
var $array = ['usa', 'france', 'germany'];
var $input_val = $(this).val().toLowerCase();
$('#output').html('');
var r = new RegExp($input_val);
for (var i = 0; i < $array.length; i++) {
if ($array[i].match(r)) {
$('#output').append('<p class="match">' + $array[i] + '</p>');
}
}
// full match entered, trigger the match
if (jQuery.inArray($input_val, $array) !== -1) {
$(this).trigger('myMatch');
}
}).on('myMatch', function() {
alert('cl');
var nativeMatch = {
native_input: $("#native").val()
};
$.ajax({
type: "POST",
url: "home.php",
dataType: 'json',
encode: true,
data: nativeMatch,
cache: false
}).done(function(data) {
alert(data);
$("#msg_native").after(data);
});
return false;
}).trigger('keyup');
$('#output').on('click', '.match', function() {
var $value = $(this).text();
$('#native').val($value).trigger('myMatch');
});
});

Categories