On change on multiple select jquery with Ajax and PHP - javascript

I have a multiple selection in my HTML page which is generated in an AJAX response: the format is like this:
<div>
<select class='myselect' idselect=1>
<option value='private'>Private</option>
<option value='public'>Public</option>
</select><button idfeed=1 class='change'>Change status</button></div>
<div>
<select class='myselect' idselect=2>
<option value='private'>Private</option>
<option value='public'>Public</option>
</select><button idfeed=2 class='change'>Change status</button>
</div>......
In my jquery/Ajax I have something like that (the code which generating the HTML above):
<script>
$( document ).ready(function() {
var id= $('#idUser').val();
//console.log('findAll');
$.ajax({
type: 'GET',
url: 'http://localhost/ws/api/getUserFeeds/'+id,
dataType: "json", // data type of response
success:function(data){
//alert(data[0].URL);
$.each(data, function (i) {
var toappend="<div><select class='myselect' idselect="+data[i].id+"><option value='private'>Private</option><option value='public'>Public</option></select><button idfeed="+data[i].id+" class='change'>Change status</button></div>";
console.log(toappend);
$("#foo").append(toappend+"<div id=rss"+i+ ">"+i+"</div>");
$('#rss'+i).FeedEk({
FeedUrl: data[i].URL,
MaxCount: 1,
DateFormat: 'MM/DD/YYYY HH:mm'
});
});
}
});
});
</script>
And when I want to retrive the value of selected by user which must either private or public I use this jquery code to select,but the problem is that it select only private all time.
<script type="text/javascript">
$(document).on('change','.myselect',function(){
var selectvar = $('.myselect').val();
console.log(selectvar);
});
</script>
As you can see I display in my console the value of the selected one,and using the JQuery change event.
I try by many ways to try to make it work but it always return private(My select is composed of two choice:private and public)
Thanks for your help!!!

You made a small mistake at the end. You should retrieve your select input with $(this), not $('.myselect') :
$(document).on('change','.myselect',function(){
var selectvar = $(this).val();
console.log(selectvar);
});

Try this
DEMO
$(document).on('change','.myselect',function(){
var selectvar = $(this).val();
console.log(selectvar);
});
$(this) = > the element changed
$(".myselect") => it can be any of the two select elements in your
given html

Related

change selected value in msdropdown

I'm trying to use the msDropdown JavaScript plugin (https://github.com/marghoobsuleman/ms-Dropdown) to create html tags that include images.
It seems to work good except for if I try to change the selected value using JavaScript.
Like in this jsFiddle: https://jsfiddle.net/cmu845eh/7/
I'm trying to make it so that if you call the setValue() function, it will change the selected value to a certain index.
I've tried multiple different solutions online but none work, solutions such as this:
var oHandler = $("#main").msDropDown().data("dd");
oHandler.set("length", 0);
always result in an error, and more basic jquery approaches dont work either.
Can someone help me change the value of my select tag to a certain index using javascript?
Using msdropdown
Let me give you a full code on how to populate select dropdown from server-side using another select dropdown.
1st Select Dropdown
<select name="" id="from" class="selectFlags" style="width:100%;">
<option value="2" title="https://fxtop.com/ico/aon.gif">GBP</option>
<option value="3" title="https://fxtop.com/ico/aon.gif">GBP</option>
</select>
2nd Select Dropdown
<select name="" id="selectFlagTo" class="selectFlagTo form-control" style="width:100%;height:52px;">
</select>
JScript
<script language="javascript">
$(document).ready(function(e) {
try {
$(".selectFlags").msDropDown({mainCSS:'dd'});
} catch(e) {
alert(e.message);
}
$(".dd").css({ 'width' : '100%' });
});
$(document).on("click",".dd .ddChild",function(e){
let $from=$("#from option:selected").val();
let $to=$("#selectFlagTo");
$to=$to.empty();
$(".dd").css({ 'width' : '100%' });
$(".dd2").css({ 'width' : '100%' });
$.ajax({
url: "http://odin.test/load_countries",
type: "POST",
data: {from:$from},
success: function(response) {
$.each(response, function(key, entry) {
$to.append("<option title='https://fxtop.com/ico/aon.gif' value='"+entry.id+"'>"+entry.name+"</option>" );
});
var oDropdown = $(".selectFlagTo").msDropDown({mainCSS:'dd2'});
$(".dd3").css({ 'width' : '100%' });
}
});
});
</script>
Enjoy coding!!!
Solved it here by fixing how I was initializing the msdropdown element after the html was created.
https://jsfiddle.net/uvbjhy31/

Javascript - Changing tag-it source with select option

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.

C# Razor - Display comment where looped in value equals selectedIndex value

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.

Default selected value of dropdown menu using Jquery

I have 3 nested dropdown menus which are dynamically populated from a mysql database and I use Jquery. I want to set a selected value, depending on the entry in my database.
For example:
I have a table that contains many devices. Each device has its storage place (room, shelve, box). Notice: different rooms contain different shelves which contain different boxes, thats why I use a nested dropdown menu.
Next to each device is a button "change".
What I want is that the current storage place of the device is already selected in my dropdown menu.
This is part of my JS functions (got them from another site, I'm very new to JS):
function populateComp(xmlindata) {
var mySelect = $('#manufacturer');
$('#printertype').disabled = false;
$(xmlindata).find("Company").each(function()
{
optionValue=$(this).find("id").text();
optionText =$(this).find("name").text();
mySelect.append($('<option></option>').val(optionValue).html(optionText));
});
}
This is my html code:
Raum:</br></br><select name="manufacturer" id="manufacturer" >
<option value="">Auswahl:</option></select> </br></br>
Regal:</br></br> <select name="printertype" id="printertype" disabled="disabled" >
<option value="">Auswahl:</option></select> </br></br>
Kiste:</br></br><select name="printermodel" id="printermodel" disabled="disabled" >
<option value="">Auswahl:</option></select></br></br>
<div id="loading" style="display: none;"></div>
<div id="output" ></div>
Part of my ajax code:
jQuery().ready(function($){
$('#loading')
.hide() // hide it initially
.ajaxStart(function() {
$(this).show();
})
.ajaxStop(function() {
$(this).hide();
})
;
// Ajax Called When Page is Load/Ready (Load Manufacturer)
jQuery.ajax({
url: 'man_list.php',
global: false,
type: "POST",
dataType: "xml",
async: false,
success: populateComp
});
Sorry for that much code, I hope anyone has a good solution for me, which I (the JS noob) can understand :)
You can check your server's response while populating dropdown options
function populateComp(xmlindata) {
var mySelect = $('#manufacturer');
$('#printertype').disabled = false;
$(xmlindata).find("Company").each(function()
{
optionValue=$(this).find("id").text();
optionText =$(this).find("name").text();
var $opt = $('<option> </option>').val(optionValue).html(optionText);
if(/* compare current data with your device here */) $opt.attr("selected", "selected");
mySelect.append($opt);
});
}

Jquery append option to select and get the selected value

Having trouble with this part.
I have a select populated with asp.net mvc and 2 other empty select that is populated by jquery
<select id="Type" onchange="GetClassification(this.value);">
#foreach (var item in Type)
{
<option value="#item.TypeID">#item.TypeName</option>
}
</select>
<select id="Classification" onchange="GetDescription(this.value);">
</select>
<select id="Description" onchange="GetDescriptionTips(this.value);">
</select>
So based on first select it populates the sencond, based on second it populates the third. First one populates right, second one populates right, third one doesn't populate on document ready.
$(document).ready(function () {
$(function () {
var type = $("#Type option:selected").val();
GetClassification(type);
});
});
function GetClassification(typeID) {
$.ajax({
type: 'GET',
url: '/types/Classification',
data: { typeID: typeID },
cache: false,
success: function (data) {
$('#Classification option').remove();
$.each(data, function (index, val) {
var optionTag = $('<option></option>');
$(optionTag).val(val.ClassificationID).text(val.ClassificationName);
$('#Classification').append(optionTag);
});
}
});
var classification = $("#Classification option:selected").val();
GetDescription(classification);
}
function GetDescription(classificationID) {
$.ajax({
type: 'GET',
url: '/types/Description',
data: { classificationID: classificationID },
cache: false,
success: function (data) {
$('#Description option').remove();
$.each(data, function (index, val) {
var optionTag = $('<option></option>');
$(optionTag).val(val.DescriptionID).text(val.DescriptionName);
$('#Description').append(optionTag);
});
}
});
}
After load page, if I select second one it changes the third one right, but if change the first, it only changes the second.
What I need is on load populate the second and third, then on change the first, re populate the second and third, and on change the second re-populate the third.
I can see it doesn't assign selected on any stage, so I am not sure if need assign it.
Hope I explained good.
Any help will be appreciated.
First of all try to follow this Don't repeat yourself, here is simple algo:
1.Choose all selects
2.Create only one ajax function and pass params like url, data, etc to it
3.In success function proccess your response from the server
4.find all next selects and clean them up or remove options as u wish
good luck!
Since you are using jQuery, try using the .on('chang', function(){...) event handler. Because you are changing the DOM and the on() method can detect the change event even the DOM changed after document ready.

Categories

Resources