i am trying to get a variable by javascript and using it in my C# block but it looks like impossible.
this is my HTML:
<select class="form-control" id="Category">
#foreach (var item in Model.Categori)
{
<option value="#item.CategoriId">#item.CategoriName</option>
}
</select>
<div id="Container"></div>
and this is my javascript code:
$('#Category').on('change', function (e) {
$("#Container").append(`#foreach (var item in Model.YetkinlikKategorileri.Where(x => x.Id == $('#Category').val()))
{
<p>hello</p>
}`);
});
well is it possible to do something like that ? if not is there another way ?
You need something like this:
<script>
var data = [
#foreach (var item in dataList)
{
#Html.Raw("'"+item+"',")
}
];
$('#Category').on('change', function (e) {
var lst = data.find(/*Your condition*/);
for (var i = 0; i < lst.length; i++) {
$("#Content").append("<p>hello</p>" + data[i] + "<br/>");
}
};
</script>
dataList is the data which comes from server.
But in this way, you should get all data from server and put it into javascript data array. Then you should make lst by finding in data array.
But using ajax is better than this razor code.
Related
I have the following case that I am having a hard time solving.
In the image what I try to do is look for the documents of the selected process and that they are displayed in the table.
This is done with ajax, jsp and servlet.
For the select dropdown, this is the code where I list the processes through java and jsp classes.
<select class="form-control js-example-basic-single" name="sucursal">
<%
MantenedorProcesosLMD md = new MantenedorProcesosLMD();
List<procesoslmd> ld = md.listar_proc_lista(con);
for (procesoslmd p : ld) {
%>
<option value="<%=p.getLDM_ID()%>">
<%=p.getLDM_NOMBPROCESOS()%>
</option>
<%
}
%>
</select>
This is my code in sql where by means of the IDPROCESOS parameter I look for the documents.
SELECT
D.IDLDMDOCUMENTOS,
LT.NOMBRETIPO,RTRIM(D.LDM_NOMENCLATURA) AS NOMENCLATURA,
RTRIM(D.LDM_NOMBRE_DOCUMENTO) AS TITULO,
D.LDM_FECHA_SUBIDA,D.LMD_RUTA_DOCUMENTO
FROM LDM_DOCUMENTOS_ D
LEFT JOIN LDM_PROCESOS_ LP ON LP.IDLDMPROCESOS = D.IDLDMPROCESOS
LEFT JOIN LDM_TIPO_DOCUMENTO_ LT ON LT.IDTIPODOC = D.IDTIPODOC
WHERE LP.IDLDMPROCESOS = #IDLDMPROCESOS
But so far I can't get to the code to find the documents by clicking the search button, I'm trying to do it with ajax I'm still collecting information.
implement this ajax code where I get the value of my select dropdown the IDPROCESOS and if it brings me the documents so far I can show it in the console, but I want to add it to the table but when I click on the search button
$(document).ready(function () {
$('select[name=procesoldm]').on('change', function () {
$.ajax({
type: 'GET',
url: '../sv_proxdocumento',
data: 'codigoproceso='+$('select[name=procesoldm]').val(),
statusCode: {
404: function () {
alert('PAGINA NO ENCONTRADA');
},
500: function () {
alert('ERROR EN EL SERVIDOR');
}
},
success: function (dados) {
var pegadatos = dados.split(":");
console.log(pegadatos);
for (var i = 0; i < pegadatos.length -1; i++){
var codigodocumento = pegadatos[i].split("-")[0];
var nombretipo = pegadatos[i].split("-")[1];
console.log(nombretipo);
}
}
});
})
});
How do I pass that found data to a table with ajax, thanks for your time.
how it should look in the table when clicking the search button
You can use another for-loop after spliting your values and then on each iteration append td inside some variable using += and then add this generated html inside your table.
Demo Code :
$(document).ready(function() {
/*$('select[name=procesoldm]').on('change', function() {
$.ajax({
//other codes..
success: function(dados) {*/
//var pegadatos = dados.split(":");
//just for demo
var pegadatos = ["1-abc-abd-abdd-2/1/12", "2-abc2-abd2-abdd2-2/22/12", ""]
var html = ""; //declare this
//loop through main array
for (var i = 0; i < pegadatos.length - 1; i++) {
var values = pegadatos[i].split("-") //split values
html += `<tr>`
for (var j = 0; j < values.length; j++) {
html += `<td>${values[j]}</td>` //splited values..
}
html += `<td>--Visitor--</td>`
html += `</tr>`
}
$("table tbody").html(html) //add result inside tbody
/* }
});
})*/
});
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/css/bootstrap.min.css">
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.0/jquery.min.js"></script>
<table class="table">
<thead>
<tr>
<th>No</th>
<th>DocumentType</th>
<th>DocumentNaming</th>
<th>title</th>
<th>date</th>
<th>visitor</th>
</tr>
</thead>
<tbody>
</tbody>
</table>
I have some problem with javascript limit. I am using Razor and filling javascript array with razor like this:`
var KriterAlanlariHtml = new Array();
#{
int sayac = 0;
string html = "";
foreach (var group in Model.GrupDTO)
{
if (group != null && group.ListAreaDTO != null)
{
foreach (var area in group.ListAreaDTO)
{
html = BuildHtmlTag(area);
<text>
KriterAlanlariHtml[#sayac] = "#MvcHtmlString.Create(html)";
</text>
sayac++;
}
}
}
}
`
After this codes View.cshtml filling Javascript array with html codes. But I couldnt this array in JavaScript. Because of javascript limitations. If I check the elements on Chrome, I am seeing like screenshot-1.
Screenshoot-1
Screenshoot-2
I coulndt use like this code: KriterAlanlariHtml[25] .Chrome giving this error:
KriterAlanlariHtml is not defined
How can i solve this problem ? (HTML is not wrong.)
You need to add javascript code inside script tag, the updated code is below
<script>
var KriterAlanlariHtml = new Array();
</script>
#{
int sayac = 0;
string html = "";
foreach (var group in Model.GrupDTO)
{
if (group != null && group.ListAreaDTO != null)
{
foreach (var area in group.ListAreaDTO)
{
html = BuildHtmlTag(area);
<script>
KriterAlanlariHtml[#sayac] = "#MvcHtmlString.Create(html)";
</script>
sayac++;
}
}
}
}
I've created a dynamic dropdown list with jQuery and JavaScript. I'm hoping someone can take a look and let me know if this is an appropriate way to handle this type of task. I'm specifically curious to know if this code is scalable, and will it perform well? Next, would it be suggested to use a switch statement instead of several if statements in the JavaScript I have below? If so, why? I'd like to store this to be reused anytime I implement a solution like this, but as I'm new to JavaScript I don't completely trust my work yet.
JSFIDDLE: http://jsfiddle.net/6vrpF/
HTML:
<select id='parent'>
<option value='test'>test</option>
<option value='sure'>sure</option>
<option value='cool'>cool</option>
<option value='best'>best</option>
</select>
<select id='child'>
</select>
JavaScript:
function newDropdown()
{
var html = ""
for(i=0; i<arguments.length; i++)
{
html += "<option value='"+arguments[i]+"'>"+arguments[i]+"</option>"
}
$("#child").append(html)
}
$("#parent").on("change",function(){
$('#child').text("")
var selection = $("#parent").val()
if(selection == 'test') {newDropdown('a','b','c')}
if(selection == 'sure') {newDropdown('d','e','f')}
if(selection == 'cool') {newDropdown('g','h','i')}
if(selection == 'best') {newDropdown('j','k','l')}
});
updated the fiddle
http://jsfiddle.net/6vrpF/4/
var parentChild = {
"test" :['a','b','c'],
"sure" :['d','e','f'],
"cool" :['g','h','i'],
"best" :['j','k','l']
};
function newDropdown()
{
var html = ""
for(i=0; i<arguments.length; i++)
{
html += "<option value='"+arguments[i]+"'>"+arguments[i]+"</option>"
}
$("#child").append(html)
}
$("#parent").on("change",function(){
$('#child').text("")
var selection = $("#parent").val();
newDropdown( parentChild[selection].join(",") );
});
You need to get your data in the JSON format as mentioned/defined above
Edit: this is the updated fiddle which will give options one by one
http://jsfiddle.net/6vrpF/6/
var parentChild = {
"test" :['a','b','c'],
"sure" :['d','e','f'],
"cool" :['g','h','i'],
"best" :['j','k','l']
};
function newDropdown()
{
var array = arguments[0];
var html = ""
for(i=0; i<array.length; i++)
{
html += "<option value='"+array[i]+"'>"+array[i]+"</option>"
}
$("#child").append(html)
}
$("#parent").on("change",function(){
$('#child').text("")
var selection = $("#parent").val();
newDropdown( parentChild[selection] );
});
I have a Dropdown box, Which is getting filled by values from mySQL database, here is the part of the script that I am using to fill the drop down.
var details = JSON.parse(data);
console.log(details);
for ( i = 0; i < details.aaData.length; i++) {
console.log(details.aaData[i].id);
$('select#package-id option').append(details.aaData[i].id);
}
and here is HTML,
<select name="package" name="package-id" id="package-id">
<option></option>
</select>
But the dropdown shows the values as 1234 where as I am expecting them as,
1
2
3
4
Any workarounds for this?
try Changing This:
var details = JSON.parse(data);
console.log(details);
for ( i = 0; i < details.aaData.length; i++) {
console.log(details.aaData[i].id);
$('select#package-id option').append(details.aaData[i].id);
}
to this:
var details = JSON.parse(data);
console.log(details);
for ( i = 0; i < details.aaData.length; i++) {
console.log(details.aaData[i].id);
$('select#package-id').append("<option value='"+details.aaData[i].id+"'>"+details.aaData[i].id+"</option>");
}
it looks right now like you may be creating a bunch of option inside the blank option.
I've a javascript array and I want to iterate them with jstl for each and display the output.
<script type="text/javascript">
phoneFilterObject = {
allPhoneArray: []
}
var specPhone = [];
OnUserSelect(){
//loop through allPhoneArray
//do filtering logic and populate specPhone array
}
</script>
<body>
// here I want to iterate through the specPhone array and display it. also I want to populate hidden variables with values from specPhoneArray
// i want to do the following
<c:if test="${!empty specPhoneArray}">
<c:foreach items="${specPhoneArray}" var="phoneObj">
<c:out value="${phoneObj.name}"/>
<input type="hidden" name="phoneID" value="<c:out value='${phoneObj.id}'/>"/>
</c:foreach>
</c:if>
</body>
i'm not able to read javascript array in jquery. I tried the following
specPhoneArray = $(specPhoneArray); &
specPhoneArray = ${specPhoneArray};
this.specPhoneArray = $(specPhoneArray);
any help is appreciated.
You can't do that with JSTL but you can accomplish it by staying in JavaScript world. First create a template and add it to your page:
<script id="phone-tmpl" type="text/html">
{name}
<input type="hidden" name="phoneID" value="{id}"/>
</script>
then in JavaScript add a little template helper:
function t(s,d) {
for (var p in d) {
s = s.replace(new RegExp('{'+p+'}','g'), d[p]);
}
return s;
}
and then you can do (assuming you are using jQuery):
var phoneTmpl = $('#phone-tmpl').html(),
html = "";
for (var i = 0, l = specPhone.length; i < l; i++) {
html += t(phoneTmpl, specPhone[i]);
}
// do something with html
$('body').append(html);
You can also check this demo: http://jsfiddle.net/d5jaY/