jQuery event on a specific DropDownList option - ajax

I am very new to JQuery - I looked but could not find answers simple enough for my issues...
I have HTML drop down list (generated by a db file) with an ID on a selection common to all lists. It is on this "Add a New" option that I would like to trigger an event that will immediately slide open a div that will allow input & update of a new name to the list.
<select name="NAME" id="NMDROP">
<option value=""></option>
<option value="JOE">Joe</option>
<option value="BOB">Bob</option>
<option id="ADDNM" value="ADD">Add a New Name</option>
</select>
This is the jQuery I am hoping will allow me to call an update pgm.
jQuery(document).ready(function () {
//Jquery for Adding a SalesPerson
$("#ADDNM").click(function () {
if ($(this).is(":clicked")) {
jQuery.ajax({
url: "Update.pgm",
type: "POST",
data: {
"task": "ajax_addsp",
"ajax_add": 'Y',
"NAME": NAME
},
success: function () { alert("success:");
},
error: function () { alert("error on Add a New Name " + data);
}
});
}
});
});
I am confident that many of you will be able to spot my fundamental errors. I am not even sure if this is a click or a change event, I have seen it both ways on this site.

change your code to:
$("#NMDROP").on('change', function () {
if ($(this).val() === 'ADD'){
//rest of code
}
});
DEMO

Instead of using click, use the change event on your dropdown and check if the selected value is "ADD".
$("#NMDROP").on("change", function(e) {
if($("#NMDROP").val() == "ADD") {
//ajax method here
}
});

Related

Div shows/hides after second click with ajax and django

i want to have simple functionality in my app. When user clicks on "show replies" button, div with class "replies" will show up, then button changes to "hide replies" and when click it again the div will disappear. I am close but the problem is: when I click on button first time (after reloading page), the button changes to "hide", data is not showing up. Until i click it second time it shows and then i have data and button "show replies". In other words: ajax call doesn't work on first time, data prints properly even with first click. Please help me to understand what is wrong.
ajax
$(document).ready(function () {
$(".showReplies").click(function () {
let id = $(this).attr('id');
$.ajax({
url: $(this).attr("data-href"),
type: 'get',
success: function (data) {
console.log(data);
$(`#${id}.replies`).html(data);
let text = $(`#${id}.showReplies`).text()
if (text == 'Show replies') {
text = 'Hide replies'
$(`#${id}.showReplies`).text(text)
} else {
text = 'Show replies'
$(`#${id}.showReplies`).text(text)
}
}
})
});
});
template
<button type="button" id="{{ comment.id }}" class="showReplies btn btn-link" data-href="{% url 'comment_replies' comment.id %}">Show replies</button>
<div class="replies" id="{{ comment.id }}" style="margin-left: 30px;">
{% include 'blog/comment_replies.html' %}
</div>
urls
path('comment_replies/<int:comment_id>/', comment_replies, name='comment_replies')
view
def comment_replies(request, comment_id):
comment = Comment.objects.get(id=comment_id)
replies = Reply.objects.filter(comment=comment)
context = {'replies': replies}
return render(request, 'blog/comment_replies.html', context)
Ok, #Swati found the solution:
$(document).ready(function () {
$(".showReplies").click(function () {
let id = $(this).attr('id');
$.ajax({
url: $(this).attr("data-href"),
type: 'get',
success: function (data) {
console.log(data);
$(`#${id}.replies`).html(data);
let text = $(`#${id}.showReplies`).text();
console.log(text);
if (text == 'Show replies') {
text = 'Hide';
$(`#${id}.showReplies`).text(text);
$(`#${id}.replies`).show();
} else {
text = 'Show replies';
$(`#${id}.showReplies`).text(text);
$(`#${id}.replies`).hide();
}
}
})
});
});
I had to add $(#${id}.replies).show();and $(#${id}.replies).hide();in if and else.

jquery autocomplete is now working properly

I am working on jquery autocomplete in mvc platform. Now, my question is that in some textbox data autocomplete is working properly while in some textbox data autocomplete is not working properly.
For more clear, lets see the image of autocomplete task
now as per the image when I write the R word, I am getting the suggestion list of related R word.
now as per the second image I have written the whole word but still suggestion is not display.
Here is my code,
View
<input type="text" id="CustomerName" name="CustomerName" required data-provide="typeahead" class="typeahead search-query form-control autocomplete"
placeholder="Customer Name" />
<script>
$(document).ready(function () {
$.ajax({
url: "/ServiceJob/CustomerSerchAutoComplete",
method: "GET",
dataType: "json",
minLength: 2,
multiple: true,
success: function (data) {
/*initiate the autocomplete function on the "myInput" element, and pass along the countries array as possible autocomplete values:*/
//autocomplete(document.getElementById("CustomerName"), data.data);
$('#CustomerName').autocomplete({ source: data.data, minLength: 2, multiple: true });
}
});
});
</script>
Controller
[HttpGet]
public IActionResult CustomerSerchAutoComplete()
{
var customers = _Db.Ledger.Where(x => x.LedgerTypeId == (int)LedgerType.Customer).ToList();
var result = (from n in customers
select new
{
kk = n.Name.ToUpper()
}).ToList();
return Json(new { data = result });
}
As you are getting
Uncaught TypeError: Cannot read property 'substr' of undefined
For this error you should check that data is not null.
success: function (data) {
if(data != null)
{
autocomplete(document.getElementById("CustomerName"), data.data);
}
}

Selectize.js: onChange event triggered on load Page

In selectize, I wont call event, but is it don't working
jquery event Working,
Selectize event don't working
Help please.
<div><select id='select'>
<option value="0">Item 0</option>
<option value="1">Item 1</option>
<option value="2">Item 2</option>
$(function () {
$('select').on('change', function () {
alert("Original input event: Change");
});
$('select').selectize({
onChange: function () {
alert("Selectize event: Change");
}
});
// this triggers an the event
$('#select').trigger( "change" );
});
http://jsfiddle.net/6zyums3d/9/
$('select').selectize({
onInitialize: function() {
this.trigger('change', this.getValue(), true);
},
onChange: function(value, isOnInitialize) {
alert('Selectize changed: ' + value);
}
});
Make sure that you passed value parameter to the change callback. Otehrwise it would be undefined
This is what worked for me with respect to triggering a change event on the select element itself.
$('select').selectize({
onChange: function() {
this.$input[0].dispatchEvent(new Event("change"))
}
})
Try to trigger the event like this:
$('#select')[0].selectize.trigger( "change" );
Trigger like this,
$('#select').selectize({
onChange: function () {
alert("Selectize event: Change");
}
});
// this triggers an the event
$('#select').trigger( "change" );

knockout sammy.js navigation issue

I have a scenario like this.
Initially loaded when page is navigated to #Action.
Once the select action is performed data-bind="with tag is loaded"
User click on "Do Something" action is performed. Which replaces the whole "parentNode"
Now When the user clicks back, and the sammy.js notices the hash tag #Action/:id, I need to load the #Action to get back the main View and then select the id to load the data-bind="with" tag again.
How can I do this?
Currently the page does go back to "Action/:id" but since main view is not loaded it doesn't do anything. I have used "this.redirect("#Action") then selected the node, but the doesn't work.
<div id="parentNode">
<ul data-bind="foreach: items">
<li data-bind="click: $root.selectItem">
<h2><span data-bind="text: Sometext"></span></h2>
</li>
</ul>
<div data-bind="with: selectedItem">
<a data-bind="click: loadSomething">Do Something</a>
</div>
</div>
In my viewmodel i have this:
viewModel.selectItem= function (item) {
location.hash = "Action/" + item.id();
}
viewModel.loadSomething = function () {
location.hash = "Action/" + viewModel.someSelectedItem().id() +"/SubAction";
}
$.sammy(function () {
this.get('#Action', function () {
$.ajax({
url: '#Url.Action("GetMainView")',
type: "GET",
data: self.someId(),
dataType: "json",
success: function (result) {
$("#parentNode").html(result.message);
}
});
this.get('#Action/:id', function () {
var id = this.params["id"];
var matchItem = ko.utils.arrayFirst(viewModel.MainItems(), function (item) {
return item.id() == id;
});
viewModel.someSelectedItem(matchItem);
});
this.get('#Action/:id/SubAction', function () {
var id = this.params['id'];
$.ajax({
url: '#Url.Action("ViewSomething")',
type: "GET",
data: { id: id },
success: function (result) {
$('#parentNode').html(result.message);
}
});
});
});
Sample Code: https://skydrive.live.com/redir?resid=33048714B5BF3B4B!913
Steps to Reproduce:
Select "SubItems" under any of the items listed (Item 1, Item 2, Item 3)
Select any of the Sub Items that Label (Sub Item 1, Sub Item 2)
Partial View will be shown with "Sub Item {x}" with "Next View" link
Click "Next View" link.
"Next Partial View" will be shown.
Press the back button.
The thing I am trying to do is to load the SubItems and Select "Sub Item 1" view.
List item
I'm not sure this will work, but could you create a separate helper function to load the main view. Then it would be the case of the following:
this.get('#Action', function () {
LoadMainView();
}
this.get('#Action/:id', function () {
if($('#parentNode').length == 0) {
LoadMainView(function() {
var id = this.params["id"];
var matchItem = ko.utils.arrayFirst(viewModel.MainItems(), function (item) {
return item.id() == id;
});
viewModel.someSelectedItem(matchItem);
})
}
}
Your LoadMainView function would then accept a callback and be something like this:
function LoadMainView(callback) {
$.ajax({
url: '#Url.Action("GetMainView")',
type: "GET",
data: self.someId(),
dataType: "json",
success: function (result) {
$("#parentNode").html(result.message);
if(typeof callback == "function") {
callback();
}
}
});
}
I haven't been able to test this in your solution (I get an error opening it), but I believe that's the general structure to do what you are asking.

ASP.Net MVC 3 action not called from Ajax

I am developing an ASP.Net MVC 3 Web Application. One of my Razor Views contains a few Textboxes and a Drop Down List. When the User selects an option from the Drop Down List, the following JQuery code executes
View
<select id="myDDL">
<option></option>
<option value="1">F1</option>
<option value="2">F2</option>
<option value="3">ST1</option>
<option value="4">ST2</option>
</select>
<div id="someDivToLoadContentTo">
</div>
JQuery
$(document).ready(function () {
$("#myDDL").change(ChangeEventOfDDL);
function ChangeEventOfDDL(){
var dropDownValue = $('#myDDL').val();
//alert(dropDownValue);
$.ajax({ type: "GET",
url: '#Url.Action("SomePartialView","testAjax")',
data: {
id: dropDownValue
},
success: function(data) {
$('#someDivToLoadContentTo').html(data);
}
});
}
});
Controller
public class testAjaxController : Controller
{
public ActionResult SomePartialView(int id)
{
var test = "Hello World";
return View(test);
}
}
However, when I put a breakpoint on the SomePartialView method within the testAjax Controller it never gets hit.
Can anyone perhaps suggest why this is?
Any help would be greatly appreciated.
Thanks.
UPDATE
I added the errorData line to my Ajax call like so, but that doesn't seem to give me anything either
$(document).ready(function () {
$("#myDDL").change(ChangeEventOfDDL);
function ChangeEventOfDDL(){
var dropDownValue = $('#myDDL').val();
//alert(dropDownValue);
$.ajax({ type: "GET",
url: '#Url.Action("SomePartialView","testAjax")',
data: {
id: dropDownValue
},
success: function(data) {
$('#someDivToLoadContentTo').html(data);
},
error: function (errorData) { $('#someDivToLoadContentTo').html(errorData); }
});
}
});
If you're going to send a value to the Controller you need to use POST, not GET.
type: "POST"
Folks the problem was with the following line
url: '#Url.Action("SomePartialView","testAjax")'
This was creating an incorrect URL, therefore, the action never got called. I changed to the following line which then corrected the problem
url: '/testAjax/SomePartialView/' + dropDownValue
I think i might have spotted it:
Try changing this:
data: {
id: dropDownValue
},
to this:
data: {
'id': dropDownValue
},
Currently i think it might be confused that id doesnt relate to anything.

Resources