JQuery Radio Button checked and change event - javascript

In my ASP.NET MVC application there are two radio buttons and one combo box.
Someone clicked to radiobutton 1, combo box load some data. If clicked to the radiobutton 2, loads different data to the combo box. Script was written using the ajax.
The code is working fine when User click changed the radio buttons. But for some users I have hidden the radiobutton 2. So for them only radiobutton 1 is visible, But at that situation, there is no data loaded to the combo box.
Want to know that also, If there is radiobutton checked when load the view, need to get related data to the combobox.
$(function() {
$('[id*=ddlTopEmployees]').select2().next().hide();
$('[id*=Approve_Type]').change(function() {
setDropDownProductsA($(this).val())
});
});
function setDropDownProductsA(xVal) {
try {
$("#ddlEmployees").empty().trigger("change")
$.ajax({
url: '../FindProductTypes',
type: 'POST',
dataType: 'json',
cache: false,
async: false,
data: {
AppLvlId: xVal
},
success: function(data) {
if (data.Success == true) {
$("#ddlEmployees").select2({
width: '100%',
data: JSON.parse(data.items)
});
}
}
});
} catch (err) {
console.log(err.message)
}
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>

use click instead of change
$('[id*=Approve_Type]').click(function() {
setDropDownProductsA($(this).val())
});

Related

Automatically select the option in jquery select2, if only one option is present in dropdown, without clicking it, on page load

I have written the following select2 code:
$('#dropdownElem').select2({
placeholder: 'Select From Dropdown',
allowClear: true,
ajax: {
quietMillis: 10,
cache: false,
dataType: 'json',
type: 'GET',
url: function(){
return '/api/'
},
data: function (params) {
return {
model__icontains: params.term
};
},
processResults: function(data) {
if (data['modelDocs'].length == 1) {
$("#dropdownElem").append($("<option />")
.attr("value", data['modelDocs'][0].id)
.html(data['modelDocs'][0].text)
).val(data['modelDocs'][0].id).trigger("change");
}
return {
results: $.map(data['modelDocs'], function(obj) {
return {
id: obj.id,
text: obj.modelDoc
};
})
};
},
},
});
$('#dropdownElem').trigger("change.select2");
Now what I want to do is if the options returned by ajax call are only one then I should make that option selected automatically and if it is greater than one then the user can select the required by clicking.
For a single option I want it to be selected automatically without clicking. When I console logged the processResults it is being called only on clicking the dropdown and not on loading the page widget where this dropdown is shown.
How can I get the desired result?
Since I could not find a way to trigger click on select2 on page load, my solution was to add these lines on page load or whenever the widget containing that select2 is called in a function:
$('#dropdownElem').select2('open');
$('#dropdownElem').select2('close');
So since I am checking the length of options in processResults, I had to trigger click and close functionality on the dropdown.
select2 has methods open and close to replicate almost the same for my use case.

How can I fill all data in select2 (4.0) when page loaded?

I am using select2 plugin (v.4.0).
What I am trying to do:
$("#search-input-chains").select2({
placeholder: "Unit",
theme: "bootstrap4",
allowClear: true,
initSelection: function (element, callback) {
callback({id: 1, text: 'Text'});
},
ajax: {
url: function () {
return getURLForFilial();
},
dataType: 'json',
delay: 250,
processResults: function (response) {
console.log(response);
return {
results: response
};
},
cache: false
}
});
function getURLForFilial() {
return '/user/rest/data/entry/units/branches?type=1';
}
I need to understand, whether my control has data retrieved from DB or not, and if there is no data - this select list shall not be activated.
I found how I can understand the data amount:
$("#search-input-chains").data().select2.results.$results[0].childNodes.length
(maybe there is another way that is much better?)
But this piece of code returns 0 until I will activate (click) on the select2 box and trigger AJAX request to find data.
I read a lot about how can I perform the pre-call off AJAX, but it doesn't work.
I tried to trigger event on select2 in such a way:
$("#search-input-chains").val().trigger('change');
Please, advice, how can I load data to my select2 control with the page load to understand whether I need to disable this select or not?
I've made it via AJAX:
ajax({
type: 'GET',
url: '/user/rest/data/entry/units/branches?type=1'
}).then(function (data) {
if (data.length !== 0) {
chainsSelectElement.prop("disabled", false);
chainSelectorHasData = true;
} else {
// create the option and append to Select2
let option = new Option('Nothing', 'null', true, true);
chainsSelectElement.append(option);
chainSelectorHasData = false;
chainsSelectElement.prop("disabled", true);
}
getDataForSubdivisions();
});

X-Editable Save With A Custom Button

Here is a link to my fiddle:
https://jsfiddle.net/v58breo8/1/
I was wondering if id was possible to save my updated input to the page by clicking the save button. If you try to edit and then click save then the text will not have been changed.
I would also like the user to only be able to save their text when they hit the save button, right now if you hit enter after editing then it will act normally and the text will change.
Here is my JQuery:
$.fn.editable.defaults.mode = 'inline';
$.fn.editable.defaults.showbuttons = false;
$.fn.editable.defaults.type = 'text';
$('#edit-btn').click(function(e){
e.stopPropagation();
$('#username').editable('toggle');
$('#edit-btn').addClass('hidden');
$('#save-btn').removeClass('hidden');
});
$('#save-btn').click(function(){
$('#username').editable({
success: function (response, newValue) {
return $.ajax({
type: 'POST',
data: { user: newValue},
url: '/post'
});
},
name: 'username',
pk: 1,
placement: 'top',
type: 'text',
toggle: 'manual'
});
$('#edit-btn').removeClass('hidden');
$('#save-btn').addClass('hidden');
});

How to submit a form after confirming submit? jQuery, AJAX

Good day, I have a simple html page containing this form:
<form:form method="post" action="details" modelAttribute="code">
<form:input path="code"/>
<br/>
<input type="submit" value="Submit" />
</form:form>
When I press the Submit button I need to check whether there are some records in the database for given code using jQuery AJAX. If yes then popup jQuery UI dialog to ask user whether he really wants to display record details (because it's a paid service). If he confirms I need to submit the form. This is my script on the html page:
$(document).ready(function() {
// Bind an event handler to the submit event
$('form#code').submit( function() {
// Check whether there are some records in the DB using AJAX
$.ajax({
url: 'getResultCount',
type: 'post',
dataType: 'html',
data: $("form#code").serialize(),
success: function(result) {
if(result == 'null') {
$('div#results').html('<p>No records found for ' + $('input#code').val() + '.</p>');
} else {
// At leat one record was found so ask the user
$('#dialog-confirm').dialog({
resizable: false,
draggable: false,
height: 240,
width: 450,
modal: true,
buttons: {
"Display details": function() {
// User confirmed, submit the form
$('form#code').submit();
},
Cancel: function() {
$(this).dialog("close");
}
}
});
}
}
});
return false;
});
});
When I press "Display details" button nothing happens. I think it is because I'm entering the same submit handler which returns false. How to solve it so that form submit is executed? Please advise.
Thank you in advance.
Vojtech
Change
$('form#code').submit();
to
$('form#code')[0].submit();
It will skip the jQuery onsubmit function.
Basic example: http://jsfiddle.net/4Ax6m/
There is one simple answer: Do not use <input type="submit" ... />.
You can instead use <button onlick="handler()">Submit</button>, where handler() is your function bound to the submit-event of the form in the above code. If your handler decides that the form should be submitted just submit it programmatically. Edit: Which is actually already in your code.
You'd need to wait for the .ajax to succeed since it is currently running in async mode.
So disable it using the async option on ajax. Documentation Here
ANSWER SPECIFICALLY FOR YOU
JS
$(document).ready(function () {
// Bind an event handler to the submit event
$('form#code').submit(function () {
// Check whether there are some records in the DB using AJAX
$.ajax({
url: 'getResultCount',
type: 'post',
dataType: 'html',
data: $("form#code").serialize(),
async: false,
success: function (result) {
if (result == 'null') {
$('div#results').html('<p>No records found for ' + $('input#code').val() + '.</p>');
//No Records found, submitting!!
return true;
} else {
// At leat one record was found so ask the user
$('#dialog-confirm').dialog({
resizable: false,
draggable: false,
height: 240,
width: 450,
modal: true,
buttons: {
"Display details": function () {
// User confirmed, submit the form
return true;
},
Cancel: function () {
//TODO: Don't think you need this line?
$(this).dialog("close");
//CANCEL!!!
return false;
}
}
});
//User skipped Dialog somehow...ignoring....DO NOT SUBMIT
return false;
}
}
});
});
});
Note: This will return true and false to continue the submit process to the server

zclip not work in jquery ui inactive tab

I am using zclip in my asp.net webpage on jQuery UI dialog in jQuery UI tab. It works great in first tab which is active but it doesn't work when I add it to second tab and click second tab and clip copy button.
my markup is below:
<input type="text" id="txtCallStatus" class="disabled"
readonly="readonly" value="NOT SET" />
Copy status
Js code is below:
$.ajax({
type: "POST",
dataType: "json",
url: "/recording/verifyUser",
data: {
ID: $("#ID").val(),
PSSWD: $("#PSSWD").val(),
ACCID: $("#ACCID").val(),
PASSWDINT: $("#PASSWDINT").val()
},
success: function (data) {
if (data == "success") {
$('#dialog-AddCallRecording').dialog({ closeOnEscape: false });
$(".ui-dialog-titlebar").hide();
$("#dialog-AddCallRecording").dialog({
dialogClass: 'transparent',
modal: true
});
$("#dialog-AddCallRecording").dialog("open");
// The link with ID "copy-description" will copy
// the text of the paragraph with ID "description"
$('a#copy-dynamic').zclip({
path: '../../Content/Zclip/ZeroClipboard.swf',
copy: function () { return $('input#txtCallStatus').val(); }
});
// The link with ID "copy-dynamic" will copy the current value
// of a dynamically changing input with the ID "dynamic"
}
else {
$("#dialog-user-login").dialog('option', 'position', 'center');
$("#dialog-user-login").dialog("open");
}
}
});
In success, after dialogue is open, I am initializing the zclip.
Please suggest solution to it. Thanks

Categories

Resources