How to assign js value to the java variable? - javascript

<select name="DB">
<option value="findmaximum" onclick="functionse()" style=font-size:20px>findmaximum</option>
<option value="marklist" onclick="functionse()"style=font-size:20px>marklist</option>
</select>
<script type="text/javascript">
function functionse(){
var DBname=document.getElementsByName('DB');
<%
String DBname = (String) request.getAttribute("DB");
System.out.println(DBname);
ResultSet resultsettable=DBconnector.tables(DBname);
String Tablenames[]=new String[0];
int i=0;
while(resultsettable.next()){
String Tablename=resultsettable.getString("TABLE_NAME");
Tablenames[i++]=Tablename;
}
%>
}
print DBname vaule but return null

Related

How to print selected string in select option drop down in csharp cshtml ASP.NET?

I new in ASP.NET.
I try to print selected string in select option drop down but Compilation error.
Compilation Error Description: An error occurred during the
compilation of a resource required to service this request. Please
review the following specific error details and modify your source
code appropriately.
Compiler Error Message: CS0201: Only assignment, call, increment,
decrement, await, and new object expressions can be used as a
statement
Here is my cshtml code.
#{ string FromAMPM = "AM"; }
<select id="FromAMPM" name="FromAMPM" class="form-control js-select">
<option value=""></option>
<option value="AM" #if (FromAMPM == "AM") { "selected"; } else { ""; }>AM</option>
<option value="PM" #if (FromAMPM == "PM") { "selected"; } else { ""; }>PM</option>
</select>
What wrong? Thanks
You can use ternary conditional operator in your case:
#{ string FromAMPM = "AM"; }
<select id="FromAMPM" name="FromAMPM" class="form-control js-select">
<option value=""></option>
<option value="AM" #(FromAMPM == "AM" ? "selected='selected'" : "")>AM<</option>
<option value="PM" #(FromAMPM == "PM" ? "selected='selected'" : "")>PM<</option>
</select>
The best way would be separate logic and html
#{
var FromAMPM = "PM";
var items = new List<SelectListItem>
{
new SelectListItem { Value= "", Text="Select" },
new SelectListItem { Value= "AM", Text="AM" },
new SelectListItem { Value="PM", Text="PM"}
};
}
you don't neeed selected code, it will automatically select asp-for value
<select id="fromAMPM" asp-for="#FromAMPM" class="form-control js-select" asp-items="#items"></select>

JS+ASP Net Core Get data from controller

the question arose: How to get data from the controller in asp net core using js?
I tried to send a post request head-on, but it seems to me there is a more elegant solution
At the same time, I need this to happen when the html of the Select element changes
I wrote a script that changes the field when the select changes
function Change_Aud() {
var x = document.getElementById("Levelid").value;
document.getElementById("Hardware_La").value = x ;
}
Controller example
public async Task<IActionResult> Get_Hardware_Unit(int id)
{
Level level = _context.Levels.Where(p => p.Number == id.ToString()).First();
return Content(level.Public_Hardware.ToString());
}
Test page code in cshtml:
#{
ViewData["Title"] = "Home Page";
int count = 5;
}
<script src="https://code.jquery.com/jquery-2.2.4.js" integrity="sha256-iT6Q9iMJYuQiMWNd9lDyBUStIq/8PuOW33aOqmvFpqI=" crossorigin="anonymous"></script>
<script>
function myFunction(selectObject) {
var value = selectObject.value;
$("#selectnum").html(value);
backendfunc(value);
}
function backendfunc(value) {
$.ajax({
url: "/Test/Get_Hardware_Unit",
type: "GET",
data: { id: value },
success: function (res) {
$("#convertnum").html(res);
},
error: function (hata, ajaxoptions, throwerror) {
$("#convertnum").html("convert failed");
}
});
}
</script>
<div>
<select name="num" id="num-select" onchange="myFunction(this)">
<option value="">--Please choose an option--</option>
<option value="1">One</option>
<option value="2">Two</option>
<option value="3">Three</option>
</select>
</div>
<br />
<br />
<div>
You select value is : <span id="selectnum"></span>
</div>
<br />
<br />
<div>
After backend converted, here is : <span id="convertnum"></span>
</div>
My function in Controller:
public async Task<IActionResult> Get_Hardware_Unit(int id) {
string result = string.Empty;
if (id == 1) {
result = "①";
}
if (id == 2)
{
result = "②";
}
if (id == 3)
{
result = "③";
}
return Content(result);
}
Test Result

Parameterise DropDown values as URL using JavaScript?

I have the code below. It has 3 dropdown option values. Currently, on change of dropdown selection an alert is thrown.
Now, I want to achieve the following: parameterise my dropdown values as URL's, so that i.e. when I enter the following URL in a browser: file://test.ds.waq.cb.uk/anywhere/UserData/PSStore02/u1718987/Desktop/new.html with ?mySelect=BMW at the end, then the browser opens the dropdown with the value BMW populated.
Or if I enter file://test.ds.waq.cb.uk/anywhere/UserData/PSStore02/u1718987/Desktop/new.html?mySelect=Audi, the browser opens the dropdown with Audi populated.
<!DOCTYPE html>
<html>
<body>
<p>Select a new car from the list.</p>
<select id="mySelect" onchange="myFunction()">
<option value="Audi">Audi
<option value="BMW">BMW
<option value="Volvo">Volvo
</select>
<p id="demo"></p>
Need to modify below script, to parameterise dropdown selection as URL, please advise.
<script>
function myFunction() {
var x = document.getElementById("mySelect").value;
alert (document.getElementById.innerHTML = "You selected: " + x);
}
</script>
</body>
</html>
You can easily fetch the url's parameter using expressions and some conditions to select the option. Change mySelect value in url to check it.
JAVASCRIPT:
function getUrlVars() {
var vars = {};
var parts = window.location.href.replace(/[?&]+([^=&]+)=([^&]*)/gi, function(m,key,value) {
vars[key] = value;
});
return vars;
}
$(document).ready(function(){
var data = getUrlVars()["mySelect"];
if(data == "Audi"){
$('select').prop('selectedIndex', 0);
}
else if(data == "BMW"){
$('select').prop('selectedIndex', 1);
}
else if(data == "Volvo"){
$('select').prop('selectedIndex', 2);
}
});
HTML:
<select>
<option class="Audi">Audi</option>
<option class="BMW">BMW</option>
<option class="Volvo">Volvo</option>
</select>
use this answer to extract search queries. Then just set value on load with the proper value.
<script>
function setValue(value) {
document.getElementById("mySelect").value = value;
alert (document.getElementById.innerHTML = "You selected: " + x);
}
</script>
UPDATE
to have both in the same script.
<script>
function setValue(value) {
document.getElementById("mySelect").value = value;
alert (document.getElementById.innerHTML = "You selected: " + x);
}
let urlParams = new URLSearchParams(window.location.search);
setValue(urlParams.get('mySelect');
</script>
You can read url params once select box loads, see below code
HTML:
<!DOCTYPE html>
<html>
<body>
<p>Select a new car from the list.</p>
<select id="mySelect" onchange="myFunction()" onload="setMySelect()">
<option value="Audi">Audi
<option value="BMW">BMW
<option value="Volvo">Volvo
</select>
<p id="demo"></p>
<script>
function setMySelect() {
var urlParams = new URLSearchParams(window.location.search);
var mySelect = urlParams.get('mySelect');
if(mySelect)
document.getElementById("mySelect").value = mySelect;
}
function myFunction() {
var x = document.getElementById("mySelect").value;
alert (document.getElementById.innerHTML = "You selected: " + x);
}
</script>
</body>
</html>
You could try the following.
var url = new URL(window.location);
var params = new URLSearchParams(url.search.slice(1));
for (let [key, value] of params.entries()) {
if(params.has(key) && key == "mySelect") {
document.getElementById(key).value = value;
}
}
document.getElementById("mySelect").addEventListener("change", (e) => {
params.set("mySelect",e.target.value);
url.search = params.toString();
let new_url = url.toString();
window.location.assign(new_url);
})
I needed the following window.onload as this function was not getting loaded.
<!DOCTYPE html>
<html>
<body>
<p>Select a new car from the list.</p>
<select id="mySelect" onchange="myFunction()" onload="setMySelect()">
<option value="Audi">Audi</option>
<option value="BMW">BMW</option>
<option value="Volvo">Volvo</option>
</select>
<p id="demo"></p>
<script>
<!-- function setMySelect() { -->
window.onload = function() {
var urlParams = new URLSearchParams(window.location.search);
var mySelect = urlParams.get('mySelect');
if(mySelect)
document.getElementById("mySelect").value = mySelect;
}
function myFunction() {
var x = document.getElementById("mySelect").value;
alert (document.getElementById.innerHTML = "You selected: " + x);
}
</script>
</body>
</html>

Unable to count select item

I facing a problem here when using select.Items.Count.
situation 1:
<select id="PrimaryArea" style="width: 100px" required tabindex="6" runat="server">
<option value="A">Item1</option>
<option value="B">Item2</option>
<option value="C">Item3</option>
<option value="D">Item4</option>
</select>
In c#
int PrimaryAreaCount=PrimaryArea.Items.Count // return 4
situation 2: option add programmatically
<select id="SecondaryArea" style="width: 100px" required tabindex="7" runat="server">
</select>
in Javascript: return correctly when check using javascript
var select = document.getElementById("<%= SecondaryArea.ClientID %>");
var js = JSON.stringify(<%= SecondaryTable %>);
var js2 = JSON.parse(js);
var len = js2.length;
var i = 0;
while (i < len) {
var new_option = new Option(js2[i].ref_desc, js2[i].cd);
select.options[select.options.length] = new_option;
i += 1;
}
In C#
int SecondaryAreaCount=SecondaryArea.Items.Count // always return 0
What should I do to get the right answer for SecondaryAreaCount in C#?
If I understand your second scenario correctly, you start with an empty list of items and then add options in JavaScript.
In this case, you can not calculate the correct count in serverside C# code, because the JavaScript will only be executed after the page has been served to the client.
One solution would be to use an additional hidden input to post back the count result.
<input id="SecondaryAreaCount" type="hidden" value="0" />
<script>
// your existing JS loop here ...
var countResult = document.getElementById("SecondaryAreaCount");
countResult.value = i; // var i is select.options.length after the while loop
</script>

can we change java variable value by using javascript in jsp?

Is it possible to change java variable value on some function by using javascript in JSP?
eg. If I have to change the value on onchange event in the select box. such as
<select id="search-field" onchange="report(this.value)">
<option value="a">a</option>
<option value="b">b</option>
<option value="b">a</option>
</select>
-------------------------------------
<%
String check = "";
%>
function report(period) {
if(period=="a") {
alert('test'+period);
<%
check = "a";
%>
} else if(period=="b") {
alert('test'+period);
<%
check = "b";
%>
} else if(period=="c") {
alert('test'+period);
<%
check = "c";
%>
}
}
is this possible?

Categories

Resources