Converting object to string JQuery/JS/HTML - javascript

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>

Related

How can I add data params to an HTML string and get a string back?

I got a string like this:
var select_string = '<select><option>1</option><option>2</option></select>';
I need to add some data params to select in this string and get this string back in order to get the following:
select_string = '<select data-param1="param1" data-param2="param2"><option>1</option><option>2</option></select>';
I tried to use jQuery functions like .html() or .text() but it did not work. Like this:
select_string = $(select_string).data('param1', 'param1').html() //or .text()
Any ideas how to make it work would be helpful. Thank you.
You can use attr to add that attributes to the element
var select_string = '<select><option>1</option><option>2</option></select>';
var select = $(select_string).attr({
'data-param1': 'param1',
'data-param2': 'param2'
});
console.log(select.prop('outerHTML'));
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
Since your attribute name starts with data-, if you want to get the value, you can use:
select.data('param1'); // param1
select.data('param2'); // param2
EDIT: Titulum is right, jquery is not needed here.
But here is the working example usign jquery
var selectString = '<select><option>1</option><option>2</option></select>';
var $select = $(selectString);
$select.attr("prop_key","prop_value");
var selectChanged = $select.prop('outerHTML');
console.log(selectChanged)
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
You don't need jQuery for this:
const myElement = document.createElement('div');
myElement.innerHTML = "<select><option>1</option><option>2</option></select>";
const selectElement = myElement.getElementsByTagName("select")[0];
selectElement.setAttribute("data-param1", "param1");
selectElement.setAttribute("data-param2", "param2");
You could use indexOf and substr() to split it into 2 parts, insert your new text, and put it back together again.
var first_half = select_string.substr(0, select_string.indexOf('>'));
var second_half = select_string.substr(select_string.indexOf('>'));
select_string = first_half + ' data-param1=\"param1\" data-param2=\"param2\" ' + second_half;

Compare variable values in scriplet and javascript

I have a jsp file with a scriptlet tag, I am getting the values of .properties file in it .I have a java script tag in which I am storing the value from the dropdown in a variable. On selecting some value in the dropdown I want to compare it with the property in the scriptlet and if it is equal a value from properties file must populate in my textbox. I have tried the following code but it is not working
My scriplet tag
<%
Properties prop = new Properties();
String propFileName = "server. properties";
InputStream inputStream = getClass().getClassLoader().getResourceAsStream(propFileName);
if (inputStream != null) {
prop.load(inputStream);
} else {
throw new FileNotFoundException("property file '" + propFileName + "'not found in the classpath");
}
String appName = prop.getProperty("Demo_name");
String link = prop.getProperty("Demo_Links");
String database = prop.getProperty("DemoApps_DataBase");
%>
JavaScript
<script type="text/javascript">
function OnSelectionChange(serverName) {
var selectedOption = serverName.options[serverName.selectedIndex];
var txtbox=document.getElementById('serverLink');
var appName=<%=appName%>;
var links=<%=link%>
alert(appName.value);
if(selectedOption.value==appName.value){
txtbox.value=links.value;
}
}
</script>
Try this code. Is Your selected value is case sensitive?
<script type="text/javascript">
function OnSelectionChange(serverName) {
var selectedOption = serverName.options[serverName.selectedIndex].value;
var txtbox=document.getElementById('serverLink');
var demoName='<%=demoServer%>';
var testName='<%=testingServer%>';
var PNGName='<%=pngServer%>';
var DCPName='<%=dcpServer%>';
var demoLink='<%=demoLink%>';
var testLink='<%=testingLink%>';
var pngLink='<%=pngLink%>';
var dcpLink='<%=dcpLink%>';
if(selectedOption==appName){
txtbox.value=links;
}
if(selectedOption==PNGName){
txtbox.value=pngLink;
}
if(selectedOption==DCPName){
txtbox.value=dcpLink;
}
if(selectedOption==demoName){
txtbox.value=demoLink;
}
}
</script>
Using scriplets populate the values in a hidden field from your scriplet like :
<input id=hiddenPops type="hidden" name="Language" value="English">prop1=value2;prop2=value3</input>
In your javascript get the value of the above field using getElementById(hiddenPops )
Split the value string into array or as desired and you can work with it to match the keys and fetch the corresponding values.
Note: Its a solution but your approach is not great. Try to use modern JS frameworks which could allow you to talk to the server directly or simply use Ajax

highlight search word using jquery in MVC

I have MVC controller that returns a list containing a search string.
public ActionResult GetList(string searchString)
{
ViewData["searchString"] = searchString;
if (String.IsNullOrEmpty(searchString))
{
var persons = db.Persons.ToList();
return View(persons);
}
else{
var persons = db.Persons.Where(p=> p.Title.Contains(searchString)).ToList();
return View(persons);
}
}
In the view the list is displayed in a table. I want to highlight the searchString (or at most the td that contains the searchString). The following is my jquery where I attempted to achieve this. I have tried putting this bit of code in a separate .js script or in the view itself and I have also tried to change the code in several ways but it wouldn't work. It appears like the searchString remains null even if the content of my ViewData has changed.
$(document).ready(function () {
var textToHighligt = #ViewData["searchString"];
$("#simpleSearchButton").click(function () {
$("td:contains(textToHighligt)").css("background-color", "yellow");
});
});
I think this:
var textToHighligt = #ViewData["searchString"];
$("td:contains(textToHighligt)").css("background-color", "yellow");
should be concatenated:
var textToHighligt = '#ViewData["searchString"]'; //<---put in quotes
$("td:contains("+textToHighligt+")").css("background-color", "yellow");
I think you can do otherwise if it is not happening in the javascript file , create a hidden field and populate the value from the ViewBag
#Html.Hidden("hiddensearchString", (string)ViewBag.searchString)
For the ViewData
#Html.Hidden("FirstName", ViewData["searchString"])
and then the javascript read the value like this
var searchString = $("#hiddensearchString").val();
In you code you can also try this using of the single quote.
var textToHighligt = '#ViewData["searchString"]';

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();

Getting the selected listValue of <s:select> in 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.

Categories