Button after div that contains dynamic elements without touch HTML - javascript

i need an help.
I have this code and i have to put a Save button to the end for store the changes or the new entry in DB.
I have the problem that i haven't idea to how put button in the end without change HTML code because i can't, i wuold insert button via javascript,
how can i do?
p.s: The problem is that i can't insert in those function because the function under here is called everytime a press a button, if a press another time is called another, and again.
p.s2: Tell me if the code is ok, in other case tell me how can i improve this
Thank you
$().ready(function() {
//Creation of array to simulate data from DB
var obj1 =
{
id: "1",
name: "Bryan",
surname: "Del Bianco"
};
var obj2 =
{
id: "2",
name: "Luca",
surname: "Del Bianco"
};
var exampleOfDatabase = new Array();
exampleOfDatabase.push(obj1);
exampleOfDatabase.push(obj2)
visualizzaModifica(exampleOfDatabase, $("#divTeamLeaderProduzione"))
function visualizzaModifica(array, div)
{
div.html("");
div.append("<br>");
let i = 1;
array.forEach(function(e) {
div.append(
"<div id='div" + i + "' class='input-group'>" +
"<input type='text' id='inputModificaNome" + i + "' class='form-control' value='" + e.name + "'>" +
"<input type='text' id='inputModificaCellulare" + i + "' class='form-control' value='" + e.surname + "'>" +
"</div>"
);
i++;
});
aggiungiInput(i, div);
}
function aggiungiInput(i,div)
{
if($("#div"+i).length == 0)
{
var next = $("<div>",
{
id: 'div'+i,
class: 'input-group'
});
var inputNome = $('<input>',
{
id: 'inputModificaNome'+i,
type: 'text',
class: 'form-control'
});
var inputCellulare = $('<input>',
{
id: "inputModificaCellulare"+i,
type: 'text',
class: 'form-control'
});
next.on('change', function ()
{
aggiungiInput(i+1, div);
});
next.append(inputNome);
next.append(inputCellulare);
div.append(next);
}
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="divTeamLeaderProduzione">
</div>

$().ready(function() {
//Creation of array to simulate data from DB
var obj1 =
{
id: "1",
name: "Bryan",
surname: "Del Bianco"
};
var obj2 =
{
id: "2",
name: "Luca",
surname: "Del Bianco"
};
var exampleOfDatabase = new Array();
exampleOfDatabase.push(obj1);
exampleOfDatabase.push(obj2)
visualizzaModifica(exampleOfDatabase, $("#divTeamLeaderProduzione"))
function visualizzaModifica(array, div)
{
div.html("");
div.append("<br>");
let i = 1;
array.forEach(function(e) {
div.append(
"<div id='div" + i + "' class='input-group'>" +
"<input type='text' id='inputModificaNome" + i + "' class='form-control' value='" + e.name + "'>" +
"<input type='text' id='inputModificaCellulare" + i + "' class='form-control' value='" + e.surname + "'>" +
"</div>"
);
i++;
});
aggiungiInput(i, div);
}
function aggiungiInput(i,div)
{
if($("#div"+i).length == 0)
{
var next = $("<div>",
{
id: 'div'+i,
class: 'input-group'
});
var inputNome = $('<input>',
{
id: 'inputModificaNome'+i,
type: 'text',
class: 'form-control'
});
var inputCellulare = $('<input>',
{
id: "inputModificaCellulare"+i,
type: 'text',
class: 'form-control'
});
next.on('change', function ()
{
aggiungiInput(i+1, div);
});
next.append(inputNome);
next.append(inputCellulare);
div.append(next);
}
$("#btnSave").remove();
div.append("<input type='button' value='Save' id='btnSave' />");
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="divTeamLeaderProduzione">
</div>
I removed the button and placed it when needed. Hope it helps. Cheers..!!

Related

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

Pass JSON result from AJAX to HTML

I am querying a fuseki server using AJAX and the result that I am getting is a JSON object.
I would like to use pagination to go through the result with a limit of records per page. I have tried to send the JSON object to a div in the html file but it is not working. Is there a workaround this? Here is my code:
function myCallBack2(data) {
var all_results = '';
for (var i = 0; i < data.results.bindings.length; i++) {
var bc = '';
if (i % 2 == 0) {
bc = '#b8cddb';
} else {
bc = '#f2f5f7';
}
all_results += '<div class="all_results" style="background-color:' + bc + '">';
for (var j = 0; j < data.head.vars.length; j++) {
var text = data.results.bindings[i][data.head.vars[j]].value;
var type = data.results.bindings[i][data.head.vars[j]].type;
all_results += '<div class="result_row">';
if (type == ('literal')) {
all_results += '<p> ' + data.head.vars[j] + ": " + text + '</p>';
} else {
all_results += '<a href=' + text + " title=" + data.head.vars[j] + '>' + text + '</a>';
}
all_results += '</div>';
}
all_results += '</div>';
}
$('#result').html(all_results);
}
function doSparql() {
var myEndPoint = "http://localhost:3030/Test/query";
name = document.getElementById("search").value;
var requiredName = "?Author foaf:firstName \"" + name + "\".}";
myQuery = ["PREFIX dcterms: <http://purl.org/dc/terms/>",
"PREFIX foaf: <http://xmlns.com/foaf/0.1/>",
"PREFIX locah: <http://data.archiveshub.ac.uk/def/>",
"SELECT ?Register ?Id ?Date ?Type",
"WHERE{",
"?Register dcterms:creator ?Author.",
"?Register dcterms:identifier ?Id.",
"?Register dcterms:type ?Type.",
"?Register locah:dateCreatedAccumulatedString ?Date.",
requiredName
].join(" ");
console.log('myQuery: ' + myQuery);
window.alert(myQuery);
$.ajax({
dataType: "jsonp",
url: myEndPoint,
data: {
"query": myQuery,
"output": "json"
},
success: myCallBack2,
error: myError
});
console.log('After .ajax');
};
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="//raw.github.com/botmonster/jquery-bootpag/master/lib/jquery.bootpag.min.js"></script>
<div id="page-selection1" "></div>
<div id="result " class="result "></div>
<div id="page-selection2 "></div>
<script>
$('#page-selection1,#page-selection2').bootpag({
total: 50,
page: 1,
maxVisible: 5,
leaps: true,
firstLastUse: true,
first: 'First',
last: 'Last',
wrapClass: 'pagination',
activeClass: 'active',
disabledClass: 'disabled',
nextClass: 'next',
prevClass: 'prev',
lastClass: 'last',
firstClass: 'first'
}).on("page ", function(event, num) {
$("#result ").html("Page " + num);
});
</script>
I am expecting to show part of the results instead Page 1, Page 2... in #result according to a limit per page.

Cannot set property 'innerHTML' of null in javascript

guys i have a column which contains text and button and what i want is when click on the button the text changed .. here is my code
var count = 0;
$(document).ready(function() {
$("#jqGrid").jqGrid({
data: data.rows,
datatype: "local",
styleUI: "Bootstrap",
colModel: [
{
label: 'Customer ID',
name: 'CustomerID',
width: 180,
editable: true,
edittype: "custom",
id: "CustomerID",
editoptions: {
custom_element: function(value, options) {
var parts = value.split(' ');
var elemStr = '<div><input size="6" id="txt_"' + count + '" value="' + parts[0] +
'" /><input type="button" size="5" value="..." onclick="setText();"/></div>';
count++;
// return DOM element from jQuery object
return $(elemStr)[0];
},
custom_value: function(elem) {
var inputs = $("input", $(elem)[0]);
var first = inputs[0].value;
return first;
}
}
},
],
});
});
function setText() {
document.getElementById("txt_" + count).innerHTML = "hey";
}
so why it gives me that exception ? .. plz help .. btw i am beginner
the count inside setText is undefined.
1st change onclick function of button to pass the count variable
var elemStr = '<div><input size="6" id="txt_"' + count + '" value="' + parts[0] +
'" /><input type="button" size="5" value="..." onclick="setText(' + count + ');"/></div>';
then accept the count as parameter
function setText(count) {
document.getElementById("txt_" + count).innerHTML = "hey";
}
You can pass count to the function:
var count = 0;
$(document).ready(function() {
$("#jqGrid").jqGrid({
data: data.rows,
datatype: "local",
styleUI: "Bootstrap",
colModel: [
{
label: 'Customer ID',
name: 'CustomerID',
width: 180,
editable: true,
edittype: "custom",
id: "CustomerID",
editoptions: {
custom_element: function(value, options) {
var parts = value.split(' ');
var elemStr = '<div><input size="6" id="txt_"' + count + '" value="' + parts[0] +
'" /><input type="button" size="5" value="..." onclick="setText(' + count + ');"/></div>';
count++;
// return DOM element from jQuery object
return $(elemStr)[0];
},
custom_value: function(elem) {
var inputs = $("input", $(elem)[0]);
var first = inputs[0].value;
return first;
}
}
},
],
});
});
function setText(count) {
document.getElementById("txt_" + count).innerHTML = "hey";
}

loop through div with different elements

I generated elements and put them in MyDiv
$("#MyDiv").append('<input type=text class = "form-control" id=tb' + row.PropertyName + ' ' + 'value="Text' + row.PropertyName + '" />');
$("#MyDiv").append(' <input type="hidden" name="hid" value= "' + row.PropertyId + '">');
Now I need to extract the row.PropertyName and row.PropertyId
I need something like this:
var arrText = new Array();
$('#MyDiv > input[type = text]').each(function () {
var id = $(this).id.val();
var text = $(this).text.val();
var data = {
'id': id,
'text': text
}
I guess this is what you want.
$(function(){
var PropertyName = "pn1";
var PropertyId = "pn2";
$("#MyDiv").append('<input type="text" class = "form-control" id="tb"' + PropertyName + ' ' +
'value="Text' + PropertyName + '" />');
$("#MyDiv").append(' <input type="hidden" name="hid" value= "' + PropertyId + '">');
$('#MyDiv > input[type = "text"]').each(function(){
var id = $(this).val();
var text = $(this).next('input[type = "hidden"]').val();
var data = {
id: id,
text: text
}
alert(data.id + data.text);
})
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div id="MyDiv"></div>
var arrText = [];
$('#MyDiv > input[type=text]').each(function () {
arrText.push({
'id': this.id,
'text': this.value
});
});
console.log( arrText );

Get the ID of a dynamic text field via dynamically created button

See below code. I'm creating two text fields dynamically. In one of those text fields 2 buttons are also created. When either of these buttons are clicked how could I get the ID of the text field that doesn't have buttons?
<button type="button" id="tfButton">Add text</button>
<div id="InputsWrapper"></div>
<div id="OuterWrapper"></div>
$(document).ready(function() {
var tfCont = 0;
var InputsWrapper = $("#InputsWrapper");
var x = InputsWrapper.length;
var namefield = $("#tfButton");
$(namefield).click(function() {
tfCont++;
$(InputsWrapper).append('<div>' + '<div class="name" id="InputsWrapper_0' + tfCont + '">' + '<input type="textarea" id="field_' + tfCont + '" class="fTypex" placeholder="Thought of the day..." data-tfcount="' + tfCont + '"/><button type="button" runclass0">Run</button><button type="button" class="removeclass0">Next</button>' + '<br>' + '</div>' + '</div>');
$("#OuterWrapper").append('<div id="textLayer_' + tfCont + '">' + '<input type="textarea" id="tf_' + tfCont + '" data-tfcount="' + tfCont + '">' + '</div>');
x++;
return false;
});
$(document).on("click blur keyup", "input.fTypex", function() {
var tfc = $(this).data("tfcount");
$("#tf_" + tfc).val(this.value);
});
});
Do you mean something like this?
I know I didn't make use of your data attributes. However, there are million ways to re-include them, I simply thought it was best to show you an easier way without relying on multiple similar ID's, found by using data. That way just seemed like more work and headache, to me anyway.
jsFiddle: live example
$(function() {
function createFields(e) {
var inWrap = $('<div />', { class: 'name-wrapper' }),
nameWrap = $('<div />', { class: 'name' }).appendTo(inWrap),
outWrap = $('<div />');
nameWrap.append(
$('<input />', { class: 'fTypex', placeholder: 'Thought of the day...', type: 'textarea' }),
$('<button />', { text: 'Run', type: 'button' }),
$('<button />', { text: 'Next', type: 'button' })
);
outWrap.append(
$('<input />', { type: 'textarea' })
);
$('#InputsWrapper').append(inWrap);
$('#OuterWrapper').append(outWrap);
}
$(document)
.on('click', '#tfButton', createFields)
.on('click', '#InputsWrapper button', function(e) {
var i = $(this).closest('.name-wrapper').index(),
inp = $('#OuterWrapper input')[i],
$inp = $(inp);
console.log(i, inp, $inp);
// could use like
$('.highlight').removeClass('highlight');
$inp.addClass('highlight');
})
})
And if you insist on your data attributes and that weird runclass0 attr and the other class, here's an alternate fiddle including those little items. You'll notice very little change in structure tho.
Alt jsFiddle
$(function() {
function createFields(e) {
var inWrap = $('<div />', { class: 'name-wrapper' }),
nameWrap = $('<div />', { class: 'name' }).appendTo(inWrap),
outWrap = $('<div />'),
iCnt = $('#InputsWrapper .name-wrapper').length + 1;
nameWrap.append(
$('<input />', { class: 'fTypex', 'data-tfcount': iCnt, id: 'field_'+iCnt, placeholder: 'Thought of the day...', type: 'textarea' }),
'<button runclass0 type="button">Run',
$('<button />', { class: 'removeclass0', text: 'Next', type: 'button' })
);
outWrap.append(
$('<input />', { 'data-tfcount': iCnt, id: 'tf_'+iCnt, type: 'textarea' })
);
$('#InputsWrapper').append(inWrap);
$('#OuterWrapper').append(outWrap);
}
$(document)
.on('click', '#tfButton', createFields)
.on('click', '#InputsWrapper button', function(e) {
var i = $(this).closest('.name-wrapper').index(),
inp = $('#OuterWrapper input')[i],
$inp = $(inp);
// see console for more info: F12 in most of today's browsers
if (console['log']) console.log(i, inp, $inp);
// could use like
$('.highlight').removeClass('highlight');
$inp.addClass('highlight');
})
})

Categories

Resources