Passing new line characters into function javascript - javascript

I receive an array from the controller which I put into the table and generate links to "edit", "delete", and "merge". The "edit" event passes variable to function which opens dialog where variable lSynonyms should be presented as multiline similarly to Synonyms shown in the table. I tried:
lSynonyms += data[i]['varNames'][j]['varTeamID'] + ' > ' + data[i]['varNames'][j]['varName'] + '\r\n';
lSynonyms += data[i]['varNames'][j]['varTeamID'] + ' > ' + data[i]['varNames'][j]['varName'] + '\n';
Both give me error "Unterminated string constant" when I click "edit" link. If I remove \r\n the function is working good except data in textarea is not appeared as new lines. How to pass these new line correctly?
Code which generates table
for (i = 0; i < data.length; i++) {
var Synonyms = '';
var lSynonyms = '';
for (j = 0; j < data[i]['varNames'].length; j++) {
Synonyms += data[i]['varNames'][j]['varTeamID'] + ' > ' + data[i]['varNames'][j]['varName'] + '<br/>';
lSynonyms += data[i]['varNames'][j]['varTeamID'] + ' > ' + data[i]['varNames'][j]['varName'] + "\r\n";
}
$("#teamstable > tbody").append('<tr><td>' + data[i]["stdTeamID"] + '</td><td>' + data[i]["stdName"] + '</td><td>' + Synonyms + '</td><td><a onclick="updateform(' + data[i]["stdTeamID"] + ',\'' + data[i]["stdName"] + '\',\'' + lSynonyms + '\')">edit</a>' + ' <a onclick="mergeform(' + data[i]["stdTeamID"] + ')">merge</a> ' + '<a onclick="RemoveTeam(' + data[i]["stdTeamID"] + ')">delete</a></td></tr>');
}
Function to open dialog:
function updateform(id, rTeam, sTeam) {
$('#id').val(id);
$('#iID').val(id);
$('#sTeam').val(rTeam);
$('#vTeam').val(sTeam);
updatedialog.dialog("open");
}
The dialog which is opening:
<div id="dialog-form" title="Update Dialog">
<form>
<fieldset>
<label for="iID">Match ID</label>
<input type="text" name="iID" id="iID" value="" class="text ui-widget-content ui-corner-all" />
<label for="rTeam">Standardized Name</label>
<input type="text" name="sTeam" id="sTeam" value="" class="text ui-widget-content ui-corner-all">
<label for="sTeam">ID > Known Synonyms</label>
<textarea rows="6" id="vTeam" class="form-control" style="min-width: 100%"></textarea>
<input type="hidden" name="id" id="id" value="" />
<input type="submit" tabindex="-1" style="position:absolute; top:-1000px">
</fieldset>
</form>
</div>

So, the idea here is that the data variable is available in context. It might be a bit more of a hassle if you don't have it available.
But the idea is that you just need a pointer back to the data, and you can get it later. And you can put the pointer in the HTML in a data- property.
So here, the HTML construction is the same, except that instead of calling updateform from the HTML, you just tell it "use index 0" or whatever. I also added a class onto the links to make them easier to identify when attaching the event handlers.
From that piece of information, you can create the necessary arguments to updateform and call it.
$(function() {
function updateform(id, rTeam, sTeam) {
/* same as before */
console.log(id, rTeam, sTeam);
}
var data = [{
stdTeamID: 912,
stdName: "912",
varNames: [{
varTeamID: 913,
varName: "913"
},
{
varTeamID: 914,
varName: "914"
}
]
}];
for (var i = 0; i < data.length; i++) {
var Synonyms = "";
for (j = 0; j < data[i]['varNames'].length; j++) {
Synonyms += data[i]['varNames'][j]['varTeamID'] + ' > ' + data[i]['varNames'][j]['varName'] + '<br/>';
}
$("#teamstable > tbody").append('<tr><td>' + data[i]["stdTeamID"] + '</td><td>' + data[i]["stdName"] + '</td><td>' + Synonyms + '</td><td><a class="updateform" data-index="' + i + '"">edit</a>' + ' <a onclick="mergeform(' + data[i]["stdTeamID"] + ')">merge</a> ' + '<a onclick="RemoveTeam(' + data[i]["stdTeamID"] + ')">delete</a></td></tr>');
}
$('#teamstable').on('click', '.updateform', function(e) {
var i = parseInt($(this).attr('data-index'), 10);
var teamId = data[i]["stdTeamID"];
var teamName = data[i]["stdName"];
var lSynonyms = "";
for (var j = 0; j < data[i]['varNames'].length; j++) {
lSynonyms += data[i]['varNames'][j]['varTeamID'] + ' > ' + data[i]['varNames'][j]['varName'] + '\r\n';
}
updateform(teamId, teamName, lSynonyms);
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table id="teamstable">
<tbody>
</tbody>
</table>

Related

Why does my code return </h2> when I set it to return as </input>?

I have a todo site with edit mode and view mode. Full code is at https://repl.it/#UCYT5040/Notekeeper, but this is the JS I am having an issue with.
let editMode = true;
let items = 1
function toggleEditMode() {
console.log(editMode)
if (editMode == true) {
editMode = false;
for (i = 0; i < items; i++) {
document.getElementById('item' + (i + 1)).innerHTML = "<h1 id=\"itemTitle" + (i + 1) + "\">" + document.getElementById('itemTitle' + (i + 1)).value + "</h1>"
}
} else {
editMode = true
for (i = 0; i < items; i++) {
document.getElementById('item' + (i + 1)).innerHTML = "<input type=\"text\" id=\"itemTitle" + (i + 1) + "\" value=\"" + document.getElementById('itemTitle' + (i + 1)).innerHTML + "></input>"
}
}
}
This ends up with
`<div id="item1">
<input type="text" id="itemTitle1" value="New Note">
</h1>
</div>`,
but it should be
`<div id="item1">
<input type="text" id="itemTitle1" value="New Note"></input>.
</div>`.
These are void elements(<input>). This means they aren't designed to contain text or other elements, and as such do not need — and in fact, cannot have — a closing tag in HTML.
document.getElementById('item' + (i + 1)).innerHTML = "<input type=\"text\" id=\"itemTitle" + (i + 1) + "\" value=\"" + document.getElementById('itemTitle' + (i + 1)).innerHTML + "/>"

How to fire the javascript function in the textboxes that are getting created dynamically in asp .net

Below is my code which creates the textboxes dynamically in modal pop up each time when i click add button and removes the text boxes in that row each time when i click remove button which is working fine till here the problem is i have the javascript function which validates the month date and year in text box that if if we give any number greater than 12 it shows message that month should be less than 12 similarly for date also it will accept till 31 but if it is greater than 31 it shows error message and similarly year also but this is done for our asp text boxes how can i make this javascript function to work in modal pop where the textboxes are created dynamically
<script type="text/javascript">
function GetDynamicTextBox(value) {
if (value == "") {
FillDropdown()
return '<input name = "DynamicTextBox" value = "' + value + '" placeholder="MM/DD/YYYY"></input> <select name = "DynamicTextBox" >"' + Hours + '"</Select><b>:</b><select name = "DynamicTextBox">"' + Min + '"</Select>' +
' <input id="btnAdd123" type="button" value="Add" onclick="AddTextBox()" /><input type="button" value="Remove" onclick = "RemoveTextBox(this)" />'
//Min = "";
// Hours = "";
//
}
}
var HHEdit = "";
var MMEdit = "";
function GetDynamicTextBox1(value) {
values = value.split(' ');
one = values[0];
two = values[1];
values = two.split(':');
three = values[0];
Four = values[1];
HHEdit = three;
MMEdit = Four;
FillDropdown()
return '<input name = "DynamicTextBox" value = "' + one + '" placeholder="MM/DD/YYYY"></input> <select name = "DynamicTextBox" >"' + Hours + '"</Select><b>:</b><select name = "DynamicTextBox">"' + Min + '"</Select>' +
' <input id="btnAdd123" type="button" value="Add" onclick="AddTextBox()" /><input type="button" value="Remove" onclick = "RemoveTextBox(this)" />'
// $('.DynamicTextBox').val(one);
}
function AddTextBox() {
var div = document.createElement('DIV');
div.innerHTML = GetDynamicTextBox("");
document.getElementById("TextBoxContainer").appendChild(div);
}
function AddTextBox1() {
var inputCount = document.getElementById('TextBoxContainer').getElementsByTagName('input').length;
if (inputCount == "0") {
var div = document.createElement('DIV');
div.innerHTML = GetDynamicTextBox("");
document.getElementById("TextBoxContainer").appendChild(div);
}
}
function RemoveTextBox(div) {
document.getElementById("TextBoxContainer").removeChild(div.parentNode);
}
function RecreateDynamicTextboxes() {
var values = eval('<%=Values%>');
if (values != null) {
var html = "";
for (var i = 0; i < values.length; i++) {
html += "<div>" + GetDynamicTextBox1(values[i]) + "</div>";
}
document.getElementById("TextBoxContainer").innerHTML = html;
}
}
var Hours = "";
var Min = "";
function FillDropdown() {
for (var i = 0; i < 24; i++) {
if (i >= 0 && i <= 9) {
if (HHEdit != "" && HHEdit == i) {
Hours += '<option value="' + i + '" selected="selected">' + " 0" + i + " " + '</option>'
}
else {
Hours += '<option value="' + i + '">' + " 0" + i + " " + '</option>';
}
}
else {
if (HHEdit != "" && HHEdit == i) {
Hours += '<option value="' + i + '" selected="selected">' + " " + i + " " + '</option>';
}
else {
Hours += '<option value="' + i + '">' + " " + i + " " + '</option>';
}
}
}
for (var i = 0; i < 60; i++) {
if (i >= 0 && i <= 9) {
if (MMEdit != "" && MMEdit == i) {
Min += '<option value="' + i + '" selected="selected">' + " 0" + i + " " + '</option>';
}
else {
Min += '<option value="' + i + '">' + " 0" + i + " " + '</option>';
}
}
else {
if (MMEdit != "" && MMEdit == i) {
Min += '<option value="' + i + '" selected="selected">' + " " + i + " " + '</option>';
}
else {
Min += '<option value="' + i + '">' + " " + i + " " + '</option>';
}
}
}
//$('#Item').append(option);
}
window.onload = RecreateDynamicTextboxes;
</script>
Code for date month year validation using javascript
var fdate = document.getElementById('<%=txtFromDate.ClientID%>').value;
var tdate = document.getElementById('<%=txtToDate.ClientID%>').value;
var fromdate = fdate.split('/');
var fmonth = fromdate[0];
var fdate = fromdate[1];
var fyear = fromdate[2];
if (fmonth > 12) {
message += "From Month Should Be Less Than 12." + "\n";
}
if (fdate > 31) {
message += "From Date Cannot Be Greater Than 31." + "\n";
}
if (fyear < 2000 || fyear > 2030) {
message += "From Year Should Be In Between 2000 to 2030." + "\n";
}
var todate = tdate.split('/');
var tmonth = todate[0];
var tdate = todate[1];
var tyear = todate[2];
if (tmonth > 12) {
message += "To Month Should Be Less Than 12." + "\n";
}
if (tdate > 31) {
message += "To Date Cannot Be Greater Than 31." + "\n";
}
if (tyear < 2000 || tyear > 2030) {
message += "To Year Should Be In Between 2000 to 2030."+"\n";
}
if (message != "") {
alert(message);
return false;
}
From Date: <asp:TextBox ID="txtFromDate" Width="113px" runat="server" placeholder="mm/dd/yyyy" onkeypress="return IsValidData(event);" ondrop="return false;"
onpaste="return false;" onkeyup="this.value=this.value.replace(/^(\d\d)(\d)$/g,'$1/$2').replace(/^(\d\d\/\d\d)(\d+)$/g,'$1/$2').replace(/[^\d\/]/g,'')"></asp:TextBox> <span id="error" style="color: Red; display: none">* Invalid Character</span>
To Date: <asp:TextBox ID="txtToDate" Width="113px" runat="server" placeholder="mm/dd/yyyy" onkeypress="return IsValidData(event);" ondrop="return false;"
onpaste="return false;" onkeyup="this.value=this.value.replace(/^(\d\d)(\d)$/g,'$1/$2').replace(/^(\d\d\/\d\d)(\d+)$/g,'$1/$2').replace(/[^\d\/]/g,'')"></asp:TextBox><span id="Span1" style="color: Red; display: none">* Invalid Character</span>
I don't see that you've actually defined your IsValidData function. I'm assuming that you've done that somewhere...
You can pass this to your IsValidData function as a parameter to work with the element that triggered the event in your function..
Also you should try moving away from inline functions to event listeners. This stack post (JavaScript click event listener on class) talks about applying an event listener to a class of DOM elements.
If you are using jQuery, since you included this tag, then I'd encourage you to look into the jQuery .on() function to add event handlers. It'll make everything much easier (http://api.jquery.com/on/)
If you do not know what a javascript event listener is, then start here (https://www.w3schools.com/js/js_htmldom_eventlistener.asp)

how to use image tag

Can someone help me out in inserting an image in the below function. I've used a json object that returns values for campaignid and campaignname.
<script>function searchedCampaigns(data) {
if (data[0].length > 0) {
var searchcmp = "";
for (var j = 0; j < data[0].length; j++) {
var input = document.createElement("input");
console.log(input.name);
searchcmp += '<input type="checkbox" id=' + data[0][j].campaignId + ' name=' + data[0][j].campaignName + '/>' +
**// image to be inserted here**
+ data[0][j].campaignName + '<br/>'; // value
}
$("#newcamp").html(searchcmp);
}}</script>
output should be this
I'm getting the checkbox as well as the campaign name. I want the image in between these two.
As simple as this..
searchcmp += '<input type="checkbox" id=' + data[0][j].campaignId + ' name=' + data[0][j].campaignName + '/>' +
'<img src="'+yourimageurlfromdata+'"/>'+
'data[0][j].campaignName + '<br/>';
I suggest you a code like this one:
<input type="checkbox"><img src="Image.PNG">Test</img></input>
Also, based on your code, it can be updated like this:
searchcmp += '<input type="checkbox" id=' + data[0][j].campaignId + ' name=' + data[0][j].campaignName + '><img src=' + YOUR_URL_LOCATION + ' />' + data[0][j].campaignName + '</input><br/>';
Where YOUR_URL_LOCATION, can be in the JSON or somewhere else.
It's going to display something like this:

Edit HTML table and capture changes as POST using Javascript

I just started off with javascript and html, so please correct me if I am doing it the wrong way. I was trying to edit an html form table.
{%extends 'base.html'%}
{%block content%}
<html>
<body>
<h4> Search results</h4>
<p id="data"></p>
<style>
table, th, td {
border: 1px solid black;
border-collapse: collapse;
}
th, td {
padding: 5px;
}
</style>
<form id="update" action="/update/" method="POST">
<script>
function onEdit(btn)
{
var id=btn.id;
if(btn.value=="Edit") {
var input = document.getElementsByName("name"+id);
for(i = 0;i < input.length; i++) {
document.getElementById(input[i].id).removeAttribute("Readonly");
} //End of for loop
document.getElementById(id).value="Save";
return false;
}
if(btn.value=="Save") {
for(i = 0;i < input.length; i++) {
document.getElementById(input[i].id).setAttribute("Readonly", "readonly");
}
document.getElementById(id).value="Edit";
return false;
}
} // End of Function onEdit()
{% autoescape off %}
var data = {{ search|safe }}; //This will be the json value returned by django view
{% endautoescape %}
text = ''
var out = "<table style=\"width:50%\">";
out += "<tr>";
out += "<th>Domain</th>";
out += "<th>Points to</th>";
out += "<th>Type</th>";
out += "<th>TTL</th>";
out += "</tr>";
var i
var id = 0;
for ( var i = 0; i < data.records.length; i++) {
id = id + 1;
out += "<tr><td>" +
"<input readonly='readonly' name='name" + id + "' id='" + data.records[i].domain + "' value='" + data.records[i].domain + "'type='text'/>" +
"</td><td>" +
"<input readonly='readonly' name='name" + id + "' id='" + data.records[i].record_points_to + "' value='" + data.records[i].record_points_to +"'type='text'/>" +
"</td><td>" +
data.records[i].record +
"</td><td>" +
"<input readonly='readonly' name='name" + id + "' id='" + data.records[i].ttl + "' value='" + data.records[i].ttl + "'type='text'/>" +
"</td><td>" +
"<input id='" + id + "' value='Edit' onclick='return onEdit(this)' type='button'/>" +
"</td></tr>";
}
out += "</table>"
total = data.meta.total_records
page = data.meta.page
records_returned = data.records.length
records_shown = ((data.meta.page - 1) * 30) + data.records.length
out += records_shown + " returned of " + total
page = data.meta.page + 1
link = window.location.href
if (records_shown == total){
out += " End "
}
else{
url ="<a href='" + updateQueryStringParameter(link, "page", page) + "'> Next"
out += url
}
function updateQueryStringParameter(uri, key, value) {
var re = new RegExp("([?&])" + key + "=.*?(&|$)", "i");
var separator = uri.indexOf('?') !== -1 ? "&" : "?";
if (uri.match(re)) {
return uri.replace(re, '$1' + key + "=" + value + '$2');
}
else {
return uri + separator + key + "=" + value;
}
}
document.getElementById("data").innerHTML = out
</script>
<input type="submit" value="Submit">
</form>
I have the page displayed as expected.
What I am trying to achieve is to make these html tables editable, which is also working half way. When I click the Edit button, the table link turns editable, and I can change the value, and the Edit button changes to Save.
But when I click on "Save" button, firebug error shows
TypeError: input is undefined
for(i = 0;i < input.length; i++) {
----------↑
(Yes, arrow points to var i)
I want to capture the changes when I click on Save, and whatever changes in that page should be captured via POST method once clicked on the submit button below. Submit is redirected to action="/update/". Please let me know what should I do.
to avoid such problems please define all variables at the beginning of their scope (the scope is a function in case of Javascript)

passing value to a dynamic created function in javascript

I am having some problems while creating a dynamic webpage in javascript.
My idea is to read a list of events and people signed up on them. I create a page with all events (each event is a button) and clicking on one of them, see the list of users.
This works fine. But now, I am adding a button to export some of these users to an excel file. And I want to add a button with an onClick function like this:
...onclick=functionÇ(id_Event, numberOfUsers, listOfUsers)...
Inside of the html code generated by javascript. I found some problems also doing like this so I changed so:
var td = document.createElement("td");
var input = document.createElement("input");
input.setAttribute("type","button");
input.setAttribute("value","Exportar a Excel CSV");
input.onclick = function() {
saveExcelFunctionControl(arrayNumberUsersInEvents[i], response);
};
td.appendChild(input);
document.getElementById("added"+element[i].id_Event).appendChild(td);
I created a global array called arrayNumberUSersInEvents in which I am adding in each possition, people subscribed. i, is the id counter for each position.
But even this, I am getting an undefined while reading the value of the firsdt parameter. I think it is a problem of dynamic data, I am not executing the function I want to each time I click the button. Do you know how to do something like this?
To sum up: My problem is that I want to pass some arguments to a function in a dynamic created page. I don't know how to pass the data and read the correct parameters inside.
I added my code because one user asked for it:
for(i = 0; i < element.length; i++){
$(".eventsControl").append(
'<li id="listControl'+ element[i].id_Event +'">'+
'<a href="#EventControl' + element[i].id_Event + '"' + 'data-transition="slidedown">'+
'<img class="crop" src= "' + element[i].image + '" />'+
'<h2>' + element[i].name + '</h2>'+
'<p>' + "Desc: " + element[i].description +'</p>'+
'</a>'+
'</li>'
).listview('refresh');
//console.log(response);
//BUCLE for setting all users in each event. Better use some string and after, join all of them
header = ' <div width="100%" data-theme = "e" data-role="page" id='+ element[i].id_Event +
' data-url="EventControl' + element[i].id_Event + '"> ' +
' <div data-theme = "a" data-role="header"><h1>Lista de Asistencia</h1> ' +
' </div>'+
' <div data-role="content"> ' +
' <fieldset data-role="controlgroup" data-type="horizontal" style="text-align: center">' +
' <div style="width: 500px; margin: 0 auto;">';
//header = header + '<input data-theme = "c" onclick="saveExcelFunctionControl(this)" id="saveExcelControl' + element[i].id_Event + '" type="button" value = "Guardar a excel"></br>';
eval('var numberUsers' +element[i].id_Event + "=1");
arrayNumberUsersInEvents[i] = 0;
if(response.length>0){
bucle = ' <table width="100%" border="1" align="left"><tr>'+
' <th>Nombre</th>'+
' <th>Primer apellido</th>'+
' <th>Segundo apellido</th>'+
' <th>NIF</th>'+
' <th>Asistencia</th>'+
' </tr>';
for(iData = 0; iData < response.length; iData++){
if(element[i].id_Event == response[iData].id_Event){
//console.log(response[iData].name);
bucle = bucle + '<tr><td>'+ eval('numberUsers' +element[i].id_Event) +'</td><td>'+ response[iData].name +'</td><td>'+
response[iData].surname1 +'</td><td>'+
response[iData].surname2 +'</td><td>'+
response[iData].NIF + '</td>'+
'<td> '+
'<input type="checkbox" id="checkBox'+element[i].id_Event+'_'+iData+'" name="option'+iData+'" value="'+iData+'"> '+
'</td>'+
'</tr>';
eval('numberUsers' +element[i].id_Event + "++");
arrayNumberUsersInEvents[i] = arrayNumberUsersInEvents[i]+1;
}
}
//header = header + '<input data-theme = "a" onclick="saveExcelFunctionControl(\""element[i].id_Event "\","" + numberUsers + "\",\"" + response+ "\"")" id="saveExcelControl' + element[i].id_Event + '" type="button" value = "Guardar a excel"></br>';
//header = header + '<input data-theme = "a" onclick="saveExcelFunctionControl(""+numberUsers+"")" id="saveExcelControl' + element[i].id_Event + '" type="button" value = "Guardar a excel"></br>';
bucle = bucle + '</table>';
$("#controlList").after(header + bucle + '<div id=added'+element[i].id_Event+'></div>');
var td = document.createElement("td");
var input = document.createElement("input");
input.setAttribute("type","button");
input.setAttribute("value","Exportar a Excel CSV");
input.onclick = function() {
saveExcelFunctionControl(arrayNumberUsersInEvents[i], response);
};
td.appendChild(input);
document.getElementById("added"+element[i].id_Event).appendChild(td);
}
}
},
error: function(xhr, status, message) { alert("Status: " + status + "\nControlGetEventsRegister: " + message); }
});
You can use closure to pass parameters to dynamically created onclick handler:
input.onclick = (function() {
var arr = arrayNumberUsersInEvents[i];
var resp = response;
return function() {
saveExcelFunctionControl(arr, resp);
}
})();
How do JavaScript closures work?
var td = document.createElement("td");
var input = "<input type='button' value='Exportar a Excel CSV'";
input+= "onclick='saveExcelFunctionControl(""" +arrayNumberUsersInEvents[i]+""","""+ response+""");' />";
};
td.textContent=input;
document.getElementById("added"+element[i].id_Event).appendChild(td);
try this way

Categories