I am new to JS and would like to set a default value when the page loads. My HTML:
<!DOCTYPE html>
<html>
<head>
<script src="js/jquery.min.js"></script>
<script src="shared/shiny.js" type="text/javascript"></script>
<script src="css/bootstrap-3.3.6-dist/js/bootstrap.min.js"></script>
<link rel="stylesheet" href="css/bootstrap-3.3.6-dist/css/bootstrap.min.css">
<script src="js/app.js" type="text/javascript"></script>
</head>
<body>
<div class="dropdown" id="country_select">
<button class="btn btn-default dropdown-toggle" type="button"
data-toggle="dropdown">Country<span class="caret"></span></button>
<ul class="dropdown-menu">
<li><a href="#" country-code="C1">Country1</a></li>
<li><a href="#" country-code="C2">Country2</a></li>
<li><a href="#" country-code="C3">Country3</a></li>
</ul>
</div>
</body>
I have tried some suggestions from similar questions but these do not work in my case.The first one is:
var main = function(){
var data_start_type = "C1";
var $data_type_elem = $('[country-code='+data_start_type+']');
$('#country_select li a').text($data_type_elem.text());
$("#country_select li a").on("click", function () {
var country_selected=$(this).text();
Shiny.onInputChange('this_country', country_selected); //send selected data to the server script
});
};
$(document).ready(main);
The code above sets all the options of the drop down as 'Country1'. I found this suggestion that I put this below my JS code but it does not set any default value.
$('#country_select li a')[2].click();
Could someone please point out how I can fix this?
You want be able to do this with a list, since a list is not made for dropdown-menues.
Try this:
<select>
<option>.....</option>
<option selected="selected">Select a language</option>
<option>.....</option>
<option>.....</option>
<option>.....</option>
</select>
Are you sure you placed your code correctly?
var main = function(){
var $menu_items = $("#country_select li a");
$menu_items.on("click", function () {
Shiny.onInputChange('this_country', $(this).text());
});
$menu_items[0].click(); // 0 for Country1, 1 for Country2, etc
};
$(document).ready(main);
Edit: Here's a demo . If you open the Console at the bottom, you'll see the default value.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.