I have a fixed set of input fields on page load. I have checkboxes with values displayed and when someone checks the checkbox the values are added to the input field. If all the input fields are filled, a new one is created. My problem is that, the checkbox values are inserted correctly in existing input fields and if the value exceeds,a new input field is created but values are not inserted immediately when the input field is created.Only on the next click is the values inserted in the newly created input field. Here's the code
<script>
function fillin(entire,name,id,key) {
if (entire.checked == true) {
var split_info = new Array();
split_info = name.split(":");
var div = $("#Inputfields"+id);
var till = (div.children("input").length)/4;
var current_count = 0;
for (var j=0;j<till;j++) {
if (document.getElementById("insertname_"+j+"_"+id).value == "" && document.getElementById("insertnumber_"+j+"_"+id).value == "") {
document.getElementById("insertname_"+j+"_"+id).value = split_info[0];
document.getElementById("insertnumber_"+j+"_"+id).value = split_info[1];
break;
} else
current_count = current_count+1;
if (current_count == till) {
var x= addnew(id);
x =x+1;
$("#Inputfields"+id).find("#insertname_"+x+"_"+id).value = split_info[0];
alert($("#Inputfields"+id).find("#insertname_"+x+"_"+id).value);
document.getElementById("insertname_"+x+"_"+id).text = split_info[0];
//alert(document.getElementById("insertname_"+x+"_"+id).value);
//document.getElementById("insertnumber_"+x+"_"+id).value = split_info[1];
}
}
} else {
}
}
</script>
<script>
function addnew(n) {
//var id = $(this).attr("id");
var div = $("#Inputfields"+n);
var howManyInputs = (div.children("input").length)/4;
alert(howManyInputs);
var val = $("div").data("addedCount");
var a = '<input type="search" id="insertinstitute_'+(howManyInputs)+'_'+n+'" placeholder="Institute" class="span3">';
var b = '<input type="search" id="insertname_'+(howManyInputs)+'_'+n+'" placeholder="name" class="span3">';
var c = '<input type="search" name="" id="insertnumber_'+(howManyInputs)+'_'+n+'" placeholder="number" class="span3">';
var d = '<input type="search" name="" id="insertarea_'+(howManyInputs)+'_'+n+'" placeholder="area" class="span3">';
var fin = a+b+d+c;
$(fin).appendTo(div);
div.data("addedCount", div.data("addedCount") + 1);
return howManyInputs;
}
</script>
UPDATED: Thank you all. I was able to find the bug. The culprit was x =x+1;. It should have been x
The problem is probably here:
document.getElementById("insertname_"+x+"_"+id).text
There's no text property in elements. There's textContent (not in IE8-), innerText (in IE) and innerHTML. There's the text method in jQuery, though. So you can either do:
document.getElementById("insertname_"+x+"_"+id).innerHTML = ...
or
$("#insertname_"+x+"_"+id).text(...);
Also, these lines:
$("#Inputfields"+id).find("#insertname_"+x+"_"+id).value = split_info[0];
alert($("#Inputfields"+id).find("#insertname_"+x+"_"+id).value);
.value there should be replaced with .val(), because those are jQuery objects.
I have reworked a lot of your code for a lot of reasons. Compare the two.
function fillin(entire, name, id, key) {
if (entire.checked) {
var split_info = [];
split_info = name.split(":");
var div = $("#Inputfields" + id);
var till = (div.children("input").length) / 4;
var current_count = 0;
var j = 0;
for (j = 0; j < till; j++) {
var myj = j + "_" + id;
if ($("#insertname_" + myj).val() === "" && $("#insertnumber_" + myj).val() === "") {
$("#insertname_" + myj).val(split_info[0]);
$("#insertnumber_" + myj).val(split_info[1]);
break;
} else {
current_count = current_count + 1;
}
if (current_count === till) {
var x = addnew(id) + 1;
div.find("#insertname_" + x + "_" + id).val(split_info[0]);
alert(div.find("#insertname_" + x + "_" + id).val());
$("#insertname_" + x + "_" + id).val(split_info[0]);
}
}
}
}
function addnew(n) {
var div = $("#Inputfields" + n);
var howManyInputs = (div.children("input").length) / 4;
alert(howManyInputs);
var myi = (howManyInputs) + '_' + n + '"';
var val = div.data("addedCount");
var a = '<input type="search" id="insertinstitute_' + myi + ' placeholder="Institute" class="span3">';
var b = '<input type="search" id="insertname_' + myi + ' placeholder="name" class="span3">';
var c = '<input type="search" name="" id="insertnumber_' + myi + ' placeholder="number" class="span3">';
var d = '<input type="search" name="" id="insertarea_' + myi + ' placeholder="area" class="span3">';
var fin = a + b + d + c;
$(fin).appendTo(div);
div.data("addedCount", val + 1);
return howManyInputs;
}
Related
I got this code from here : Display Spreadsheet Data to HTML Table
thanks to the great work of Cooper.
function htmlSpreadsheet(ssO) {
var br='<br />';
var s='';
var hdrRows=1;
var ss=SpreadsheetApp.openById(ssO.id);
var sht=ss.getSheetByName(ssO.name);
var rng=sht.getDataRange();
var rngA=rng.getValues();
s+='<table>';
for(var i=0;i<rngA.length;i++)
{
s+='<tr>';
for(var j=0;j<rngA[i].length;j++)
{
if(i<hdrRows)
{
s+='<th id="cell' + i + j + '">' + '<input id="txt' + i + j + '" type="text" value="' + rngA[i][j] + '" size="20" onChange="updateSS(' + i + ',' + j + ');" />' + '</th>';
}
else
{
s+='<td id="cell' + i + j + '">' + '<input id="txt' + i + j + '" type="text" value="' + rngA[i][j] + '" size="20" onChange="updateSS(' + i + ',' + j + ');" />' + '</th>';
}
}
s+='</tr>';
}
s+='</table>';
s+='</body></html>';
var namehl=Utilities.formatString('<h1>%s</h1>', ss.getName());
var shnamehl=Utilities.formatString('<h2>%s</h2>', sht.getName());
var opO={hl:s,name:namehl,shname:shnamehl};
return opO;
}
function updateSpreadsheet(updObj) {
var i=updObj.rowIndex;
var j=updObj.colIndex;
var value=updObj.value;
var ss=SpreadsheetApp.openById(updObj.id);
var sht=ss.getSheetByName(updObj.name);
var rng=sht.getDataRange();
var rngA=rng.getValues();
rngA[i][j]=value;
rng.setValues(rngA);
var data = {'message':'Cell[' + Number(i + 1) + '][' + Number(j + 1) + '] Has been updated', 'ridx': i, 'cidx': j};
return data;
}
function doGet() {
var userInterface=HtmlService.createHtmlOutputFromFile('htmlss').setWidth(1000).setHeight(450);
return userInterface.setXFrameOptionsMode(HtmlService.XFrameOptionsMode.ALLOWALL);
}
function getAllSpreadSheets() {
var files=DriveApp.getFilesByType(MimeType.GOOGLE_SHEETS);
var s = '';
var vA=[['Select Spreadsheet',0]];
while(files.hasNext())
{
var file = files.next();
var fileName=file.getName();
var fileId=file.getId();
vA.push([fileName,fileId]);
}
//return vA;
return {array:vA,type:'sel1'};
}
//working on this function right now 2017/11/08
function getAllSheets(ssO) {
var ss=SpreadsheetApp.openById(ssO.id);
var allSheets=ss.getSheets();
var vA=[['Select Sheet']];
for(var i=0;i<allSheets.length;i++)
{
var name=allSheets[i].getName();
vA.push([name]);
}
return {array:vA,type:'sel2'};
}
What I am trying to do is on a Single sheet. That is I don't want to browse all sheets and select among them~
I have tried modifying this code
function getAllSpreadSheets() {
var files=DriveApp.getFilesByType(MimeType.GOOGLE_SHEETS);
var s = '';
// var vA=[['Select Spreadsheet',0]];
while(files.hasNext())
{
// var file = files.next();
var fileName=file.getName();
var fileId=file.getId();
vA.push([fileName,fileId]);
}
//return vA;
return {array:vA,type:'sel1'};
}
I have used sheet Id instead of file.getId(), But It just don't work.
Please help me.
Change:
var files = DriveApp.getFilesByType(MimeType.GOOGLE_SHEETS)
To getFileById():
var file = DriveApp.getFileById("sheet Id");
Then remove the loop:
function getSingleSpreadSheet() {
var file = DriveApp.getFileById("sheet Id")
var fileName = file.getName()
var fileId = file.getId()
var vA = []
vA.push([fileName, fileId])
return {
array: vA,
type:'sel1'
}
}
I'm looping through DOM elements when a certain button is clicked. I've attached the class finish-proc to the button, so when clicked will activate this function:
<script>
$(document).on('click', '.finish-proc', function () {
var communities = [];
var $this, $thisDay, input, inputDay, text, textDay, obj, objDay;
$('.panel-default').each(function (i) {
var maxPeople = '.' + $(this).attr('data-community') + '-max-people';
var dayInfoRow = '.' + $(this).attr('data-community') + '-day-info';
obj = {};
obj["maxPeople"] = $(maxPeople).val();
var daysArrayInLoop = [];
$(dayInfoRow).each(function (j) {
var objDay = {};
var dayString = '.' + $(this).attr('data-community') + '-day-' + (j + 1);
var dayStringStart = '.' + $(this).attr('data-community') + '-day-' + (j + 1) + '-start';
var dayStringEnd = '.' + $(this).attr('data-community') + '-day-' + (j + 1) + '-end';
objDay["dayString"] = $(dayString).val();
objDay["dayStringStart"] = $(dayStringStart).val();
objDay["dayStringEnd"] = $(dayStringEnd).val();
daysArrayInLoop.push(objDay);
}
obj["dayArray"] = daysArrayInLoop;
communities.push(obj);
}
}
</script>
This code is breaking on the line:
daysArrayInLoop.push(objDay);
With the error:
daysArrayInLoop.push is not a function
Can anyone tell me why this is?
EDIT - I've tried to alter the var daysArrayInLoop = []; to var daysArrayInLoop = {};, still getting the same error
Try This code define array after push in object
var daysArrayInLoop = new Array();
daysArrayInLoop.push(obj);
I was trying to make something where you can type a string, and the js only shows the objects containing this string. For example, I type Address1 and it searches the address value of each one then shows it (here: it would be Name1). Here is my code https://jsfiddle.net/76e40vqg/11/
HTML
<input>
<div id="output"></div>
JS
var data = [{"image":"http://www.w3schools.com/css/img_fjords.jpg","name":"Name1","address":"Address1","rate":"4.4"},
{"image":"http://shushi168.com/data/out/114/38247214-image.png","name":"Name2","address":"Address2","rate":"3.3"},
{"image":"http://www.menucool.com/slider/jsImgSlider/images/image-slider-2.jpg","name":"Name3","address":"Address3","rate":"3.3"}
];
var restoName = [], restoAddress = [], restoRate = [], restoImage= [];
for(i = 0; i < data.length; i++){
restoName.push(data[i].name);
restoAddress.push(data[i].address);
restoRate.push(data[i].rate);
restoImage.push(data[i].image);
}
for(i = 0; i < restoName.length; i++){
document.getElementById('output').innerHTML += "Image : <a href='" + restoImage[i] + "'><div class='thumb' style='background-image:" + 'url("' + restoImage[i] + '");' + "'></div></a><br>" + "Name : " + restoName[i] + "<br>" + "Address : " + restoAddress[i] + "<br>" + "Rate : " + restoRate[i] + "<br>" + i + "<br><hr>";
}
I really tried many things but nothing is working, this is why I am asking here...
Don't store the details as separate arrays. Instead, use a structure similar to the data object returned.
for(i = 0; i < data.length; i++){
if (data[i].address.indexOf(searchedAddress) !== -1) { // Get searchedAddress from user
document.getElementById("output").innerHTML += data[i].name;
}
}
Edits on your JSFiddle: https://jsfiddle.net/76e40vqg/17/
Cheers!
Here is a working solution :
var data = [{"image":"http://www.w3schools.com/css/img_fjords.jpg","name":"Name1","address":"Address1","rate":"4.4"},
{"image":"http://shushi168.com/data/out/114/38247214-image.png","name":"Name2","address":"Address2","rate":"3.3"},
{"image":"http://www.menucool.com/slider/jsImgSlider/images/image-slider-2.jpg","name":"Name3","address":"Address3","rate":"3.3"}
];
document.getElementById('search').onkeyup = search;
var output = document.getElementById('output');
function search(event) {
var value = event.target.value;
output.innerHTML = '';
data.forEach(function(item) {
var found = false;
Object.keys(item).forEach(function(val) {
if(item[val].indexOf(value) > -1) found = true;
});
if(found) {
// ouput your data
var div = document.createElement('div');
div.innerHTML = item.name
output.appendChild(div);
}
});
return true;
}
<input type="search" id="search" />
<div id="output"></div>
I need to add checkbox dynamically by entering the label name.
Here I can add checkbox, but problem is if same label(case sensitive) is already present it should not allow user to add. Please help on this. Thanks in advance.
HTML
<input type="button" value="add" onClick="add()" />
<ul id="container" style="list-style-type:none;">
</ul>
Script
var i=0;
function add() {
var label = prompt("Please enter label name", "");
if (label != null || label != "") {
i++;
var title = label;
var node = document.createElement('li');
node.innerHTML = '<input type="checkbox" id="check' + i + '" name="check' + i + '"><label for="check' + i + '">'+ title +'</label>';
document.getElementById('container').appendChild(node);
}
}
Jsfiddle
Store the labels in an array and check whether the new label is present in that array or not, then proceed inserting the new element.
var i = 0;
var labels = [];
function add() {
var label = prompt("Please enter label name", "");
if (label != null || label != "") {
if (labels.indexOf(label) == -1) {
labels.push(label); i++;
var node = document.createElement('li');
node.innerHTML = '<input type="checkbox" id="check' + i + '" name="check' + i + '"><label for="check' + i + '">' + labels[labels.length - 1] + '</label>';
document.getElementById('container').appendChild(node);
} else {
alert("labels should be unique!")
}
}
}
DEMO
You can try something like this:
var i=0;
function add() {
var label = prompt("Please enter label name", "");
var exists = document.evaluate('//label[text()="' + label + '"]', document, null, XPathResult.ORDERED_NODE_SNAPSHOT_TYPE, exists).snapshotItem(0);
if (exists) {
return;
}
if (label != null || label != "") {
i++;
var title = label;
var node = document.createElement('li');
node.innerHTML = '<input type="checkbox" id="check' + i + '" name="check' + i + '"><label for="check' + i + '">'+ title +'</label>';
document.getElementById('container').appendChild(node);
}
}
You can use data attribute and querySelector to check for the existance.
var i=0;
function add() {
var label = prompt("Please enter label name", "");
var labels = ;
if ((label != null || label != "") && !document.querySelector('label[data-value="'+label+'"]')) {
i++;
var title = label;
var node = document.createElement('li');
node.innerHTML = '<input type="checkbox" id="check' + i + '" name="check' + i + '"><label for="check' + i + '" data-value="'+title+'">'+ title +'</label>';
document.getElementById('container').appendChild(node);
}
}
Most of the action is in the function next. The other functions are provided for context. The global variable tally increments as it should when the right answer is selected. However the variable nr is not incremented and I can't figure out way it is not.
You can see that I commented out that the next function returned an object with tally and nr and assigned those values in the event listener. When I did it that way, it worked. But it should work the other way as well, right.
var nr = 0;
var tally = 0;
function onLoadEvent(nr) {
//alert('onload');
var quiz = document.getElementById('quiz');
var question = allQuestions[nr];
var next = quiz.lastElementChild;
var qHeader = "<h2>" + question.question + "</h2>";
var q = "";
for(var i=0;i<question.choices.length;i++){
q = q + '<p><label for="a' + i + '">' +
'<input type="radio" id="a' + i + '" name="q" value="' +
i + '">' + question.choices[i] + '</label></p>';
}
quiz.innerHTML = qHeader + q + next.outerHTML;
//next = document.getElementById('next');
}
function getChecked(){
var radios = document.getElementsByName('q');
var radio;
for(var i=0;i<radios.length;i++){
if(radios[i].checked){
radio = radios[i];
break;
}
}
return radio;
}
function next(nr){
if (getChecked() !== undefined) {
var answer = getChecked();
if(answer.value == allQuestions[nr].correctAnswer){
tally = tally + 1;
}
nr = nr + 1;
if (nr>=allQuestions.length){
alert("You got " + tally + " points!");
} else {
onLoadEvent(nr);
}
} else {
alert('You need to check a radio button');
}
//return {nr: nr, tally: tally};
}
var form = document.getElementById('quiz');
form.addEventListener('click', function(event){
if(event.target.id === 'next'){
next(nr);
//nr = obj.nr;
//tally = obj.tally;
} else if(event.target.id === 'prev'){}
}, false);
window.addEventListener('load', function(event){onLoadEvent(nr);}, false);
You are accepting parameters with same name nr which is hiding global scope nr.
Solution to your problem is remove nr as parameter. So use function onLoadEvent() instead of function onLoadEvent(nr)