<div id="image_div">
<input type="checkbox" />
<img src="1.jpg" />
<input type="checkbox" />
<img src="2.jpg" />
<input type="checkbox" />
<img src="3.jpg" />
<input type="checkbox" />
</div>
On page load, I return a JSON array:
{
"src":["lml7x8nJzI.jpg","TaR7dALIPJ.jpg","TDE2pWgIfa.jpg","tUtuDx1BEf.jpg"],
"checked":["lml7x8nJzI.jpg","TaR7dALIPJ.jpg","tUtuDx1BEf.jpg"]
}
The src contains all the source names of image and checked is the checked type of check boxes.
The checked defines which image is checked (every image has a check box).
I need the final HTML like this:
<div id="image_div">
<input type="checkbox" />
<img src="lml7x8nJzI.jpg" />
<input type="checkbox" checked /> //this is a checked one
<img src="TaR7dALIPJ.jpg" />
<input type="checkbox" checked/> //this is a checked one
<img src="TDE2pWgIfa.jpg" />
<input type="checkbox" /> //this is not
<img src="tUtuDx1BEf.jpg" />
<input type="checkbox" checked /> //this is a checked one
</div>
I can use array contains in JavaScript, or is there a better way?
My attempt:
var initial = "<ul class='gallary'>";
var middle = "";
var end = "</ul>";
var i;
for (i = 0; i < data.src.length; i++)
{
if (data.checked.contains(data.src[i])) // How can I do this?
{
middle = middle +
"<li><img src=" +
"http://localhost/project/user/" +
"<?php echo $this->session->userdata('username');?>" +
"/pages/" +
"<?php echo $this->uri->segment(3);?>" +
"/images/gallery/" +
data.src[i] +
" />" +
"<br /><input type='checkbox' value=" +
data.src[i] +
" checked/></li>";
}
else
{
middle = middle +
"<li><img src=" +
"http://localhost/project/user/" +
"<?php echo $this->session->userdata('username');?>" +
"/pages/" +
"<?php echo $this->uri->segment(3);?>" +
"/images/gallery/" +
data.src[i] +
" />" +
"<br /><input type='checkbox' value=" +
data.src[i] +
" /></li>";
}
}
var complete = initial + middle + end;
$("#project_gallary_layout").html(complete);
You can use indexOf method of Array
var a = ['a', 'b', 'c'];
if (a.indexOf('a') > -1 ) {
//element is in array
} else {
//element is not in array
}
Note that indexOf method is absent in IE6, but there is an implementation available by Mozilla on the same page.
Here's my complete solution using indexOf
$(function(){
var url = 'http://localhost/project/user/<?php echo $this->session->userdata('username'); ?>/pages/<?php echo $this->uri->segment(3); ?>/images/gallery/'
, complete = '<ul class="gallery">'
data.src.forEach(function(src){
complete += '<li><img src="' + url + src + '"><input type="checkbox" value="' + src + '"'
if(data.checked.indexOf(src) > -1){
complete += ' checked'
}
complete += '></li>'
})
$("#project_gallary_layout").html(complete);
})
A better approach would be to replace
{"src":["lml7x8nJzI.jpg","TaR7dALIPJ.jpg","TDE2pWgIfa.jpg","tUtuDx1BEf.jpg"],
"checked":["lml7x8nJzI.jpg","TaR7dALIPJ.jpg","tUtuDx1BEf.jpg"]}
with
{"src":[
{"src": "lml7x8nJzI.jpg", "checked": true},
{"src": "TaR7dALIPJ.jpg", "checked": true},
{"src": "TDE2pWgIfa.jpg", "checked": false},
{"src": "tUtuDx1BEf.jpg", "checked": true}]
}
for instance.
Then you could just write
for(i=0;i<data.src.length;i++) {
var elem = data.src[i];
var checked = "";
if (elem.checked)
checked = "checked";
middle = middle +
"<li><img src=" +
"http://localhost/project/user/" +
"<?php echo $this->session->userdata('username');?>" +
"/pages/" +
"<?php echo $this->uri->segment(3);?>" +
"/images/gallery/" +
elem.src +
" />" +
"<br /><input type='checkbox' value=" +
elem.src +
" " +
checked +
"/></li>";
}
}
The only thing different between the two strings you make is the attribute checked (which should really be checked="checked" if you want to follow standards), so I'd prefer setting a variable checked to either an empty string or "checked" depending on whether the checkbox is checked or not.
Related
my problem is that i can not set an id for the input or a value. Because the input is inside JavaScript how can i call it ? and i want the values of the input change each time i enter a certain number.
i would like to see the values of the first column change, so if the user enter number four that means there are 4 lights.
function createTable() {
var a;
a = document.getElementById('number1').value;
if (a == 2 || a == 1 || a < 0) {
alert("Please enter a positive number greater than 2");
} else {
var rows = "<th>Light </th><th>Rating(W)</th><th>Span-from prev.light-(m)</th><th>Voltage Drop (v)</th><th>Voltage Drop( % ) </th>";
for (var i = 0; i < a; i++) {
rows += "<tr><td><input type='number' id=frt name='" + "Light".concat(i + 1) + "' id=li></td><td><input type='number' value=250 name='" + "Rating(W)".concat(i + 1) + "'><td><input type='number' value=40 name='" + "Span-from prev.light-(m)".concat(i + 1) + "'></td><td><input type='number' name='" + "Voltage Drop (v)".concat(i + 1) + "'></td><td id='amt'><input type='number' id='sum' onkeyup='myfunction(this.value);' name = '" + "Voltage Drop(%)".concat(i + 1) + "'> </td></tr >";
}
}
document.getElementById("table").innerHTML = rows;
}
<!DOCTYPE html>
<html>
<body>
<table cellpadding="1" cellspacing="1" border="1" id="table" style="font: 20px solid bold;font-weight: bold; background-color:#707B7C;color:black;"></table>
<input type="number" name="Numbers of Lights" id="number1" oninput="createTable()" value="3" style="width:40px; position: absolute;
top:300px; left:800px;">
</div>
</body>
</html>
If change the line to this
rows += "<tr><td><input value='" + (i + 1) + "' type='number' id=frt name='" + "Light".concat(i + 1) + "' id=li></td><td><input type='number' value=250 name='" + "Rating(W)".concat(i + 1) + "'><td><input type='number' value=40 name='" + "Span-from prev.light-(m)".concat(i + 1) + "'></td><td><input type='number' name='" + "Voltage Drop (v)".concat(i + 1) + "'></td><td id='amt'><input type='number' id='sum' onkeyup='myfunction(this.value);' name = '" + "Voltage Drop(%)".concat(i + 1) + "'> </td></tr >";
you can get the iteration as a value in the first column.
this is my code that i used to genrate html table using javascipt
now my problem is i want to put "--" insted of "null" value,so how can i
check the value that null or not before code should displayed.
var res1 = sessionStorage.getItem('user_list');
var res = JSON.parse(res1);
var createList = '';
for (var i = 0; i < res.length; i++) {
createList += " <div class='table-data-banner'> <div class='div-block switch'>\
<div data-ix='switch' class='switch-click-area'>\
<div class='switch-length'><div class='switch-bulb'>\
</div>\
</div>\
</div>\
</div>\
<a href='#' class='table-data-link' style='max-width:100%' >\
<input type='hidden' class='user_id' value=" + res[i].user_id + " \> \
<div class='text-block-2 data first'>" + res[i].first_name + "</div><div class='text-block-2 first data'>" + res[i].last_name + "</div>\
<div class='text-block-2 email no-mobile data'>" + res[i].email_id + "</div>\
<div class='text-block-2 phone no-mobile data'>" + res[i].cell_phone + "</div>\
<div class='text-block-2 access no-mobile data'>" + res[i].access_level + "</div>\
<div class='text-block-2 access no-mobile data'>\
<input type='button' class='w-button delete-data' value='delete' user_id=" + res[i].user_id + " postion=" + i + "> \
<input type='button' class='w-button edit-data' value='edit' user_id=" + res[i].user_id + " postion=" + i + "></div>\
\
</a> </div>"
}
You can use the falsy nature of JS to coalesce null or undefined values to '--', like this:
'<input type="hidden" class="user_id" value="' + (res[i].user_id || '--') + '" \>'
Also note that I'd suggest you use templating logic to build your HTML, as having that much UI code within the JS is not ideal.
I'd program it more functionally using the map function and template literals for better readibility
var res1 = sessionStorage.getItem('user_list');
const list = JSON.parse(res1)
.map(item => {
return `<div class='table-data-banner'>
<div class='div-block switch'>
... (template markup here)
<input type='hidden' class='user_id' value="${(item.user_id || '--')}"\>
..(template markup here)
</div>`
})
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>
I was unable to retrieve the dynamic generated textfields and radio buttons that I created using javascript but was able to retrieve the those that I manually added into the form using html.
Previously, I use styling to hide and show all my textfields instead of dynamically created textfields, so I have no problem getting all the textfields and can safely assume my PHP processing doesn't have any problem.
My HTML/Interface coding
<?php
for ($x = 1; $x <= 5; $x++)
{
$inputAreaID = "inputArea".$x;// Creating all dynamic options and etc in this div using javascript
$typeID = "type".$x; //for select type id
$opt2ID = "ans".$x;
$optID = "opt".$x;
$comID = "com".$x;
$qnName = "qn".$x // for qn textfield name?>
<table>
<tr>
<td>Question <?php echo $x ?></td>
<td><input type="text" name='<?php echo $qnName ?>' required></td>
</tr>
<tr>
<td>Question Type</td>
<td>
<select id="<?php echo $typeID ?>" name="<?php echo $typeID ?>" onclick="showQuestionSelect('<?php echo $x ?>', '<?php echo $typeID ?>', '<?php echo $inputAreaID ?>')">
<option value="">Please select one option </option>
<option value="Yes,No">Yes/No </option>
<option value="True,False">True/False</option>
<option value="3">A. B. C. D.</option>
</select>
</td>
</tr>
</table>
<div id='<?php echo $inputAreaID ?>' style="margin-bottom: 1px;margin-top:1px;"></div>
JavaScript coding
function showQuestionSelect(questionNo, typeID, inputArea)
{
var s = String(typeID);
var i = String(inputArea);
var e = document.getElementById(s);
var selectedOpt = e.options[e.selectedIndex].value;
ansID = questionNo + "_ans";
comID = questionNo + "_com";
optA = questionNo + "_optA";
optB = questionNo + "_optB";
optC = questionNo + "_optC";
optD = questionNo + "_optD";
var msg = "";
if (selectedOpt == "True,False")
{
msg ="<div style='margin-bottom: 10px;margin-top:10px;'><input type='radio' name='"+ ansID + "' value='True'> Submit True as Answer<input type='radio' name='" +ansID +"' value='False'> Submit False as Answer</div>";
msg +="<div style='margin-bottom: 10px;margin-top:10px;'>Reason for the answer: <input type='text' name='" + comID + "' value='' /></div>"
}
else if (selectedOpt == 3)
{
msg = "<div style='margin-bottom: 10px;margin-top:10px;'>";
msg += "Option A: <input type='text' name='" + optA + "' value='' /> <input type='radio' name='" + ansID + "' value='" + optA + "'> Submit as Answer <br><br>";
msg += "Option B: <input type='text' name='" + optB + "' value='' /> <input type='radio' name='" + ansID + "' value='" + optB + "'> Submit as Answer <br><br>";
msg += "Option C: <input type='text' name='" + optC + "' value='' /> <input type='radio' name='" + ansID + "' value='" + optC + "'> Submit as Answer <br><br>";
msg += "Option D: <input type='text' name='" + optD + "' value='' /> <input type='radio' name='" + ansID + "' value='" + optD + "'> Submit as Answer </div>";
msg +="<div style='margin-bottom: 10px;'>Reason for the answer: <input type='text' name='" + comID + "' value='' /></div>";
}
document.getElementById(i).innerHTML = msg;
}
PHP Processing Coding
for ($x = 1; $x <= 5; $x++)
{
$qn = $_POST["qn".$x]; // for qn textfield name
$type = $_POST["type".$x]; //for select type id
$ans = $_POST[$x."_ans"]; //for answer div id
$reason = $_POST[$x."_com"]; //for answer div id
$optionType = "";//to put into database
if ($type == "Yes,No")
{
$ans = "";
$reason = "";
}
if ($type == "3")
{
$optA = $_POST[$x."_optA"];
$optB = $_POST[$x."_optB"];
$optC = $_POST[$x."_optC"];
$optD = $_POST[$x."_optD"];
$optionType = $optA.",".$optB.",".$optC.",".$optD;
if ($ans == $x."_optA")
$ans = $optA;
else if ($ans == $x."_optB")
$ans = $optB;
else if ($ans == $x."_optC")
$ans = $optC;
else
$ans = $optD;
}
else
$optionType = $type;
Can anyone assist?
First of all you should to check server has got the values of those generated textfields. Try to display all members of $_POST[].
I guess that you are stuck in the names of the parameters
In my web application I have created a form that will allow users to insert stories to an online newspaper.
In order to do this I have created a hidden table which I clone to allow users to create new stories which I later catch on the submit event of my form.
Here I am facing a problem regarding the contents of the story's text.
For example, if the story contains double quotes on it, it will break my string when creating a new element on the submit event, like so;
$("form").submit(function () {
var myForm = $(this);
// begin cover stories process
var stories = $("#newsBlock").find("table");
if (stories != undefined) {
stories.each(function (index) {
var cNew = new CoverNew($(this).find('[name="news_id"]').attr("value"), $(this).find('[name="editionDate"]').attr("value"), $(this).find('[name="newsTitle"]').attr("value"), $(this).find('[name="newsLink"]').attr("value"), $(this).find('[name="newsAuthor"]').attr("value"), $(this).find('[name="newsSource"]').attr("value"), $(this).find('[name="newsDescription"]').attr("value"), $(this).find('[name="newsImageListing"]').attr("value"), $(this).find('[name="newsImageStory"]').attr("value"), $(this).find('[name="newsImageStory_Author"]').attr("value"), $(this).find('[name="newsImageStory_Description"]').attr("value"), $(this).find('[name="newsVideo"]').attr("value"), $(this).find('[name="newsText"]').val(), $(this).find('[name="newsOrder"]').attr("value"));
var ids = '<input name="Cover[' + index + '].id" id="Cover[' + index + '].id" type="text" value ="' + cNew.id + '" style="display:none;" />';
var title = '<input name="Cover[' + index + '].title" id="Cover[' + index + '].title" type="text" value="' + cNew.title + '" style="display:none;" />';
var editionDate = '<input name="Cover[' + index + '].edition_date" id="Cover[' + index + '].edition_date" type="text" value="' + cNew.editionDate + '" style="display:none;" />';
var link = '<input name="Cover[' + index + '].link" id="Cover[' + index + '].link" type="text" value="' + cNew.link + '" style="display:none;" />';
var author = '<input name="Cover[' + index + '].author" id="Cover[' + index + '].author" type="text" value="' + cNew.author + '" style="display:none;" />';
var source = '<input name="Cover[' + index + '].source" id="Cover[' + index + '].source" type="text" value="' + cNew.source + '" style="display:none;" />';
var description = '<input name="Cover[' + index + '].description" id="Cover[' + index + '].description" type="text" value="' + cNew.description + '" style="display:none;" />';
var menuPicture = '<input name="Cover[' + index + '].photo_in_list" id="Cover[' + index + '].photo_in_list" type="text" value="' + cNew.menu_picture + '" style="display:none;" />';
var story_picture = '<input name="Cover[' + index + '].photo_in_news" id="Cover[' + index + '].photo_in_news" type="text" value="' + cNew.story_picture + '" style="display:none;" />';
var story_picture_description = '<input name="Cover[' + index + '].photo_in_news_desc" id="Cover[' + index + '].photo_in_news_desc" type="text" value="' + cNew.story_picture_description + '" style="display:none;" />';
var story_picture_author = '<input name="Cover[' + index + '].photo_in_news_author" id="Cover[' + index + '].photo_in_news_author" type="text" value="' + cNew.story_picture_author + '" style="display:none;" />';
var video = '<input name="Cover[' + index + '].video" id="Cover[' + index + '].video" type="text" value="' + cNew.video + '" style="display:none;" />';
var content = '<input name="Cover[' + index + '].content" id="Cover[' + index + '].content" type="text" value="' + cNew.content + '" style="display:none;" />';
var order = '<input name="Cover[' + index + '].order" id="Cover[' + index + '].order" type="text" value="' + cNew.order + '" style="display:none;" />';
myForm.append(ids);
myForm.append(title);
myForm.append(editionDate);
myForm.append(link);
myForm.append(author);
myForm.append(source);
myForm.append(description);
myForm.append(menuPicture);
myForm.append(story_picture);
myForm.append(story_picture_description);
myForm.append(story_picture_author);
myForm.append(video);
myForm.append(content);
myForm.append(order);
index++;
});
}
});
In the above process, I collect the tables cloned by the user which contain stories.
Inside the variable content I place the text of the story.
But by the way I am concatenating it, if the text contains a double quote, the string will be broken at that point.
Is there anything I could do with javascript (even pure javascript) to fix this problem?
Yes - do var content = '<input name="Cover[' + index + '].content" id="Cover[' + index + '].content" type="text" value="' + cNew.content.replace(/"/g, """) + '" style="display:none;" />';
Use string Replace, for example:
cNew.story_picture_description.replace(/"/g, """);
Another and cleaner way would be to copy the whole table with cloneNode und delete the values in the new table.
use the javascript function to replace the " with "
var content = content.replace(/"/g, """);
You should definetely make use of some template engine. Even simple jquery template or micro-template will work fine.
// Template engine, yea that easy
function templ(str, data) {
for (var p in data)
str = str.replace(new RegExp('{'+p+'}','g'), data[p]);
return str;
}
var cNew = new CoverNew(...);
cNew.index = index;
var story = templ($('#story-content').html(), cNew);
myForm.append(story);
And also place all your html into container:
<script type="text/template" id="story-content">
<input name="Cover[{index}].id" id="Cover[{index}].id" type="text" value ="{id}" style="display:none;" />
<input name="Cover[{index}].title" id="Cover[{index}].title" type="text" value="{title}" style="display:none;" />
...
</script>
Of course it's a little bit more complecated. But your code becomes more maintainable and clean.