I am using the Chosen plugin in MVC razor and need to get the selected item id in onchange event:
<optgroup label="#col">
foreach (String[] colSub in sList)
{
<option id="#colSub[1]" class="opts">#colSub[0]</option>
}
</optgroup>
JQuery:
$('#chosen').on('change', function (evt, params) {
var selectedOption = params.selected; //gives me the selectedOption = #colSub[0]
var id = //i need the id here
}
In the above i need the ID also?
You can simply use
$('#chosen').on('change', function (evt, params) {
var id = $(this).find('option:selected').prop('id');
});
You can use use .map() to generate array of selected IDs
$("#chosen").on('change', function (evt, params) {
var SelectedIds = $(this).find('option:selected').map(function () {
return $(this).prop('id')
}).get();
console.log(SelectedIds);
})
DEMO
Related
I have this controller function:
public function showclientsinvoice($id)
{
$clients = Clients::find($id);
return response()->json($clients);
}
That makes me autopopulate the input fields with clients data.
My problem is I don't know how to autopopulate a dropdown list
My jquery script is this:
$(document).ready(function () {
$('body').on('click', '#show-client', function () {
var userURL = $(this).data('url');
$.get(userURL, function (data) {
$('#invoicemodal').modal('show');
$('#client-id').val(data.id);
$('#client-name').val(data.nume);
$('#client-ctara').val(data.tara);
$('#cif').val(data.cif);
$('#cif1').val(data.cif1);
$('#rgc').val(data.rgc);
$('#rgc1').val(data.rgc1);
$('#rgc2').val(data.rgc2);
$('#rgc3').val(data.rgc3);
$('#cp').val(data.cp);
$('#judet').val(data.judet);
})
});
});
</script>
How can I integrate in this script an autopopulate for dropdown?
You can use JQuery in this way to add dynamically dropdown options:
let options = {
a : 'one',
b : 'two'
};
var select = $('#idselect');
$.each(options, function(val, text) {
select.append(
$('<option></option>').val(val).html(text)
);
});
Need to send dynamic (not hardcode) data to a select element.
This code works great in one of my sheets but doesn't work in the other sheet.
The "select" element doesn't get updated with the options I send..
I don't get an error message either.
I've spent a lot of time twitching it and trying to find why but still don't see what's wrong.
p.s. I used a dummy object to send the data for testing purpose.
The html (used MaterializeCss framework)
<select class="icons browser-default" id="selName" onChange ="getNameText();">
<option value="" disabled selected>Choose week</option>
<div id = "err"></div>
//select element initialization in framework
document.addEventListener('DOMContentLoaded', function() {
var elems = document.querySelectorAll('select');
var options = handlers()
var instances = M.FormSelect.init(elems);
});
function handlers() {
var success = google.script.run.withSuccessHandler(addOptions).getNamesForDropdown()
var failure = google.script.run.withFailureHandler(showError).getNamesForDropdown()
return;
}
function addOptions(names) {
var selectTag = document.getElementById("selName") //select tag
for (var k in names) {
var thisID = k;
var thisText = names[k];
var option = document.createElement("option"); //creating option
option.text = thisText
option.value = thisID;
selectTag.add(option);
}
}
function showError() {
var err = document.getElementById("err").innerHTML = "There was an error."
}
//get the text of selected option
function getNameText() {
var sel = document.getElementById("selName")
var nameText = sel.options[sel.selectedIndex].text;
return nameText;
}
Dummy object I send:
function getNamesForDropdown() {
var namesObj = {
one: "blah",
two: "blahblah"
}
return namesObj;
}
Here's the result what I get (on the screen you there's only hardcoded option):
I handled it. I added a class "browser-default" to the select and the options got updated. This class comes from MaterializeCss Framework.
I am trying to add an element to a dropDown and after selection remove it, by naively trying to have htmlElement refrence defines as such : (Of course this doeasnt work)
var selectAnOption = "<option value='' selected='selected'>Select One</option>";
So later
var addSelectAnOption = function () { ('#ddb1').prepend(selectAnOption ); };
var removeSelectAnOption = function () { selectAnOption.remove(); };
I have also tried the following variation:
var selectAnOption;
var addSelectAnOption = function () { selectAnOption = $('#ddb1').prepend("<option value='' selected='selected'>Select One</option>"); };
var removeSelectAnOption = function () { selectAnOption.remove(); };
But this also didn't work, as selectAnOption was set to the dropDownBox itself
Of course I could add the option with an id and then later use that to find it to remove it, but that seemed not too pretty.
wrap it in $():
var selectAnOption = $("<option value='' selected='selected'>Select One</option>");
DEMO
I am trying to get the custom attribute values from the select box. It is triggered by a checkbox click which I already have working. I can get the name and value pairs just fine. I want get the custom attributes (therapy) (strength) (weight) and (obstacle) from the option value lines. is this possible?
select box
<option value="2220" therapy="1" strength="1" weight="0" obstacle="0">Supine Calf/Hamstring Stretch</option>
<option value="1415" therapy="0" strength="0" weight="0" obstacle="0">Sitting Chair Twist</option>
<option value="1412" therapy="0" strength="0" weight="0" obstacle="0">Static Abductor Presses</option>
jQuery
// exercise list filter category
jQuery.fn.filterByCategory = function(checkbox) {
return this.each(function() {
var select = this;
var optioner = [];
$(checkbox).bind('click', function() {
var optioner = $(select).empty().scrollTop(0).data('options');
var index=0;
$.each(optioner, function(i) {
var option = optioner[i];
var option_text = option.text;
var option_value = parseInt(option.value);
$(select).append(
$('<option>').text(option.text).val(option.value)
);
index++;
});
});
});
};
You need to find the selected , like this:
var $select = $('#mySelectBox');
var option = $('option:selected', $select).attr('mytag');
That is how to get selected option attribute:
$('select').find(':selected').attr('weight')
Get selected option and use attr function to get the attribute:
$("select").find(":selected").attr("therapy")
JSFIDDLE
Just to give you a better idea I am making a computer customization page with a bunch of dropdown lists
that display the Part name and have the PartID as the data value. I wish to append all the part name text values for all options excluding the currently selected option with the price difference between the price of this part and the currently selected one.
i.e:
[Intel i7 950] - selected visible option
[Intel i7 960 (+ $85)] - not selected but in the drop down list
[Intel i7 930 (- $55)] - not selected but in the drop down list
I do not have the price, so I would need to retrieve the price for all the option data values (PartID)
and return it as a json collection ({PartID, Price}) key value pairs as the page loads in Ajax call. I would only need to make one Ajax call and use this data for all onchange events for my dropdown list.
Then using Javascript/Jquery, for each option, using its data value (PartID) as key, find its price from the returned Json collection and append to the end of the non selected options text value the difference between its price and the currently selected options price. This will have to run every time (onchange) that a new option is selected.
Using ASP.NET MVC3/Razor
Here's what my dropdown list html looks like, I have about ten such dropdown lists:
<select id="partIdAndCount_0__PartID" name="partIdAndCount[0].PartID">
<option value="">Select processor</option>
<option value="3">Intel Core i7 950</option>
<option value="4">Intel Core i7 930</option>
</select>
Someone has now suggested I take the easier approach and simply add the cost to each option as additional attribute. In my view I have code as follows:
#Html.DropDownList("partIdAndCount[0].PartID", new SelectList(Model.Processor.Products, "ProductID", "Name"), "Select processor" )
I can add additional attributes but only to the select tag and not option?
new { datacost = Model.Processor.Products[0].ListPrice }
I know how to get at the text value of all the options/option and to change it entirely, but not how to append to it or use javascript to use the options data values to find their price in the json collection and then only append to the non selected options text values etc. Also no idea how initially gather all options data values and pass them in an ajax call to my action method that will return the json result.
<script type="text/javascript">
$(document).ready(function () {
var arr = new Array();
$('select option').each(function () {
arr.push($(this).val());
});
$.ajax({
type: "POST",
url: "/Customise/GetPartPrice",
data: { arr: arr },
traditional: true,
success: function (data) { mydata = data; OnSuccess(data) },
dataType: "json"
});
});
$('select').change(function () { OnSuccess(mydata); });
function OnSuccess(data) {
$('select').each(function () {
var sov = parseInt($(this).find('option:selected').attr('value')) || 0; //Selected option value
var sop; //Selected Option Price
for (i = 0; i <= data.length; i++) {
if (data[i].partid == sov) {
sop = data[i].price;
break;
}
};
$(this).find('option').each(function () {
$(this).append('<span></span>');
var uov = parseInt($(this).attr('value')) || 0; //Unselected option value
var uop; //Unselected Option Price
for (d = 0; d <= data.length; d++) {
if (data[d].partid == uov) {
uop = data[d].price;
break;
}
}
var newtext = uop - sop;
var text = $(this).attr("text");
$(this).find('span').html(newtext);
});
});
};
//$(document).ready(function () { $("#partIdAndCount_0__PartID").prepend('<option value="0">Select Processor<option>'); });
</script>
Maybe it would be easier if you just included the price of each item in the option (inside of a data-cost attribute, or whatever), like this (just guessing on the prices):
<select id="partIdAndCount_0__PartID" name="partIdAndCount[0].PartID">
<option value="">Select processor</option>
<option data-cost="210" value="5">Intel Core i7 930</option>
<option data-cost="250" value="3">Intel Core i7 950</option>
<option data-cost="280" value="4">Intel Core i7 960</option>
</select>
Then use this script to update the options instead of needing to make numerous calls to your server to get more json data. Here is a demo.
$('select')
.find('option').each(function() {
// add spans to the option, done here because it doesn't
// seem to work if you include the span in the markup
$(this).append(' <span></span>');
}).end()
.change(function() {
var v, diff,
// get cost of selected option
sel = parseFloat($(this).find('option:selected').attr('data-cost'), 10) || 0;
// Add cost difference to option
$(this).find('option[data-cost]').each(function() {
v = parseFloat($(this).attr('data-cost'), 10);
diff = '(' + (sel > v ? '-' : '+') + ' $' + Math.abs(sel - v) + ')';
if (sel === v) {
diff = '';
}
$(this).find('span').html(diff);
});
})
// show values on init
.trigger('change');