Is there a way to use something like $(".class").change(function(){ or $("#id").change(function(){, but to change the value the value attribute of an option element like so?
<select>
<option value="changeThis">opt</option>
</select>
I'm using a for loop to generate each option of a select list from a relational database, so I need to have a function to automatically increment the value so they're unique.
New code:
<div class="facilitySelection">
<select name="Facility" class="form-control">
<option selected disabled>Select a facility...</option>
#{
var i = 1;
foreach (var item in Model)
{
<option value="#i">#Html.DisplayFor(modelItem => item.FacilityName</option>
i++;
}
}
</select>
</div>
Newer code:
I have a table of Facilities, with an ID and Name field. Now using a foreach loop to use the ID directly from the database rather than generating the number from a variable in the script block, to ensure the ID and Name from the database line up correctly.
<div class="facilitySelection">
<select id="Facility" name="Facility" class="form-control">
<option selected disabled>Select a facility...</option>
#{
foreach(var f in ViewBag.Facilities)
{
<option value="#f.Id">#f.Name</option>
}
}
</select>
</div>
You change attributes with the attr function:
$("selector-for-the-option").attr("value", "new value");
You can also use prop because the value of an option element has a reflected property called value (unlike input elements, where the value property is not the reflected property for the value attribute):
$("selector-for-the-option").prop("value", "new value");
Related
Let's say I have this code:
<select id = dropdown-list>
<option value = "0"> Yes </option>
<option value = "1"> No </option>
</select>
The user can select yes or no from a dropdown list. How can I use pure JS/HTML to figure out what the user has selected (and is currently showing in the dropdown list box when the list isn't expanded) so I can use that data elsewhere? The only way I can figure out is if I add an eventListener on each option but I feel there is a better way. I am quite new to JS so I'm not sure. Thank you.
You can use onchange attribute from select element.
<select id="dropdown-list" onchange="onChange(this.value)">
<option value = "0"> Yes </option>
<option value = "1"> No </option>
</select>
and in JS:
function onChange(val) {
// `val` is the value
}
Execute a JavaScript function changeResult when a user changes the selected option of a element:
Flow:
We bind changeRegult using onchange event listener.
When we change the dropdown menu, it calls changeResult function.
Inside the function, we select our dropdown menu using its id property.
After getting the element by id, we can now access all properties.
Here we want to show the value property, so we use document.getElementById("dropdown-list").value.
For more check this link.
function changeResult() {
var x = document.getElementById("dropdown-list").value;
document.getElementById("result").innerHTML = "You selected: " + x;
}
<select id = "dropdown-list" onchange="changeResult()">
<option value = "0"> Yes </option>
<option value = "1"> No </option>
</select>
<p id="result"></p>
You may want to use on change event.
Since you use each I suppose you are using Jquery.
If you have any question just let me know.
$(document).ready(function(){
$('#dropdown-list').on('change',function(){
alert($(this).children('option:selected').val());
})
});
https://jsfiddle.net/u4dz162o/
I am trying to access my HTML form parameters from RESTful Web service but in vain. All the form parameters are easily accessed using #FormParam except the cloned HTML elements whose attributes are set using attr(attribute name, value) in jQuery. Here is my HTML code
<div id="process_block">
<div id="process_operands" class="process_input">
<select name="process_operands">
<option name="PO" value="Process_Name">Process Name</option>
<option name="PO" value="Process_Path">Process Abspath</option>
<option name="PO" value="Process_Signature">Process Signature</option>
<option name="PO" value="Process_Acl">Process ACL</option>
<option name="PO" value="Process_Checksum">Process Checksum</option>
<option name="PO" value="Process_Type">Process Type</option>
</select>  
<input type=text name="PO_value" maxlength="5000">
</div>
<div id="Padditionalselects"></div>
<p class="add_PO">Add more</p>
</div>
I am cloning the select list when clicked on Add more and setting their attribute values. Here is my JS code
$(document).ready(function(){
// Cloned elements count
var counter = 0;
$(".add_PO").click(function(){
// Increment the cloned element count
counter++;
// Clone the element and assign it to a variable
var clone = $("#process_operands").clone(true)
.append($('<a class="delete" href="#">Remove</a>'))
.appendTo("#Padditionalselects");
// Modify cloned element, using the counter variable
clone.find('select').attr('name', 'process_operands_'+counter);
clone.find('input').attr('name', 'PO_value_'+counter);
clone.attr('id', "process_operands_" + counter);
});
$("body").on('click',".delete", function() {
$(this).closest(".process_input").remove();
counter--; // Modify the counter
});
Please find my web service, which tries to get hold of these param values.
#Path("/xml")
public class x{
#POST
#Consumes(MediaType.APPLICATION_FORM_URLENCODED)
public String createMessage(#FormParam("process_operands") String process_operands,
#FormParam("PO_value") String PO_value,
#FormParam("process_operands_1") String process_operands_1,
#FormParam("PO_value_1") String PO_value_1) {
System.out.println(" PO: "+process_operands+" PO Value: "+ PO_value+" PO1: "+process_operands_1+" PO value1: "+PO_value_1 );
} }
I am able to get the values for process_operands and PO_value. But, a null value is shown for process_operands_1 and PO_value_1.
I have this drop-down list in my angular code:
<div class="btn-group" dropdown>
<select class="selected_location" ng-options="perlocation.id as perlocation.name for perlocation in locations" ng-model="cleaningServiceLocation">
<option value="">Please Select Location</option>
</select>
<div>
Now in my controller I can easily call the selected value as:
$scope.cleaningServiceLocation
How can I get the text, or in my case, the name of the selected location?
You can make model (perlocation) as object instead of (perlocation.id)-
<select class="selected_location" ng-options="perlocation as perlocation.name for perlocation in locations" ng-model="cleaningServiceLocation">
And access it as -
$scope.cleaningServiceLocation.name
The easy way would be to loop through the locations array every time the value changes and grab the name property from the location whose id matches $scope.cleaningServiceLocation:
$scope.getName = function(id) {
for (var i = 0; i < $scope.locations.length; i++) {
if ($scope.locations[i].id == id) {
return $scope.locations[i].name;
}
}
return "";
}
Try it in a Plunker.
I have this html:
<select onchange="check_status(this);" name="status[171]">
<option selected="true" value="open" data="04f2cf35e4d7a1c0158459fd0450a605">open</option>
<option value="in_process" data="04f2cf35e4d7a1c0158459fd0450a605">pending</option>
<option value="finished" data="04f2cf35e4d7a1c0158459fd0450a605">finished</option>
<option value="canceled" data="04f2cf35e4d7a1c0158459fd0450a605">canceled</option>
</select>
and js
function check_status(obj){
var uid = obj.getAttribute('data');
alert(uid);
}
but it always alerts null instead of data value
Where is the problem guys? Thanks
The problem is that you get select element and not selected option element as function argument. And it does not have the data attribute. You have to get the option attribute like so:
function check_status(obj) {
var uid = obj.options[obj.selectedIndex].getAttribute('data-uid');
alert(uid);
}
<select onchange="check_status(this);" name="status[171]">
<option selected="true" value="open" data-uid="01f2cf35e4d7a1c0158459fd0450a601">open</option>
<option value="in_process" data-uid="02f2cf35e4d7a1c0158459fd0450a602">pending</option>
<option value="finished" data-uid="03f2cf35e4d7a1c0158459fd0450a603">finished</option>
<option value="canceled" data-uid="04f2cf35e4d7a1c0158459fd0450a604">canceled</option>
</select>
Notice that I changed the attribute name to data-uid for it to be valid according to HTML5 specificaion.
You are trying to get select data attribute, and not option's.
Also, I can see that all you data attributes are identical. Then you can move it from option to select itself: <select onchange="check_status(this);" name="status[171]" data="04f2cf35e4d7a1c0158459fd0450a605" > and use code snipped from your question unmodified.
function check_status(obj) {
var uid = obj.options[obj.selectedIndex].getAttribute('data');
alert(uid)
}
<select onchange="check_status(this);" name="status[171]">
<option selected="true" value="open" data="open04f2cf35e4d7a1c0158459fd0450a605">open</option>
<option value="in_process" data="pending104f2cf35e4d7a1c0158459fd0450a605">pending</option>
<option value="finished" data="finished04f2cf35e4d7a1c0158459fd0450a605">finished</option>
<option value="canceled" data="canceled04f2cf35e4d7a1c0158459fd0450a605">canceled</option>
</select>
You define custom attributes using the "data" attribute. In your code, there is not custome attribute which I'm sure you wanted it to be an ID. The exact format is "data-*", where "*" is replaced with the desired custom attribute name, then set to the desired string value. So in your code, it should ideally be:
<select onchange="check_status(this);" name="status[171]">
<option selected="true" value="open" data-id="open04f2cf35e4d7a1c0158459fd0450a605">open</option>
<option value="in_process" data-id="pending104f2cf35e4d7a1c0158459fd0450a605">pending</option>
<option value="finished" data-id="finished04f2cf35e4d7a1c0158459fd0450a605">finished</option>
<option value="canceled" data-id="canceled04f2cf35e4d7a1c0158459fd0450a605">canceled</option>
</select>
assuming you want the custom attribute to be "id".
There are two ways you can retrieve the value of "data" attributes using pure JavaScript: in addition to the good old fashion get/setAttribute(), you can also access using the "dataset" property of the element
Using DOM's getAttribute() property
function check_status(obj) {
var myoption = obj.options[obj.selectedIndex];
var uid = myoption.getAttribute('data');
alert(uid);
// setting and removing the data-id attribute
myoption.setAttribute("data-id", "foo") //changes "data-id" to "foo"
myoption.removeAttribute("data-id") //removes "data-id" attribute entirely
}
Using JavaScript's dataset property
function check_status(obj) {
var myoption = obj.options[obj.selectedIndex];
var uid = myoption.dataset.id;
alert(uid);
var statusId = myoption.dataset["id"]
alert(statusId);
}
function check_status(obj){
var uid = obj.options[obj.selectedIndex].getAttribute('data');
alert(uid);
}
This is my jspPage.
<select id="class_Teacher" name="classTeacher" style="height:25px; width: 190px;" onchange="Class(this.id)">
<option id="1">Manager</option>
<option id="2">Supervisor</option>
</select>
And here is javascript
function Class(str)
{
alert(str);
}
i want to get the id of Option on onchange Event. Thanks :)
You can do this if you are trying to get the id of the option which has been selected
function Class(str)
{
var select = document.getElementById("class_Teacher");
var option = select.options[select.selectedIndex];
alert(option.id);
}
Your onchange event will look like this. Just remove the .id as that will return the id of the select box itself not the option
onchange="myFunction(this)"
and your javascript function like this, which will alert the ID of the selected option
function myFunction(ele){
alert(ele.options[ele.selectedIndex].id);
}
Broken down ele represents the select box (a dom object). .options accesses the options within the select box. the [] brackets are a way of accessing a specific option. Like an array myArr[1] etc. and ele.selectedIndex returns a number representing the selected option i.e if the first option is chosen - ele.selectedIndex will be equivalent to 0.
HTML (you should use "value" attribute instead of "id")
<select id="class_Teacher" name="classTeacher" style="height:25px; width: 190px;" onchange="onChange()">
<option id="1" value="ID1">Manager</option>
<option id="2" value="ID2">Supervisor</option>
</select>
JS
var selectElement = document.getElementById("class_Teacher");
selectElement.onchange=function(){
alert(selectElement.options[selectElement.selectedIndex].id); // id in the html element
alert(selectElement.selectedIndex); // index starting from 0
alert(selectElement.value); // value of the selected element
};
Fiddle
Use selsectedIndex Property of GetElementByID
<script>
function val() {
d = document.getElementById("select_id").selectedIndex;
alert(d);
}
</script>
<select onchange="val()" id="select_id">