Razor code creates new line inside of JavaScript string - javascript

I have a JavaScript variable which should hold Razor code to be generated when a button clicked:
$("#addNewCatBtn").click(function(e){
e.preventDefault();
counter++;
var html = '<label class="col-md-2 control-label">İçerik Kategorisi</label><div class="col-md-3">'+
'#{ List<SelectListItem> modCatList = new List<SelectListItem>(); if (Model.CategoryList != null && Model.CategoryList.Count > 0) { foreach (var cat in Model.CategoryList) { modCatList.Add(new SelectListItem { Text = cat.CategoryName, Value = cat.ModCategoryId.ToString(), Selected = false }); } } else { modCatList.Add(new SelectListItem { Text = "Kategori Yok", Value = "0", Selected = true }); } } #Html.DropDownList("ModCategoryId_"+Html.Raw("counter"), modCatList, new { #class = "select2-select-00 col-md-12 full-width-fix required", #data_rule_required = "true", #data_msg_required = ModerationWEB.ErrorMessages.NOTVALID_MODCAT_EMPTY }) </div> '
+'<label class="col-md-2 control-label">Süreç Kategorisi</label> <div class="col-md-3"> '+
'#{ List<SelectListItem> flowCatList = new List<SelectListItem>(); if (Model.FlowCatList != null && Model.FlowCatList.Count > 0) { foreach (var cat in Model.FlowCatList) { flowCatList.Add(new SelectListItem { Text = cat.CategoryName, Value = cat.FlowCategoryId.ToString(), Selected = false }); } } else { flowCatList.Add(new SelectListItem { Text = "Kategori Yok", Value = "0", Selected = true }); } } #Html.DropDownList("FlowCatId_" +Html.Raw("counter"), flowCatList, new { #class = "select2-select-00 col-md-12 full-width-fix required", #data_rule_required = "true", #data_msg_required = ModerationWEB.ErrorMessages.NOTVALID_MODCAT_EMPTY, #multiple = "multiple", #size = "5" }) </div>';
$("#modFlowCatGroupDiv").html();
});
When it generates the list elements, the options come in new lines and it causes JavaScript to give Unterminated string constant error. How can I stop this?

In your code modCatList and flowCatList should be constructed outside of the JS.
If I remember correctly Html.DropDownList returns a MvcHtmlString so you could add the following in your JS:
var html = '<label class="col-md-2 control-label">İçerik Kategorisi</label><div class="col-md-3">'+
'#Html.DropDownList("ModCategoryId_"+Html.Raw("counter"), modCatList, new { #class = "select2-select-00 col-md-12 full-width-fix required", #data_rule_required = "true", #data_msg_required = ModerationWEB.ErrorMessages.NOTVALID_MODCAT_EMPTY }).ToHtmlString().Replace(Environment.NewLine, "") </div> '
+'<label class="col-md-2 control-label">Süreç Kategorisi</label> <div class="col-md-3"> '+
'#Html.DropDownList("FlowCatId_" +Html.Raw("counter"), flowCatList, new { #class = "select2-select-00 col-md-12 full-width-fix required", #data_rule_required = "true", #data_msg_required = ModerationWEB.ErrorMessages.NOTVALID_MODCAT_EMPTY, #multiple = "multiple", #size = "5" }).ToHtmlString().Replace(Environment.NewLine, "") </div>';
You may need to unescape the rendered code so,
$("#modFlowCatGroupDiv").html(unescape(html));

Eventually, I decided to try like below, and it worked:
var str =
'<div class="form-group"><label class="col-md-2 control-label">İçerik Kategorisi</label>' +
'<div class="col-md-3">' +
'<select class="select2-select-00 col-md-12 full-width-fix required select2-offscreen"'
+ ' data-msg-required="Moderasyon Kategorisi boş olamaz!" data-rule-required="true" data-val="true" data-val-number="The field ModCategoryId must be a number."'
+ ' data-val-required="The ModCategoryId field is required." id="ModCategoryId_' + counter + '" name="ModCategoryId_' + counter + '" tabindex="-1">' +
#{foreach(var item in modCatList)
{
#:'<option value="#item.Value">#item.Text</option>' +
}
}
'</select>'
+ '</div>'
+ '<label class="col-md-2 control-label">Süreç Kategorisi</label> '
+'<div class="col-md-3">' +
'<select class="select2-select-00 col-md-12 full-width-fix required select2-offscreen" data-msg-required="Moderasyon Kategorisi boş olamaz!"'
+ ' data-rule-required="true" id="FlowCatId_' + counter + '"name="FlowCatId_' + counter + '" tabindex="-1">' +
#{
foreach (var item in flowCatList)
{
#:'<option value="#item.Value">#item.Text</option>' +
}
}
'</select>'
+ '</div>' + '<div class="col-md-2"></div></div>';
$("#modFlowCatGroupDiv").append(str);

Related

how to use arrays within select dropdown select

I am trying to populate a dropdown select with an array using jQuery.
Here is my code:
<div class="form-group row">
<label class="col-xl-3 col-lg-3 col-form-label">Numbers</label>
<div class="col-lg-9 col-xl-6">
<div class="form-inline">
<select name="sabb" class="req form-control form-control-lg form-control-solid" id="age-range-2" autocomplete="off" required />
</select>
<label class="col-xl-1 col-lg-1 col-form-label">to</label>
<select name="eabb" class="req form-control form-control-lg form-control-solid" id="second-2" autocomplete="off" required />
</select>
</div>
</div>
</div>
My accompanying jQuery is as follows:
$(function() {
var $select = $("#age-range-2");
for (i = 18; i <= 60; i++) {
$select.append($('<option></option>').val(i).html(i))
}
$("#age-range-2").change(function() {
var val = parseInt($("#age-range-2").val());
$("#second-2").html("");
for (i = val + 1; i <= 60; i++) {
$("#second-2").append("<option value='" + i + "'>" + i + "</option>");
}
});
});
I am trying to add an array that includes numbers and letters instead of a for loop which should be something like this: var numbers = [1K, 2K, 3K, 4K, 5K];
Here is a visual:
I think this what you need:
for (i = 1; i <= 50; i++) {
var o = new Option( i + "K", i);
$(o).html( i + "K");
$("#age-range-2").append(o);
}
for (i = 18; i <= 60; i++) {
var o = new Option( i + "K", i);
$(o).html( i + "K");
$("#second-2").append(o);
}
You can see result in JSFiddle here
Edited:
If you need predefined array:
var numbers = [1,4,8,14,20,50,100];
$.each(numbers, function( index, value ) {
var o = new Option( value + "K", value);
$(o).html( value + "K");
$("#age-range-2").append(o);
});

using .on to listen for event not working

I am trying to use .on to listen for an event.
html:
<div class="form-group" id="group_names">
<label> Names: </label><br>
<input type="text" class="form-control name" placeholder="name1" id="name1" name ="name1"><br>
</div>
JS:
for (n = 1; n < inputLength+3 ; ++n) {
var test2 = document.getElementById(dude+n);
$(test2).on('change', '#group_names', forFunction);
}
The change to the input field is not being recognized.
Additionally, I am hoping .on will recognize changes made to new html i am injecting using the following function:
var dude = "name";
function forFunction() {
for (m = 1; m < inputLength + 1; ++m) {
var test = document.getElementById(dude + m)
if (test.value != "") {
var txt = "<input type=\"text\" class=\"form-control name\" placeholder=" + dude + (m + 1) + " id=" + dude + (m + 1) + " name=" + dude + (m + 1) + "><br>";
document.getElementById('group_names').insertAdjacentHTML('beforeend', txt);
//function updateHTML(txt)
}
}
}
I am not sure if my syntax for .on is correct. I am trying to use "#group_names" as the selector, but not sure if I am doing it right.
Thanks
You probably want to use event delegation on the parent div instead.
$('#group_names').on('change', 'input.form-control.name', forFunction);
Consider the following jQuery code.
$(function() {
var inputFields = $("input[id*='name']");
function forFunction(evt) {
console.log(evt.type);
inputFields.each(function(i, el) {
var n = i + 1;
if ($(el).val() != "") {
console.log("Value Detected");
$("<input>", {
type: "text",
class: "form-control name",
placeholder: "group" + n,
id: "group" + n,
name: "group" + n
}).insertBefore("#group_names");
}
});
}
inputFields.on("change", forFunction);
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="form-group" id="group_names">
<label> Names: </label><br>
<input type="text" class="form-control name" placeholder="name1" id="name1" name="name1"><br>
</div>
This should work for all of the Input items.

Can't read checked value from checkbox returned from json

My web application has a Dropdown List which displays users and what I want is, when the field change happens it updates a set of check-boxes to either true or false, depending on the value stored in the DB.
My controller
public IActionResult Admin(string message) {
EditUser euModel = new EditUser();
List<EditUser> editUser= new List<EditUser> {
new EditUser { UserID = 0, Username = "--Select User--"},
new EditUser { UserID = 1, Username = "Unchecked"},
new EditUser { UserID = 2, Username = "Checked"}
};
ViewBag.haveAccess = HaveAccess;
List<EditUser> HaveAccess = new List<EditUser> {
new EditUser { DepartmentID = 1, DepartmentName = "IT", HaveAccess=false},
new EditUser { DepartmentID = 2, DepartmentName = "Financial", HaveAccess=false},
new EditUser { DepartmentID = 3, DepartmentName = "Sales", HaveAccess=false}
};
var SelectedValues = HaveAccess.Where(a => a.HaveAccess == true).Select(u => u.DepartmentID).ToArray();
ViewBag.haveAccess = new MultiSelectList(HaveAccess, "DepartmentID", "DepartmentName", SelectedValues);
return View(euModel);
}
My view
<form asp-controller="Admin" asp-action="HaveAccess" method="post" class="form-horizontal" role="form">
<div class="alert-danger" asp-validation-summary="ModelOnly"></div>
<div class="col-xs-12 col-sm-6 col-md-6 col-lg-4">
<label asp-for="Username" class="control-label" value=""></label>
<select asp-for="UserID" class="form-control" id="changeid"
asp-items="#(new SelectList(ViewBag.editUser, "UserID", "Username"))"></select>
</div>
<div class="col-xs-12 col-sm-6 col-md-6 col-lg-4">
<ul asp-for="haveAccess" class="control-label" id="haveAccess">
#foreach (var item in (new SelectList(ViewBag.haveAccess, "DepartmentID", "DepartmentName", "HaveAccess")))
{
<li class="checkbox-label">
<div class="checkbox">
#Html.CheckBox("HaveAccess", #item.Selected)
#Html.Label("HaveAccess", #item.Text)
</div>
</li>
}
</ul>
</div>
</form>
My js on-change for changeid (user ddl)
<script type="text/javascript">
$(document).ready(function () {
$("#changeid").change(function () {
var url = '#Url.Content("~/")' + "Admin/GetAccess";
var ddlsource = "#changeid";
$("#haveAccess").hide();
var items = " ";
$.getJSON(url, { UserID: $(ddlsource).val() }, function (data) {
$("#haveAccess").empty();
$.each(data, function (i, HaveAccess) {
items +=
"<li class='checkbox-label'>" +
"<div class='checkbox'>" +
"<input id='HaveAccess_" + HaveAccess.value + "' name='HaveAccess_" + HaveAccess.value + "' type='checkbox' " + "checked='" + HaveAccess.selected + "'/>" +
"<label for='HaveAccess_" + HaveAccess.value + "'>" + HaveAccess.text + "</label>" +
"</div>" +
"</li>";
});
$("#haveAccess").html(items);
$("#haveAccess").show();
});
})
})
</script>
JsonResult GetAccess
public JsonResult GetAccess(string UserID) {
List<EditUser> HaveAccess = new List<EditUser>();
//Getting Data from Database
con.Open();
string ua_query = "select gu.deptid as DepartmentID, d.department as DepartmentName , gu.have_access as Have_Access " +
"from it_materials_users u " +
"inner join it_materials_gu gu on u.id = gu.userid " +
"inner join it_materials_dept d on d.id = gu.deptid " +
"where u.id = '" + UserID + "'";
OracleCommand ua_cmd = new OracleCommand(ua_query, con);
OracleDataAdapter ua_da = new OracleDataAdapter(ua_cmd);
DataTable ua_dt = new DataTable();
ua_da.Fill(ua_dt);
foreach (DataRow ua_dr in ua_dt.Rows) {
HaveAccess.Add(new EditUser {
DepartmentID = Convert.ToInt16(ua_dr["DepartmentID"]),
DepartmentName = Convert.ToString(ua_dr["DepartmentName"]),
HaveAccess = Convert.ToBoolean(ua_dr["Have_access"])
});
}
con.Close();
var SelectedValues = HaveAccess.Where(a => a.HaveAccess == true).Select(u => u.DepartmentID).ToArray();
return Json(new MultiSelectList(HaveAccess, "DepartmentID", "DepartmentName", SelectedValues));
}
My load page works fine, but when I change the value of user the js triggers and the JsonResult GetAccess works as expected. But all the check-boxes at the browser are always checked even when the return of the sql HaveAccess is false.
Can someone point what I'm doing wrong?
Thanks in advance for your help.
Regards
all the check-boxes at the browser are always checked even when the return of the sql HaveAccess is false.
To fix above issue, please modify the code as below to set checked property for your checkboxes based on HaveAccess.selected value.
$.getJSON(url, { UserID: $(ddlsource).val() }, function (data) {
console.log(data);
$("#haveAccess").empty();
$.each(data, function (i, HaveAccess) {
var ischecked = HaveAccess.selected ? "checked" : "";
//console.log(ischecked);
items +=
"<li class='checkbox-label'>" +
"<div class='checkbox'>" +
"<input id='HaveAccess_" + HaveAccess.value + "' name='HaveAccess_" + HaveAccess.value + "' type='checkbox' " + ischecked + "/>" +
"<label for='HaveAccess_" + HaveAccess.value + "'>" + HaveAccess.text + "</label>" +
"</div>" +
"</li>";
});
$("#haveAccess").html(items);
$("#haveAccess").show();
});

adding and removing multiple form field

Hi I am sharing my code below. Can anyone help me for small changes.While creating new box the add button is at fixed position.I need make it dynamic.
$(document).ready(
function () {
var max_fields = 6;
var wrapper = $(".items");
var add_button = $(".add-more");
var x = 1;
$(add_button)
.click(
function (e) {
e.preventDefault();
if (x < max_fields) {
x++;
$(wrapper)
.append(
'<div class="row add-more1"><div class="col-sm-11"><div class="col-sm-4"><form role="form"><div class="form-group">'
+ '<select class="full-width form-control"><option value="AK">- Select -</option><option value="AK">Name</option>'
+ '<option value="HI">Email</option><option value="AK">Contact No.</option><option value="HI">Assigned To</option>'
+ '<option value="AK">Next Action From</option><option value="HI">Next Action To</option><option value="AK">Status</option></select>'
+ '</div></form></div>'
+ '<div class="col-sm-4"><form role="form"><div class="form-group">'
+ '<select class="full-width form-control"><option value="AK">- Select -</option><option value="AK">=</option>'
+ '<option value="HI">></option><option value="AK">>=</option><option value="HI"><</option><option value="AK"><=</option>'
+ '<option value="HI">like</option></select>'
+ '</div></form></div>'
+ '<div class="col-sm-4"><form role="form"><div class="form-group">'
+ '<input type="text" class="form-control input-sm" name="name" placeholder="Enter value"/>'
+ '</div></form></div></div>'
+ '<span class="remove_field"><i class="fa fa-times"></i></span></div>');
}
});
$(wrapper).on("click", ".remove_field",
function (e) {
e.preventDefault();
$(this).parent('div').remove();
x--;
})
});
please add css maybe its work :
.remove_field{
position: absolute;
right: 0;
}

jQuery split() returns undefined

i have problam idont know why bat i see all time "undefined" in all "field_input"
when i try to add from jquery .split
function field_include()
{
var form_id = $( ".form" ).val();
$.ajax({
url: 'ajax/field_include.php',
type: 'POST',
data: {
form_id : form_id
},
success: function(data) {
var fields = data;
var field = fields.split(";").filter(Boolean);
$.each(field, function(i, val){
var field_val = val.split(",");
$( ".addfromform" ).append('<div class="form-group"><label class="col-lg-2 control-label mt10">'+field_val[2]+'</label><div class="col-xs-10"><label for="'+field_val[1]+'" class="field prepend-icon"><input type="'+field_val[0]+'" name="'+field_val[1]+'" id="first_name" class="gui-input" placeholder="'+field_val[3]+'" autocomplete="off"><label for="'+field_val[1]+'" class="field-icon"><i class="fa fa-user"></i></label></label></div></div>').fadeIn('slow');
});
}
});
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
string from "field_include.php":
1,first_name,First Name:,First Name,1;1,last_name,Last Name:,Last Name,2;1,email,Email:,Email,3;1,job,Job title:,Job title,4;
how i can fix ?
Try chaining .filter(Boolean) to fields.split(";") to remove empty string "" at last index of field where character at last index of string is ";" which would return undefined at var field_input = val.split(','); as val would be empty string ""
var field = fields.split(";").filter(Boolean);
var fields = "1,first_name,First Name:,First Name,1;1,last_name,Last Name:,Last Name,2;1,email,Email:,Email,3;1,job,Job title:,Job title,4;";
var field1 = fields.split(";");
var field2 = fields.split(";").filter(Boolean);
$.each(field2, function(i, val) {
var field_val = val.split(",");
$("body").append('<div class="form-group"><label class="col-lg-2 control-label mt10">' + field_val[2] + '</label><div class="col-xs-10"><label for="' + field_val[1] + '" class="field prepend-icon"><input type="' + field_val[0] + '" name="' + field_val[1] + '" id="first_name" class="gui-input" placeholder="' + field_val[3] + '" autocomplete="off"><label for="' + field_val[1] + '" class="field-icon"><i class="fa fa-user"></i></label></label></div></div>');
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>

Categories

Resources