Hello and thank you for making stackoverflow such a great resource for learning programmers like me. I've been reading lots of answers on here to help with my first MVC project, this is my first time asking.
Here is my dropdown HTML
<div class="dropdown">
<select id="assetSelect" onchange="location = this.options[this.selectedIndex].value;">
<option value="/History/Index/All">All Assets</option>
#foreach (var item in Model.NodeInfo)
{
<option value="/History/Index/#item.node.name">#item.node.name</option>
}
</select>
</div>
Once an item is selected from the dropdown, the url will look like this
http://web.site/History/Index/G0000106
Now I'm trying to grab that last part of the URL (in this case G0000106) and set the corresponding dropdown option to selected. Here is the javascript I have pieced together so far but it's not working.
$('#assetSelect').find('option').each(function () {
function getCurrentPageId() {
var params = window.location.href.split('/');
var i = params.length;
var pageId = params[i];
return pageId;
}
var currentPageId = getCurrentPageId();
var $this = $(this);
if ($this.text() == currentPageId) {
$this.attr('selected', 'selected');
return false;
}
});
Will this function work with the one that populates the dropdown list? Is this the best way or is there an HTML helper that can do it? Any help is appreciated, thanks!
Option 1. You can simplify your code significantly:
function getCurrentPageId() {
var params = window.location.href.split('/');
return params[params.length - 1];
}
var pageId = getCurrentPageId();
$('#assetSelect').find('option:contains(' + pageId + ')').prop('selected', true);
Anyway, your problem was in this line:
var i = params.length;
var pageId = params[i];
It should be params[i - 1], since you want to get the last array element.
Option 2. An even simpler approach which should also work for you is to use location.pathname:
$('#assetSelect').val(window.location.pathname);
Related
although I found similar questions the solutions mentioned there wont seem to work for me.
What I'm trying to do:
Fetch all the table names of my database with Ajax
Fill the Table Names as options with respective values into a select field
How far I've come:
My fetch_devices php script echoes:
["test1","test2","test3"]
function FetchDevices(){
alert("Fetching");
$.ajax({
url: 'php/sql/fetch_devices.php',
success: function(devices) {
var elements = Object.keys(devices).length;
var select = document.getElementById("devices");
var option = document.createElement("option");
var i = 0;
while(i < elements)
{
option.text= devices[i];
option.value= devices[i];
select.appendChild(option);
i++;
}
},
cache: false
});
}
But in the end I only see the last option "test3".....
Why is that happening?
Thanks in advance!
Best Regards,
You are overriding the same option. Aslo make use of add(). Change it to
while(i < elements)
{
var option = document.createElement("option");
option.text= devices[i];
option.value= devices[i];
select.add(option);
i++;
}
I am doing a HTML page with employee leave details. In that page, pending leave option having edit option. User may have edit that leave while its in PENDING. Once I click the edit button, the correspond row details will pass to update page. Leave type should be an combo box. So how to pass that combobox and make that variable as selected.
For example, When i click the edit button in Casual Leave category, the output should be
<select id="select_type">
<option value="Earned Leave">Earned Leave</option>
<option value="Casual Leave" selected>Casual Leave</option>
</select>
P.S: Need to pass the variable via javascript
So my javascript to pass the variable as below
function GetUrlValue(VarSearch){
var SearchString = window.location.search.substring(1);
var VariableArray = SearchString.split('&');
for(var i = 0; i < VariableArray.length; i++){
var KeyValuePair = VariableArray[i].split('=');
if(KeyValuePair[0] == VarSearch){
return KeyValuePair[1];
}
}
}
var x = decodeURIComponent(GetUrlValue('ReqType'));
var y = decodeURIComponent(GetUrlValue('FromDate'));
var z = decodeURIComponent(GetUrlValue('ToDate'));
var z1 = decodeURIComponent(GetUrlValue('NoDays'));
So pass the value to the combo box text and make it as selected. Hope you got my point.
You can make it like this, if you have the option value
var yourSelectedValue = somevalue;
$('#select_type option[value='+yourSelectedValue +']').attr('selected','selected');
Or like this
$("#select_type").val(yourSelectedValue );
I've created a dynamic dropdown list with jQuery and JavaScript. I'm hoping someone can take a look and let me know if this is an appropriate way to handle this type of task. I'm specifically curious to know if this code is scalable, and will it perform well? Next, would it be suggested to use a switch statement instead of several if statements in the JavaScript I have below? If so, why? I'd like to store this to be reused anytime I implement a solution like this, but as I'm new to JavaScript I don't completely trust my work yet.
JSFIDDLE: http://jsfiddle.net/6vrpF/
HTML:
<select id='parent'>
<option value='test'>test</option>
<option value='sure'>sure</option>
<option value='cool'>cool</option>
<option value='best'>best</option>
</select>
<select id='child'>
</select>
JavaScript:
function newDropdown()
{
var html = ""
for(i=0; i<arguments.length; i++)
{
html += "<option value='"+arguments[i]+"'>"+arguments[i]+"</option>"
}
$("#child").append(html)
}
$("#parent").on("change",function(){
$('#child').text("")
var selection = $("#parent").val()
if(selection == 'test') {newDropdown('a','b','c')}
if(selection == 'sure') {newDropdown('d','e','f')}
if(selection == 'cool') {newDropdown('g','h','i')}
if(selection == 'best') {newDropdown('j','k','l')}
});
updated the fiddle
http://jsfiddle.net/6vrpF/4/
var parentChild = {
"test" :['a','b','c'],
"sure" :['d','e','f'],
"cool" :['g','h','i'],
"best" :['j','k','l']
};
function newDropdown()
{
var html = ""
for(i=0; i<arguments.length; i++)
{
html += "<option value='"+arguments[i]+"'>"+arguments[i]+"</option>"
}
$("#child").append(html)
}
$("#parent").on("change",function(){
$('#child').text("")
var selection = $("#parent").val();
newDropdown( parentChild[selection].join(",") );
});
You need to get your data in the JSON format as mentioned/defined above
Edit: this is the updated fiddle which will give options one by one
http://jsfiddle.net/6vrpF/6/
var parentChild = {
"test" :['a','b','c'],
"sure" :['d','e','f'],
"cool" :['g','h','i'],
"best" :['j','k','l']
};
function newDropdown()
{
var array = arguments[0];
var html = ""
for(i=0; i<array.length; i++)
{
html += "<option value='"+array[i]+"'>"+array[i]+"</option>"
}
$("#child").append(html)
}
$("#parent").on("change",function(){
$('#child').text("")
var selection = $("#parent").val();
newDropdown( parentChild[selection] );
});
I have the following JavaScript:
var next_user = "1";
i=0;
for (i=0;i<=10;i++)
{
var el = document.getElementById("user_list");
var val = el[i].value;
if (val <= next_user)
{
next_user = i;
}
if (val >= next_user)
{
next_user = i;
}
alert(next_user);
}
and I have following Select box on the screen:
<select id="user_list" onclick="load_user(this)" name="user_list" size="21" style="width:200px;">
<option value="1">Bob</option>
<option value="2">john</option>
<option value="3">Frank</option>
<option value="5">tom</option>
</select>
I can't seem to get it working the way I want it to.
The select box could have 10 users in the list and each of the (options) values are unique (1-10).
as you can see in my select box I am missing value 4. My Javascript code from above is meant to go though the select box and find the first value that is missing. (in my above example, it should reply back with 4 as that is missing) but If Bob is missing then it should reply back with 1.
Well that's what my JavaScript code above should be doing but I can't seem to work out what I am doing wrong. (well I hope I am doing it correct)
does anyone know what I am doing wrong?
(I am not plaining to use any jQuery at this stage)
You should use options property of that select element you extracted.
Example:
<script>
var userList = document.getElementById("user_list");
for (var i=0;i<userList.options.length; i++) {
if (userList.options[i].value != (i+1)) {
alert((i+1)+" is missing");
break;
}
}
</script>
You can use the following code to alert the missing Option
var next_user = 1;
var el = document.getElementById("user_list");
for (i = 0; i < 10; i++) {
var val = parseInt(el[i].value);
if (val > next_user) {
alert(next_user);
break;
} else {
next_user++;
}
}
Demo: http://jsfiddle.net/joycse06/75kM7/
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');