I have a select list that looks like this:
<select class="form-control">
<option>Select</option>
<option value="2">Order</option>
<option value="5">Delivery</option>
<option value="6">PickUp</option>
<option value="13">Quote</option>
</select>
Once a user selects an option, I would like to display a comment only where db_Type = the value of the selected option:
foreach (var note in Model.GetNotes)
{
<div class="current-note-container">
<h5 class="note-comment"><b>Description:</b><br/> #note.db_Comment.Where(note.db_Type == /* Selected Index */)</h5>
</div>
}
I'm not really sure how I can accomplish this using razor, or how to mix javascript in to get the job done.
This is not exact, but I'm think you're looking for something like this
<select class="form-control" onchange="GetComment(this.value)">
<option>Select</option>
<option value="2">Order</option>
<option value="5">Delivery</option>
<option value="6">PickUp</option>
<option value="13">Quote</option>
</select>
Add this to the script of your razor view
function GetComment(ID)
{
var parameters = {};
parameters["ListID"] = ID;
$.ajax
({
type: "GET",
data: parameters,
url: "/MyController/GetComment",
success: function (message) {
$('#note-comment').val(message);
},
error: function () {
alert("error");
}
});
}
And finally something like this to your controller
[HttpGet]
public JsonResult GetComment(int ListID)
{
return Json(Mylist[ListID].Comment);
}
Razor is a server side code and so you can not combine it with client script like what you are planning to.
Instead use jQuery to listen to the selection changed event and pass (GET/POST) newly selected value back to controller and query database and get the required comment.
jQuery inside View (pseudo code):
$( "#ddlOptions" ).change(function() { //assuming ddlOptions is the Id of select list
var selectedOptionId= $(this).val();
$.get('#Url.Action("ActionName","ControllerName")', { id: selectedOptionId},
//You can use $.get(...) or $.post(...) based on action method type.
function (data) {
//Display/append the comment received to a container(div/span etc)
});
});
Controller code (pseudo code)
public JsonResult Get(int id)
{
//Query database here based on id to get the comment
//e.g: db_comment.where(com=>com.id==id).FirstOrDefault();
return Json(comment,JsonRequestBehavior.AllowGet);
}
Hope this provide you some idea.
Related
As that title says, I am attempting to use the same javascript function multiple times on the same page. Basically, I have 2 separate drop downs that call users via ajax so that even new users will be present. (The site is based off not having to always reload.) Anyways, the way I currently have it setup is something like this...
Javascript:
function getAllUsers() {
(function getAllUsers() {
$.ajax({
url: 'staff/getAllUsers.php',
success: function(data) {
$('#getAllUsers').html(data);
},
complete: function() {
// Schedule the next request when the current one's complete
setTimeout(getAllUsers, 5000);
}
});
})();
}
getAllUsers();
function getAllUsers2() {
(function getAllUsers2() {
$.ajax({
url: 'staff/getAllUsers.php',
success: function(data) {
$('#getAllUsers2').html(data);
},
complete: function() {
// Schedule the next request when the current one's complete
setTimeout(getAllUsers2, 5000);
}
});
})();
}
getAllUsers2();
I am sure that doing it like this is unpractical, hence why I am asking for some guidance now.
This is the current HTML setup for it on the dropdowns:
<select class="select2" name="user" id="getAllUsers" required>
<option selected="true" disabled="disabled">Loading Users...</option>
</select>
<select class="select2" name="user" id="getAllUsers2" required>
<option selected="true" disabled="disabled">Loading Users...</option>
</select>
Obviously the Loading Users... option is replaced when the ajax data is loaded.
Again though, I am sure that a better way of doing this exists.
But whenever I try to do something like this with the html... using the same javascript function, the second one just stays at "Loading Users..."
<select class="select2" name="user" id="getAllUsers" required>
<option selected="true" disabled="disabled">Loading Users...</option>
</select>
<select class="select2" name="user" id="getAllUsers" required>
<option selected="true" disabled="disabled">Loading Users...</option>
</select>
I would think that doing it the way I currently do with multiple functions all calling the PHP file constantly can cause load time issues after a while espically if I add more.
Thank you for any assistance!
Both select2's are using the same endpoint, why not just assign the value in the same ajax request?
Something like this will be okay:
function getAllUsers() {
$.ajax({
url: 'staff/getAllUsers.php',
success: data => {
$('#getAllUsers').html(data);
$('#getAllUsers2').html(data);
},
error: err => {
//$('#getAllUsers').html("<option>test</option>");
//$('#getAllUsers2').html("<option>test</option>");
},
complete: () => {
// Schedule the next request when the current one's complete
setTimeout(getAllUsers, 5000);
}
});
}
getAllUsers();
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<select class="select2" name="user" id="getAllUsers" required>
<option selected="true" disabled="disabled">Loading Users...</option>
</select>
<select class="select2" name="user" id="getAllUsers2" required>
<option selected="true" disabled="disabled">Loading Users...</option>
</select>
First, you need to understand why it doesn't work for you and then find a solution.
The problem is that, you are using the same element ID in two separate elements, this is not strictly forbidden and will not throw you any errors, but it points to a wrong implementation.
When you are trying to select elements with the ID getAllUsers using jQuery, it knows that there should be only one such element, so it selects only the first one. Any other elements with the same ID are ignored. That's why it worked only for the first one.
Now, let's try to find solutions.
One solution, as Miroslav Glamuzina suggested is correct and works, but not flexible enough.
Another solution would be using a selector that selects multiple element which is not an ID. The best option is to use element's class, that will be unique for your two (or more) select elements. So if you want to add another one in the future, you don't have to touch the JS code, but only the HTML part.
You can do something like this:
HTML
<select class="select2 getAllUsers" name="user" required>
<option selected="true" disabled="disabled">Loading Users...</option>
</select>
<select class="select2 getAllUsers" name="user2" required>
<option selected="true" disabled="disabled">Loading Users...</option>
</select>
(Note that I also changed the name attribute of the second select, to prevent issues in the future)
JavaScript
(function getAllUsers() {
$.ajax({
url: 'staff/getAllUsers.php',
success: function(data) {
$('.getAllUsers').html(data);
},
complete: function() {
// Schedule the next request when the current one's complete
setTimeout(getAllUsers, 5000);
}
});
}());
WARNING!
If you are planning to use this script publicly, you should pay attention on the security issue in this script.
This script is opened for XSS attacks. Because, you are requesting a remote content and applying its content as HTML without any data validations nor escaping.
I would suggest in your case, to generate a JSON in the PHP script, with the list of users and all the data you need, then on the JavaScript, create option elements using the data from the JSON list.
You should do something like this:
Let's say that this is the JSON received from staff/getAllUsers.php:
[
{"id": 14, "name": "User 1"},
{"id": 16, "name": "User 2"},
{"id": 17, "name": "User 3"}
]
JavaScript:
(function getAllUsers() {
$.ajax({
url: 'staff/getAllUsers.php',
success: function(data) {
try {
const list = JSON.parse(data); // Parse JSON from string to object
const selectEl = $('.getAllUsers').empty(); // Clear the content of both `select` elements
for ( let i=0; i<list.length; i++ ) { // Loop through each item in the JSON array
$('<option />') // Create an `option` element
.attr('value', list[i].id) // Set attribute `value` to `option` element
.text(list[i].name) // Set `option` text (this function also escapes any special characters, which prevents potential XSS attacks)
.appendTo(selectEl); // Add `option` element to both `select` elements
}
} catch (e) {
// Report any errors with the JSON parsing process to the developer console.
console.error(e);
}
},
error: function(jqXHR, textStatus, errorThrown) {
// Track any errors received from the server for debugging purposes
console.error(textStatus, errorThrown);
}
complete: function() {
// Schedule the next request when the current one's complete
setTimeout(getAllUsers, 5000);
},
dataType: 'json' // Expect a `json` back from server
});
}());
I hope you can learn something from this.
Good luck!
I want to show the models by changing the Drop Down value....I know how to get the value of drop down with change function but my problem is that i want to send that value in route to filter the models.....Please tell me how can i send the changed value id with route from blade..
This is my Drop Down
<select class="form-control" id="category" placeholder="Select category">
<option>All</option>
#foreach($categories as $category)
<option value="{{route('contributors.index')}}?category={{ $category->id }}">{{$category->name}}</option>
#endforeach
</select>
Here i my Jquery Change Function
$('#category').change(function(){
alert($(this).val());
})
Explanation :
Please check the below picture....I want to show the models(in the same view)which are related to that category selected in the drop down.
Add this to redirect you to the specific route. For you, it refreshes the page with the selected id in URL. So, models will filter for the given category_id.
$('#category').change(function(){
window.location = "domain.com/route/" + $('option:selected', this).val();
})
Of course, you should use your own URL instead of the URL in the example.
You can use ajax call to append and send category value to your route
$( "#category" ).change(function() {
var id=$(this).val();
$.ajax({
type: 'GET',
url: your url goes here,
success: function (data) {
//here yuo can append to model div
},
error: function (data) {
console.log(data);
}
});
});
the above code is sample for ajax request
I have a select with two options. When changing the select ... I want to filter/autocomplete a different database. Without http://aehlke.github.io/tag-it/ it's working fine and the autocomplete is changing the source ... but not with it. It stays at source_01.php although I see in the console the change of Test Source 01 to Test Source 02. What might causes this?
HTML:
<select id="search_database" class="form-control">
<option value="1" selected="">Source 01</option>
<option value="2">Source 02</option>
</select>
Javascript:
$('#search_database').on('change', function () {
if ( $('#search_database').val() == 1 ) {
console.log('Test Source 01');
$("#input-newsearch").tagit({
...
autocomplete: ({
source: function( request, response ) {
...
$.ajax({
url: "/source_01.php",
...
});
},
...
})
});
} else if ( $('#search_database').val() == 2 ) {
console.log('Test Source 02');
$("#input-newsearch").tagit({
...
autocomplete: ({
source: function( request, response ) {
...
$.ajax({
url: "/source_02.php",
..
});
},
...
})
});
}
});
Your problem is the value not getting picked up by the script when you change the options if you want to pick the value of the changed option you've to do something similar to the below code.
HTML:
<label for="clientSelect" style="margin-left:14px;">Client:</label>
<select name="clientSelect" id="clientSelect" onChange="clientId(this.id)" style="width:180px;"></select>
<input type="text" id="clintId" size="1" hidden>
JavaScript:
function getClient(cId){
//Get the selected ID using this.is in client side HTML then breaks it up using this to get the ID only
var select = document.getElementById("catSelect"),
optionId = select.options[select.selectedIndex],
catId = optionId.id;
I use the hidden text filed to send the selected ID to my PHP then to the database.
I'm using ASP.NET MVC 4
Let's puttig this way, this is my Html:
<select id="cmbProducts" name="Products" class="form-control">
<option value="1">Product1</option>
<option value="2">Product2</option>
<option value="3">Product3</option>
</select>
<button id="cmdAddProduct" type="button">Add selected product</button>
<select id="cmbAddedProducts" name="AddedProducts" size="8" class="form-control">
<!-- These options are added dinamically on click via jQuery -->
</select>
And this is my jQuery function
$(function () {
$("#cmdAddProduct").click(function (e) {
var productName = $('#cmbProducts :selected').text();
var productValue = $('#cmbProducts :selected').val();
var exists = false;
$("#cmbAddedProducts > option").each(function () {
if (this.text == productName) {
exists = true;
}
});
if (!exists) {
$('#cmbAddedProducts').append($('<option>', {
value: productValue,
text: productName
}));
}
});
It works perfect adding elements to my list.
My problem is I'm trying to get the options array which were added dinamically on 'cmbAddedProducts' (these are being added using .append on my function).
On my controller, I'm using an ActionResult to retrieve the options on the <select>
public ActionResult AEventos(FormCollection form) {
string[] AddedProducts = Request.Form.GetValues("AddedProducts");
}
But it only retrieves the <option>'s that I added directly on html code, not the added dynamically using jQuery on my buttons click.
I think this is related to the DOM not updating but I've been searching for help without success, and still have no idea about how to solve this.
Update your javascript to
$('#cmbAddedProducts').append($('<option>', {
value: productValue,
text: productName,
selected: true
}));
so that option you add will get selected in your DOM and thus this will be getting accessed from your controller.
We have the following SELECT combobox that is populated dynamically with ajax and httphandler web service (.ashx).
When SELECT combobox is dynamically populated, it looks like this:
<select name="selectid" id="selectid">
<option value="">-Select an option-</option>
<option value="1">Test1</option>
<option value="2">Test2</option>
<option value="3">Test3</o4tion>
<option value="4">Test5</option>
<option value="5">Test6</option>
<option value="6">Test7</option>
</select>
Below is the js:
function getText() {
$.ajax({
url: 'rulings.ashx',
dataType: 'json'
})
.done(function(textInfo) {
$(textInfo).each(function(i, texts) {
$('<option>').val(texts.dbtextID).text(texts.textToBeDisplayed).appendTo( $('#selectid') );
})
});
}
When we display the values from the dropdown, it displays the VALUE options instead of the displayed text.
Example from the combobox above, it displays 1 instead of Test1.
How do I modify the script to show displayed text instead of VALUE options?
Try this code , just put it inside
$(document).ready(function(event){
$("#selectid").on('change',function() {
//alert($("#selectid option:selected").text());
$('#summTextvalue').html($("#selectid option:selected").text());
});
})
The ON method in jQuery can bind events to dynamically created elements.
or you can also do something like
function _bindEvent()
{
$("#selectid").on('change',function() {
alert($("#selectid option:selected").text());
});
}
and call _bindEvent() from your AJAX done method
Try this to get text, instead of value.
$('#selectid').change(function(){
var selectedVal=$(this).val();
alert($(this).children("option[value='"+selectedVal+"']").text());
});