Getting the selected listValue of <s:select> in javascript - javascript

I am using tag of struts to display a list of items.
<s:select name="example" id="example" list="exampleList" listKey="exampleKey"
listValue="exampleValue" onchange="fun()"/>
Now I have a javascript function:
function fun()
{
var ex=document.getElementById("example");
alert(ex.value);
}
In this function I need to get the listValue of the selected item but when I'm using the above code, it just alerts me the listKey that I have selected. How can I get the listValue instead of listKey in the javascript function?

$(document).ready(function() {
$('#reminderTypeID').change(function()
{
var ex = document.getElementById("reminderTypeID");
var selTex = ex[$('#reminderTypeID').val()].text;
var selVal = ex[$('#reminderTypeID').val()].value;
alert(ex[$('#reminderTypeID').val()].text);
});
});

Try this (Worked for me):
function fun()
{
var ex = document.getElementById("example");
alert(ex.getAttribute('listValue'));
}
Edit
Added fiddle: http://jsfiddle.net/FranWahl/Ur6jT/2/
(Not sure why it won't work for you. In the fiddle it works.)

I ran into this same issue, and neither of the other answers was working for me. This is the solution that I found worked:
$(document).ready(function(){
$("#example").change(function(){
var options = document.getElementById("example").options;
var selectedIndex = document.getElementById("example").selectedIndex;
var selectedOptionText = options[selectedIndex].text;
var selectedOptionValue = options[selectedIndex].value;
console.log("Id of selected option is: " + selectedOptionValue);
console.log("Text of selected option is: " + selectedOptionText);
});
});
To further understand the issue, it helped to think about what HTML is created when the JSP is processed. The <s:select> will generate the following HTML:
<select id="example" name="example">
<option value="456">TextA</option>
...
</select>
Following OP's sample code, "456" would be derived from exampleKey and "TextA" from exampleValue. There would be such HTML <option> for each item in exampleList.
Note in my solution, I used the jQuery .change() function. However I also tried the solution with onchange="fun()", as the OP had done, and that worked too.
When I tried replacing document.getElementById("example") with $("#example"), the solution did not work.
Also helpful was reading this reference on <select> option selectedValue.

Related

How to add value on select tag with javascript [duplicate]

I'd like to add option to a select dynamically using plain javascript. Everything I could find involves JQuery or tries to create the select dynamically as well. The closest thing I could find was Dynamically add input type select with options in Javascript which does the latter and was the only I found that doesn't involve JQuery. Although I did try and use it like so:
daySelect = document.getElementById('daySelect');
daySelect.innerHTML += "<option'>Hello world</option'>";
alert(daySelect.innerHTML)
After I did this there was no change to the select and the alert gave me
HELLO WORLD</option'>
I apologize if this is simple but I'm very new at javascript and web programming in general. Thank you for any assistance.
EDIT: So I tried the given suggestions like so.
daySelect = document.getElementById('daySelect');
myOption = document.createElement("option");
myOption.text = "Hello World";
myOption.value = "Hello World";
daySelect.appendChild(myOption);
This has not changed the select in the page at all. Any idea why? And I did check that the code was being run with an alert.
EDIT: The idea did work, it just turned out that it wasn't displaying a value in the dropdown. I don't know why but I can figure that one out I think.
This tutorial shows exactly what you need to do: Add options to an HTML select box with javascript
Basically:
daySelect = document.getElementById('daySelect');
daySelect.options[daySelect.options.length] = new Option('Text 1', 'Value1');
I guess something like this would do the job.
var option = document.createElement("option");
option.text = "Text";
option.value = "myvalue";
var select = document.getElementById("daySelect");
select.appendChild(option);
The simplest way is:
selectElement.add(new Option('Text', 'value'));
Yes, that simple. And it works even in IE8. And has other optional parameters.
See docs:
HTMLSelect​Element​.add(item[, before])
new Option(text, value, defaultSelected, selected);
Use the document.createElement function and then add it as a child of your select.
var newOption = document.createElement("option");
newOption.text = 'the options text';
newOption.value = 'some value if you want it';
daySelect.appendChild(newOption);
.add() also works.
var daySelect = document.getElementById("myDaySelect");
var myOption = document.createElement("option");
myOption.text = "test";
myOption.value = "value";
daySelect.add(myOption);
W3 School - try
Try this;
var data = "";
data = "<option value = Some value> Some Option </option>";
options = [];
options.push(data);
select = document.getElementById("drop_down_id");
select.innerHTML = optionsHTML.join('\n');
<html>
<head></head>
<body>
<select id="ddl"></select>
</body>
<script>
var ddl = $("#ddl");
ddl.empty();
ddl.append($("<option></option>").val("").html("--Select--"));
</script>
</html>

Converting object to string JQuery/JS/HTML

I am trying to append a list of countries to my select tag, but whatever I try it keeps showing as [object Object]. Here is my JS code:
I've tried var x = JSON.Stringify(country); and passing that into var o, and I've also tried country.toLocaleString('en-US); and that has not worked either. How can I have the countries show in the select list? Thanks
You need to use world_list[i].country to access country.
Here is demo code :
//your json
var report={"last_updated":"2020-06-02T04:15:21Z","regions":{"world":{"name":"World","totals":{"confirmed":6370499,"recovered":2904076,"deaths":377515,"critical":2811064,"tests":11709},"list":[{"country":"Hong Kong","confirmed":1088,"deaths":4,"recovered":1037,"Incidence_Rate":"14.49915619446103","Case-Fatality_Ratio":"0.36798528058877644","last_updated":"2020-06-02T04:15:21Z","country_code":"hk","daily_confirmed":0,"daily_deaths":0,"critical":47,"tests":5},{"country":"Macao","confirmed":45,"deaths":-1,"recovered":45,"Incidence_Rate":"6.930092308829553","Case-Fatality_Ratio":"0.0","last_updated":"2020-06-02T04:15:21Z","country_code":"mo","daily_confirmed":0,"daily_deaths":-1,"critical":0,"tests":-1}]}}};
var world_list = report.regions.world.list;
for(var i in world_list){
//use word_list[i].country to retrieve slected value
var o = new Option(world_list[i].country, i);
$("select").append(o);
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<select>
</select>

val() returns [object Object]

Here is my script
<input type="text" id="teamleader-default" value="${foo.teamLeaderId}/${foo.teamLeaderFirstName} ${foo.teamLeaderLastName}" />
<script type="text/javascript">
$(document).ready(function(){
var teamleader = $('#teamleader-default').val();
var tl_details = teamleader.split("/");
$('#teamleader-default').prop('type', 'hidden');
$("#update").submit(function() {
if ($('#ParentDD :selected').text() == "Engineer") {
var tmp0 = $('#teamleader').val(tl_details[1]);
var tmp1 = $('#teamleaderId').val(tl_details[0]);
alert(tmp0);
alert(tmp1);
} else {
var tmp2 = $('#teamleader').val('');
var tmp3 = $('#teamleaderId').val(0);
alert(tmp2);
alert(tmp3);
}
});
});
</script>
The problem is that I can't assign a value for both the teamleader and the teamleader ID
$('#teamleader').val(tl_details[1]);
$('#teamleaderId').val(tl_details[0]);
instead the value it contains is just saying "Object object" like the one in this image:
Can anyone help me on how to assign a value for the team leader.
Again a big thanks for those who could help me.
I think the comments above have already answered the question quite well, if you want to know whether it is assgined successfully, you can use tm0.val().
By the way, using alert is not my choice to debug code like Js. Since you have chosen Chrome, you can get the advanced debug tool just press F12.You can get some tips on How to use Chrome DevTools
Happy coding~

jQuery .html only get last value of JSON

I have a problem with jQuery("#someID").html. It only prints the last key from the JSON.
Here is the js:
<div class="row" id="fetchmember">
<script type="text/javascript">
jQuery('#group').change(function() {
var id_group = this.value;
var memberjson = "fetchmember.php?group="+id_group;
jQuery.getJSON(memberjson, function(data) {
jQuery.each(data, function(i, items) {
jQuery("#fetchmember").html("<li>"+items.name+"</li>");
});
});
});
</script>
</div>
JSON result from one of the selected option :
[{"id":"1645819602","name":"Michael English","first_name":"Michael","last_name":"English"},
{"id":"100000251643877","name":"Bill Gaither","first_name":"Bill","last_name":"Gaither"}]
I want to print all of name from the json, but it print only last name key of the json. What's wrong with my code?
Any advice and helps would be greatly appreciated. Thank you very much
You're erasing the content on each iteration. Use append instead of html
Instead of
jQuery("#fetchmember").html("<li>"+items.name+"</li>");
Use
jQuery("#fetchmember").append("<li>"+items.name+"</li>");
At iteration, you overwrite the content with last one.
Better to use .append instead of .html, but you have to make the area empty before : jQuery("#fetchmember").empty();

get the title from a context

How Do I select the title of the context? I am suppose to select it to change the title of the page.
var handler = function(context){
document.title = //context's title
....
}
//sample context from ajax request
var context = '<!DOCTYPE html><html>\
<head><title>Hello</title></head>\
<body>\
Click Here<p>This is my sentence.</p>\
</body></html>';
.ajax{(
...
success: function(data){
handler(data);
}
});
EDIT: I forgot the doctype just incase it's necessary. The context was from an AJAX Request.
You can use regex to extract the title as well
var matches = context.match(/<title>(.*?)<\/title>/);
var title = matches[1];
Demo
Just discovered a way to do this, the non-regex way
title = $(context).filter("title");
console.log(title.html());
Demo
The second argument to the jquery $ function is the context
So you can try $("title",$(context)).text()
this should do:
var title = $(context).eq(0).text()
var handler = function(context){
$xml=$.parseXML(context);
console.log($($xml).find('title').text());
}
var context = '<html><head><title>Hello</title></head><body>Click Here<p>This is my sentence.</p></body></html>';
handler(context);
http://jsfiddle.net/MdvWq/
Please check http://jsfiddle.net/sethunath/UAt5p/
$(context)[1].innerHTML
returns the title
I don't know why, but nobody mention this. This is a popular method to search for elements in responses:
$(function() {
var context = '<html><head><title>Hello</title></head><body>Click Here<p>This is my sentence.</p>< /body></html > ';
alert($(context).filter("title").html()); //Use filter to get elements you want
alert($(context).filter("a").html()); //Will get HTML of that link (<a>)
alert($(context).filter("body > p").html()); //HTML of <p>
});​
http://jsfiddle.net/DerekL/THdaC/2/

Categories