Appending div to the form disappears automatically - javascript

I have a form, I want to append a entire div every time a button is clicked. The code works but after few seconds the appended div automatically disappears. don't get any errors.
I am using jQuery 2.1.3. Here is my code in JS Fiddle:
https://jsfiddle.net/sathyabaman/jgdLtu4d/
My code:
<form method="POST" id="form_property" enctype="multipart/form-data">
<div class="row">
<div class="span4" id="image">
<h3><strong>4.</strong> <span>Add Images to your Property (Maximum : 6 Images)</span></h3>
<div id="clone_image" class="fileupload fileupload-new ">
<label class="control-label">Image file</label>
<div class="input-append">
<div class="uneditable-input"> <i class="icon-file fileupload-exists"></i>
<span class="fileupload-preview"></span>
</div> <span class="btn btn-file">
<span class="fileupload-new">Select file</span>
<span class="fileupload-exists">Change</span>
<input type="file" name="files1" accept="image/*" />
</span>
</div>
</div>
</div>
<!-- /.span4 -->
</div>
<!-- /.row -->
<br/> <a id="another_image" class="btn btn-primary btn-small list-your-property" href="">Add Another Image</a>
<br/>
<br/>
<input type="submit" name="submit" value=" Save images " class="btn btn-primary btn-large" style="float: left; width: 370px; height: 50px; margin-top: 10px">
</form>
jquery
$(document).ready(function(){
var count = 2;
$('#another_image').click (function(){
var clonedEl = $('#clone_image').first().clone()
clonedEl.find(':file').attr('name','files'+count)
if(count < 7){
if(count == 6){ $('#another_image').hide();}
$(clonedEl).appendTo("#image");
count++;
}
});
});
Thank you..

You need to prevent the default action of the anchor click, which is to navigate to the target page.
Since you have specified an empty href it reloads the same page that is why you can see the new element and then it appears to be disappearing.
$(document).ready(function () {
var count = 2;
$('#another_image').click(function (e) {
//e.preventDefault()
var clonedEl = $('#clone_image').first().clone()
clonedEl.find(':file').attr('name', 'files' + count)
if (count < 7) {
if (count == 6) {
$('#another_image').hide();
}
$(clonedEl).appendTo("#image");
count++;
}
});
});
Demo: Fiddle

Related

I can't get past the js div hiding problem

I want to hide the divi when I click the button and open it when I click it again. But I couldn't run the normally working code, what could be the reason?
The js code works when there is only one div, but it does not work due to this code I wrote, but I can't solve the problem.
Razor Page
#for (int i = 0; i < Model.quest.Count; i++)
{
<div class="row mt-12" >
<div class="col-md-1">
<input type="checkbox" id="questcb" asp-for="#Model.quest[i].check">
<span>#(i + 1) Soru</span>
</div>
<div class="col-md-9">
<textarea class="form-control" asp-for=#Model.quest[i].Question rows="3" id="question" hidden></textarea>
<label>#Model.quest[i].Question</label>
</div>
</div>
<div class="row mt-12">
<div class="col-md-1" hidden>
<button class="btn btn-outline-secondary" type="button" id="A" onclick="clickFunc(this.id)">A</button>
</div>
<div class="col-md-1" >
A)
</div>
<div class="col-md-11" hidden="hidden">
<input type="text" asp-for=#Model.quest[i].Answer1 class="form-control" placeholder="" id="answer"
aria-label="Example text with button addon" aria-describedby="button-addon1">
</div>
<div class="col-md-11" id="Amod_#i" style="display:inline-block">
#Model.quest[i].Answer1
</div>
<div class="col-md-2">
<button class="btn btn-primary" type="button" id="mod_#i" onclick="question(this.id)">Cevapları Görüntüle</button>
</div>
</div>
}
js code
let question = button => {
let element = document.getElementById(`A${button}`);
let buttonDOM = document.getElementById(`${button}`)
let hidden = element.getAttribute("hidden");
if (hidden) {
element.removeAttribute("hidden");
buttonDOM.innerText = "Cevapları Gizle";
}
else {
element.setAttribute("hidden", "hidden");
buttonDOM.innerText = "Cevapları Görüntüle";
}
}
</script>
If the id of div is unique in your code,your js should work.If it still doesn't work,you can try to find the div with the position of the button:
let question = button => {
let element = $("#" + button).parent().siblings(".col-md-11")[1];
let buttonDOM = document.getElementById(`${button}`);
if (element.hidden) {
element.removeAttribute("hidden");
buttonDOM.innerText = "Cevapları Gizle";
}
else {
element.setAttribute("hidden", "hidden");
buttonDOM.innerText = "Cevapları Görüntüle";
}
}
result:

Problem showing questions in a quiz made in javascript

I have a form with 5 questions, in which they are displayed one at a time to the user, as in a quiz, that is, the first question appears on the screen, the user answers and goes to the second, and so on.
However, I have a problem with questions 3 and 4, when I don't type anything and press ENTER, question 2 is also appearing on the screen, like the image below:
[![error in questions 3 and 4][1]][1]
[1]: https://i.stack.imgur.com/63pQC.png
I can't show two questions at the same time, just one at a time, and I don't know where I'm going wrong.
Here's the code inside the form tag:
<form class="questions_box formulario" action="enviar-landing-page-v3.php" method="post">
<div id="question-1">
<h3>The question is: ... ?</h3>
<input type="radio" name="objetivo" id="question-1-answer-a" value=1 required oninput="checkObjective()"> Answer 1.<br>
<input type="radio" name="objetivo" id="question-1-answer-b" value=2 oninput="checkObjective()"> Answer 2.<br>
<input type="radio" name="objetivo" id="question-1-answer-c" value=3 oninput="checkObjective()"> Answer 3.<br>
<div class="text-end mt-3">
<input type="submit" id="submit1" class="btn btn-primary btn-lg" value="Enviar Resposta" style="display: none;" />
</div>
<script type="text/javascript">
function checkObjective() {
if (document.getElementsByName('objetivo').value == '') {
document.getElementById('submit1').style.display = 'none';
} else {
document.getElementById('submit1').style.display = 'block';
}
}
</script>
</div>
<div id="question-2">
<h3>Quantos anos tem seu filho(a)?</h3>
<div class="input-formulario">
<i class="far fa-calendar-alt"></i>
<input required type="text" name="idade_aluno_lp" id="idade_aluno_lp" placeholder="Digite a idade do aluno" oninput="checkAge()" maxlength="2" />
</div>
<div class="text-center mt-3">
<input type="submit" id="submit2" class="btn btn-primary btn-lg" value="Enviar Resposta" style="display: none;" />
</div>
<div class="text-end mt-3">
<input type="submit" id="previous2" class="btn btn-primary btn-lg" value="Pergunta Anterior" style="display: block;" />
</div>
<script type="text/javascript">
function checkAge() {
var countAge = document.getElementById('idade_aluno_lp');
countAge.value = countAge.value.replace(/\D/, ''); // Remove caracteres que não sejam números
if (countAge.value.length == 0) { // 0 caracteres digitados
document.getElementById('submit2').style.display = 'none';
} else {
document.getElementById('submit2').style.display = 'block';
}
}
</script>
</div>
<div id="question-3">
<h3>Qual seu nome?</h3>
<div class="input-formulario">
<i class="far fa-user"></i>
<input required type="text" name="nome_lp" id="nome_lp" placeholder="Digite seu nome" oninput="checkName()">
<span id="error-name"></span>
</div>
<div class="text-center mt-3">
<input type="submit" id="submit3" class="btn btn-primary btn-lg" value="Enviar Resposta" style="display: none;" />
</div>
<div class="text-center mt-3">
<input type="submit" id="previous3" class="btn btn-primary btn-lg" value="Pergunta Anterior" style="display: block;" />
</div>
<script type="text/javascript">
function checkName() {
var countName = document.getElementById('nome_lp');
var errorName = document.getElementById('error-name')
countName.value = countName.value.replace(/[0-9]/g, ''); // Remove numbers
if (countName.value.length < 3) { // 0 chars entered
errorName.innerHTML = "O nome precisa ter ao menos 3 caracteres."
document.getElementById('submit3').style.display = 'none';
} else {
errorName.innerHTML = "";
document.getElementById('submit3').style.display = 'block';
}
}
</script>
</div>
<div id="question-4">
<h3>Qual seu email?</h3>
<div class="input-formulario">
<i class="fas fa-at"></i>
<input required type="email" name="email_lp" id="email_lp" placeholder="Digite seu email" oninput="checkEmail()">
<span id="error-email"></span>
</div>
<div class="text-center mt-3">
<input type="submit" id="submit4" class="btn btn-primary btn-lg" value="Enviar Resposta" style="display: none;" />
</div>
<div class="text-end mt-3">
<input type="submit" id="previous4" class="btn btn-primary btn-lg" value="Pergunta Anterior" style="display: block;" />
</div>
<script type="text/javascript">
function checkEmail() {
var email = document.getElementById('email_lp');
var errorEmail = document.getElementById('error-email');
if (!email.checkValidity()) {
errorEmail.innerHTML = "O email deverá seguir o padrão: meuemail#provedor.com";
document.getElementById('submit4').style.display = 'none';
} else {
errorEmail.innerHTML = "";
document.getElementById('submit4').style.display = 'block';
}
}
</script>
</div>
<div id="question-5">
<h3>Qual seu whatsapp?</h3>
<div class="input-formulario">
<i class="fab fa-whatsapp"></i>
<input required type="text" name="celular_lp" id="celular_lp" placeholder="Digite seu DDD + celular" maxlength="14" onkeypress="return mascaraCelular(event)" oninput="checkMobile()">
<span id="error-mobile"></span>
</div>
<div class="text-end mt-3">
<input type="submit" id="submit5" class="btn btn-primary btn-lg" value="Enviar Resposta" style="display: none;" />
</div>
<div class="text-end mt-3">
<input type="submit" id="previous5" class="btn btn-primary btn-lg" value="Pergunta Anterior" style="display: block;" />
</div>
</div>
<script type="text/javascript">
function checkMobile() {
var countMobile = document.getElementById('celular_lp');
var errorMobile = document.getElementById('error-mobile');
if (countMobile.value.length < 13) {
errorMobile.innerHTML = "Além do DDD, o número do celular precisa ter ao menos 8 dígitos";
document.getElementById('submit5').style.display = 'none';
} else {
errorMobile.innerHTML = "";
document.getElementById('submit5').style.display = 'block';
}
}
</script>
</form>
And the javascript responsible for show/hide the questions:
// Variables
var submit1 = document.getElementById('submit1');
var submit2 = document.getElementById('submit2');
var submit3 = document.getElementById('submit3');
var submit4 = document.getElementById('submit4');
var previous2 = document.getElementById('previous2');
var previous3 = document.getElementById('previous3');
var previous4 = document.getElementById('previous4');
var previous5 = document.getElementById('previous5');
// Next question button
submit1.addEventListener('click', function() {
nextQuestion(2);
growProgressBar('40%');
})
submit2.addEventListener('click', function() {
nextQuestion(3);
growProgressBar('60%');
})
submit3.addEventListener('click', function() {
nextQuestion(4);
growProgressBar('80%');
})
submit4.addEventListener('click', function() {
nextQuestion(5);
growProgressBar('100%');
})
// grow Progress Bar
function growProgressBar(percentage_width) {
var bar = document.getElementById('progress_bar');
bar.style.width = percentage_width;
}
// Shows next question, hides current
function nextQuestion(question_number) {
var current_question_number = question_number - 1; //question_number is the next question
var question_number = question_number.toString();
var current_question_number = current_question_number.toString();
document.getElementById('question-' + question_number).style.display = 'block';
document.getElementById('question-' + current_question_number).style.display = 'none';
}
// Previous question button
previous2.addEventListener('click', function() {
previousQuestion(1);
shrinkProgressBar('20%');
})
previous3.addEventListener('click', function() {
previousQuestion(2);
shrinkProgressBar('40%');
})
previous4.addEventListener('click', function() {
previousQuestion(3);
shrinkProgressBar('60%');
})
previous5.addEventListener('click', function() {
previousQuestion(4);
shrinkProgressBar('80%');
})
// Shrink Progress Bar
function shrinkProgressBar(percentage_width) {
var bar = document.getElementById('progress_bar');
bar.style.width = percentage_width;
}
// Shows previous question, hides current
function previousQuestion(question_number) {
var current_question_number = question_number + 1;
var question_number = question_number.toString();
var current_question_number = current_question_number.toString();
var el = document.getElementById('question-' + question_number);
console.log(question_number);
var el2 = document.getElementById('question-' + current_question_number);
el.style.display = 'block';
el2.style.display = 'none';
}
About Carsten Massmann answer:
The problem with the code was just to change the buttons type="submit" to type="button", and leave only the last button as type="submit", however, I really liked your code, I learned a lot, for example, I had never read about closest method. Could you explain to me how these two lines of code work (what they are for I understand):
current = (Q.length + current + inc) % Q.length; // cycle through questions...
Above I don't understand why you use the question length.
And on the next line, I don't understand why I use trim():
(el.value.trim() ? "block" : "none")
I also understand that you cycle between questions, but I need to demarcate the first and last question in the loop, and put something like if Q=0, don't show the "Previous question" button, and if Q=4, that the final button would execute method="POST" and action="next-page". I believe that the "submit" is not being executed because of the loop, but I don't understand why the loop takes precedence over the submit.
The following snippet is still missing your actual validation functions for individual fields but I hope it illustrates the point of how you can avoid unnecessary repetitions in your code and markup. I am using classes to address the various input elements and "delegated event attachment" to combine the click handling for different buttons. For simplicity I allow cycling through the questions. Feel free to change and adapt ...
function changeQ(inc){
current= (Q.length+current+inc)%Q.length; // cycle through questions ...
Q.forEach((q,i)=>q.style.display=(i==current?"":"none"))
}
function showHideOK(el){
let ok=!!el.value.trim();
el.closest(".input-formulario").querySelector("input.ok").style.display=
(ok?"block":"none");
ans[el.name]=ok;
}
document.querySelectorAll("div.input-formulario").forEach((div,i)=>{div.innerHTML+=`<div class="text-end mt-3"><input type="submit" class="btn btn-primary btn-lg back" value="Pergunta Anterior"/></div><div class="text-center mt-3"><input type="submit" class="btn btn-primary btn-lg ok" value="Próxima Pergunta"/></div>`;
div.addEventListener("input",ev=>{ let el=ev.target;
if (el.tagName!=="INPUT") return // only act on input elements ...
showHideOK(el)
btn.style.display=Object.values(ans).filter(a=>a).length==Q.length?"":"none";
});
div.onclick=ev=>{if (ev.target.type=="submit") {
ev.preventDefault();
changeQ( ev.target.classList.contains("back")?-1:1 );
}}
})
const btn = document.querySelector("button"),
Q=document.querySelectorAll(".question"),
ans={};
let current=0;
changeQ(0);
btn.style.display="none";
input.ok {display:none}
<form class="questions_box formulario" action="enviar-landing-page-v3.php" method="post">
<div class="question">
<div class="input-formulario">
<h3>The question is: ... ?</h3>
<label><input type="radio" name="objetivo" value=1 required> Answer 1.</label><br>
<label><input type="radio" name="objetivo" value=2> Answer 2.</label><br>
<label><input type="radio" name="objetivo" value=3> Answer 3.</label><br>
</div>
</div>
<div class="question">
<h3>Quantos anos tem seu filho(a)?</h3>
<div class="input-formulario">
<input required type="number" name="idade_aluno_lp" placeholder="Digite a idade do aluno" maxlength="2" />
</div>
</div>
<div class="question">
<h3>Qual seu nome?</h3>
<div class="input-formulario">
<input required type="text" name="nome_lp" placeholder="Digite seu nome"> <span></span>
</div>
</div>
<div class="question">
<h3>Qual seu email?</h3>
<div class="input-formulario">
<input required type="email" name="email_lp" id="email_lp" placeholder="Digite seu email"> <span></span>
</div>
</div>
<div class="question">
<h3>Qual seu whatsapp?</h3>
<div class="input-formulario">
<input required type="text" name="celular_lp" id="celular_lp" placeholder="Digite seu DDD + celular"
maxlength="14"> <span></span>
</div>
</div>
<br><button>Enviar todas as respostas</button>
</form>
Further explanations:
Why am I using Q.length?
The expression current = (Q.length + current + inc)/Q.length uses Q.length (=total number of questions) to keep current always within the range of existing question indexes. The term Q length+... is necessary to keep values positive for the situation where current=0 and inc=-1 and % Q.length limits the results from 0 to Q.length-1.
Why do I use .trim()?
This is just a simple way of avoiding that an answer containing only blanks would be accepted as a valid answer.
Why is there no "submit"?
I actively disabled the submit action by calling ev.preventDefault() within my event-handling function.
How to submit the answers, and when?
There are many different ways of doing it. My suggestion would be to keep cycling through the questions until all questions are answered in a valid way. At that point an extra button appears that submits all answers at once. I just added that button (btn) to the script. It is hidden at first through btn.style.display="none" but made visible again on the condition that all questions have received an answer:
btn.style.display=Object.values(ans).filter(a=>a).length==Q.length?"":"none";
The (global) object ans is constantly updated in the function showHideOK():
let ok=!!el.value.trim();
...
ans[el.name]=ok;

How to create a reply button that displays for each button clicked one at a time

I'm creating a comment and reply system, but I can't get the reply button to display the input field for only the comment.
When the any reply button is clicked, all the input fields displays instead of just the one clicked
This is my javascript:
function reply() {
var doc;
doc=document.getElementsByClassName("sho") ;
for (var i = 0 ; i < doc.length; i++){
doc[i].style.display="block ";
}
}
$('.btn-reply').on("click", function () {
var parent_dom = $(this).parent();
var _input_child_dom = $(parent_dom).children("input");
var find_allInput = $('.reply-container').find("input");
if(find_allInput.length > 0 ){
for (var i = 0; i < find_allInput.length; i++) {
$(find_allInput[i]).css("display" , "none");
}
}
$(_input_child_dom).css("display" , "block");
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="reply-container">
<div class="reply">
<p>First reply</p>
<button class="btn btn-primary btn-reply">reply</button>
<input type="text" class="InputReply" style="display: none;">
</div>
<br>
<div class="reply">
<p>Second reply</p>
<button class="btn btn-primary btn-reply">reply</button>
<input type="text" class="InputReply" style="display: none;">
</div>
<br>
<div class="reply">
<p>Third reply</p>
<button class="btn btn-primary btn-reply">reply</button>
<input type="text" class="InputReply" style="display: none;">
</div>
</div>
Note: This is the idea of how you can achieve your requirement.

Using jQuery move new children in the DOM

I am creating a HTML form for data entry that contains a couple of textboxes and function buttons.
There is also an add button that copies (clones) from a DIV template (id: w) for each "row" and appends to the end of the main DIV (id: t). On each row, there is a "X" button to remove the row and two arrow buttons to visually move the "row" up and down in the DOM.
The form is dynamically created from a database and the elements already on the page when the page is loaded and using jQuery 3.4.1, for the selecting and most of the DOM manipulation using the functionality of each rows buttons.
The "rows" are added to the container DIV and the elements are renamed depending on the counter which is expected. The "X" button deletes the "row", and moves all pre-existing rows up and down in the container DIV.
But for some unknown reason any new rows that are created I have to press the "up" button twice. The "down" button for the bottom row, is redundant and not functional.
I think it might have to do with the previousSibling and nextSibling returning the wrong Object type and causing a problem and failing the first time.
Any thoughts on how to fix or improve this functionality?
var rr = $("[id^=l]").length;
$(".data-up").click(function() {
var e = $(this).first().parent().parent().get(0);
moveUp(e);
});
$(".data-down").click(function() {
var e = $(this).parent().parent().get(0);
moveDown(e);
});
$(".remove").click(function() {
$(this).parent().parent().remove();
});
function add() {
rr += 1;
var a = $("#w").clone(true, true).removeAttr('id').removeAttr('style');
a.attr("datarow", "row" + rw);
a.find("input[data-field='l']").attr("id", "l" + rr).attr("name", "l" + rr).removeAttr("data-field");
a.find("input[data-field='s']").attr("id", "s" + rr).attr("name", "s" + rr).removeAttr("data-field");
a.appendTo("#t");
}
function moveUp(e) {
if (e.previousSibling) {
if (e.previousSibling === e.parentNode.children[0]) {} else {
e.parentNode.insertBefore(e, e.previousSibling);
}
}
}
function moveDown(e) {
if (e === e.parentNode.children[e.parentNode.children.length - 1]) {} else {
e.parentNode.insertBefore(e.nextSibling, e);
}
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
<button type="button" class="btn btn-secondary" ID="p" onclick="add();">Add</button>
<div id="t">
</div>
<div class="form-group row" id="w" style="display:none;" datarow="row">
<div class="col-sm-1"><input name="s" class="form-control txt-s col-form-label" id="s" type="text" readonly="true" data-field="s"></div>
<div class="col-sm-3"><input name="l" class="form-control txt-l" id="l" type="text" data-field="l"></div>
<div class="col-sm-2">
<button class="btn btn-danger mr-1 remove" type="button">X</button>
<button class="btn btn-info mr-1 data-up" type="button">↑</button>
<button class="btn btn-info data-down" type="button">↓</button>
</div>
</div>
With jQuery - use .closest() to find the current parent of the button. The find the .prev() or the .next() sibling. If the sibling exists use .insertBefore() or .insertAfter() to move the current parent before or after the sibling:
var rr = $("[id^=l]").length;
$(".data-up").click(function(e) {
var current = $(this).closest('.form-group'); // find the current parent
var target = current.prev(); // find the relevant sibling
if(target.length) { // if sibling exists
current.insertBefore(target); // insert the current item above it
}
});
$(".data-down").click(function() {
var current = $(this).closest('.form-group'); // find the current parent
var target = current.next(); // find the next sibling
if(target.length) { // if the next sibling exists
current.insertAfter(target); // insert the current item after it
}
});
$(".remove").click(function() {
$(this).parent().parent().remove();
});
function add() {
rr += 1;
var a = $("#w").clone(true, true).removeAttr('id').removeAttr('style');
a.attr("datarow", "row" + rr);
a.find("input[data-field='l']").attr("id", "l" + rr).attr("name", "l" + rr).removeAttr("data-field");
a.find("input[data-field='s']").attr("id", "s" + rr).attr("name", "s" + rr).removeAttr("data-field");
a.appendTo("#t");
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
<button type="button" class="btn btn-secondary" ID="p" onclick="add();">Add</button>
<div id="t">
</div>
<div class="form-group row" id="w" style="display:none;" datarow="row">
<div class="col-sm-1"><input name="s" class="form-control txt-s col-form-label" id="s" type="text" readonly="true" data-field="s"></div>
<div class="col-sm-3"><input name="l" class="form-control txt-l" id="l" type="text" data-field="l"></div>
<div class="col-sm-2">
<button class="btn btn-danger mr-1 remove" type="button">X</button>
<button class="btn btn-info mr-1 data-up" type="button">↑</button>
<button class="btn btn-info data-down" type="button">↓</button>
</div>
</div>
What's wrong in your code
The problem with the up button is e.previousSibling === e.parentNode.children[0] - the 1st element is always the first item in the collection, so this blocks you from moving an item above it. All you have to check is if there is a previousSibling for up, and nextSibling for down.
Fixed code + comments:
var rr = $("[id^=l]").length;
$(".data-up").click(function() {
var e = $(this).parent().parent().get(0); // first() is redundant - this is the only element in the collection
moveUp(e);
});
$(".data-down").click(function() {
var e = $(this).parent().parent().get(0);
moveDown(e);
});
$(".remove").click(function() {
$(this).parent().parent().remove();
});
function add() {
rr += 1;
var a = $("#w").clone(true, true).removeAttr('id').removeAttr('style');
a.attr("datarow", "row" + rr);
a.find("input[data-field='l']").attr("id", "l" + rr).attr("name", "l" + rr).removeAttr("data-field");
a.find("input[data-field='s']").attr("id", "s" + rr).attr("name", "s" + rr).removeAttr("data-field");
a.appendTo("#t");
}
function moveUp(e) {
if (e.previousSibling) { // just check if there's a previous sibling
e.parentNode.insertBefore(e, e.previousSibling);
}
}
function moveDown(e) {
if (e.nextSibling) { // just check if there's a next sibling
e.parentNode.insertBefore(e.nextSibling, e);
}
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
<button type="button" class="btn btn-secondary" ID="p" onclick="add();">Add</button>
<div id="t">
</div>
<div class="form-group row" id="w" style="display:none;" datarow="row">
<div class="col-sm-1"><input name="s" class="form-control txt-s col-form-label" id="s" type="text" readonly="true" data-field="s"></div>
<div class="col-sm-3"><input name="l" class="form-control txt-l" id="l" type="text" data-field="l"></div>
<div class="col-sm-2">
<button class="btn btn-danger mr-1 remove" type="button">X</button>
<button class="btn btn-info mr-1 data-up" type="button">↑</button>
<button class="btn btn-info data-down" type="button">↓</button>
</div>
</div>

Collect list item according to name and store in array or object

I have a dual list in which you get an option to add left list item in right list. And right list is a form. Now i am stuck at a problem where when user click the submit button all the li in right list and there inside values get store in an object with there specific name div id name. I have worked on it for 5 days now but unable to collect data according to div id name. Like
<div id="name1">
<input id="tts" type="text" value="${CTLIST.tts}"> s<br>
<input id="topic_level" type="text" value="${CTLIST.topic_level}"><br>
<label>${Object.keys(CTLIST)[4]}</label> <input id="to_be_shown_individually" type="checkbox" ${(CTLIST.to_be_shown_individually && 'checked')}> <br>
<label>${Object.keys(CTLIST)[3]}</label><input id="check_for_geometry" type="checkbox" ${(CTLIST.check_for_geometry && 'checked')}><br>
</div>
Suppose this is an li of right list.
I want data to get stored like
{
[name : name1,
tts.value : 10,
ifcheckboxcheck : true,
],
[name : name2,
tts.value : 10,
ifcheckboxcheck : true,]
}
HEre is my html
<section class="ctList">
<div class="container">
<div class="row">
<div class="dual-list list-left col-md-5">
<div class="well text-right">
<div class="row">
<div class="col-md-10">
<div class="input-group">
<span class="input-group-addon glyphicon glyphicon-search"><i class="fa fa-search"
aria-hidden="true" style="padding-right: 20px;"></i></span>
<input type="text" name="SearchDualList" class="form-control"
placeholder="search" />
</div>
</div>
<div class="col-md-2">
<div class="btn-group">
<a class="btn btn-default selector" title="select all"><i
class="glyphicon glyphicon-unchecked"></i></a>
</div>
</div>
</div>
<ul class="list-group" id="La">
</ul>
</div>
</div>
<div class="list-arrows col-md-1 text-center">
<button class="btn btn-default btn-sm move-left">
<span class="glyphicon glyphicon-chevron-left"><i class="fa fa-arrow-left"
aria-hidden="true"></i></span>
</button>
<button class="btn btn-default btn-sm move-right">
<span class="glyphicon glyphicon-chevron-right"><i class="fa fa-arrow-right"
aria-hidden="true"></i></span>
</button>
</div>
<div class="dual-list list-right col-md-5">
<div class="well">
<div class="row">
<div class="col-md-2">
<div class="btn-group">
<a class="btn btn-default selector" title="select all"><i
class="glyphicon glyphicon-unchecked"></i></a>
</div>
</div>
<div class="col-md-10">
<div class="input-group">
<input type="text" name="SearchDualList" class="form-control"
placeholder="search" />
<span class="input-group-addon glyphicon glyphicon-search"></span>
</div>
</div>
</div>
<form id="rightData" method="POST">
<ul class="list-group" id="accordian">
<!-- right list -->
</ul>
<input type="submit" value="submit" name="submit">
</form>
</div>
</div>
</div>
</div>
</section>
This is my js which is obviously not working
$('.content').hide();
$('.listelement').on('click', function () {
if (!($(this).children('.content').is(':visible'))) {
$('.content').slideUp();
$(this).children('.content').slideDown();
} else {
$('.content').slideUp();
}
});
$(function () {
$('body').on('click', '.list-group .list-group-item', function () {
$(this).toggleClass('active');
});
$('.list-arrows button').click(function () {
var $button = $(this), actives = '';
if ($button.hasClass('move-left')) {
actives = $('.list-right ul li.active');
actives.clone().appendTo('.list-left ul');
actives.remove();
} else if ($button.hasClass('move-right')) {
actives = $('.list-left ul li.active');
actives.clone().appendTo('.list-right ul');
actives.remove();
}
});
$('.dual-list .selector').click(function () {
var $checkBox = $(this);
if (!$checkBox.hasClass('selected')) {
$checkBox.addClass('selected').closest('.well').find('ul li:not(.active)').addClass('active right');
$checkBox.children('i').removeClass('glyphicon-unchecked').addClass('glyphicon-check');
} else {
$checkBox.removeClass('selected').closest('.well').find('ul li.active').removeClass('active');
$checkBox.children('i').removeClass('glyphicon-check').addClass('glyphicon-unchecked');
}
});
$('[name="SearchDualList"]').keyup(function (e) {
var code = e.keyCode || e.which;
if (code == '9') return;
if (code == '27') $(this).val(null);
var $rows = $(this).closest('.dual-list').find('.list-group li');
var val = $.trim($(this).val()).replace(/ +/g, ' ').toLowerCase();
$rows.show().filter(function () {
var text = $(this).text().replace(/\s+/g, ' ').toLowerCase();
return !~text.indexOf(val);
}).hide();
});
});
////printing properties
$(function () {
var ctList = [];
var ctRight = [];
var $tBody = $("#La");
var $rbody = $("#accordian");
$.getJSON('https://api.myjson.com/bins/d6n2a', function (data) {
data.topic_info.qt_ct_connection.map(value => {
value.ct_list.forEach((CTLIST) => {
$tBody.append(`<li class="list-group-item" id="rl">
<span id="nameOfCt">${CTLIST.ct}</span>
View More
<div id="${CTLIST.ct}" class="collapse valueDiv">
<label>${Object.keys(CTLIST)[2]}</label> <input id="tts" type="text" value="${CTLIST.tts}"><br>
<label>${Object.keys(CTLIST)[1]}</label> <input id="topic_level" type="text" value="${CTLIST.topic_level}"><br>
<label>${Object.keys(CTLIST)[4]}</label> <input id="to_be_shown_individually" type="checkbox" ${(CTLIST.to_be_shown_individually && 'checked')}> <br>
<label>${Object.keys(CTLIST)[3]}</label><input id="check_for_geometry" type="checkbox" ${(CTLIST.check_for_geometry && 'checked')}><br>
</div>
</li>`);
});
})
})
})
</script>
<script>
var SendDataObject = {};
$("#rightData").on("submit", function (event) {
event.preventDefault();
var IDs = [];
var list = {};
var data = {} ;
var tts = {};
let rightListLength;
rightListLength = $('#rightData li').length;
var tts = [];
$("#rightData li").each(function (){
$("#rightdata").find("div").each(function(){ IDs.push(this.id);
$('#rightData').find("#tts").each(function () { IDs.push(this.value)})
})
});
// $('#rightData li').each(function () {
// var a = $(this).html();
// console.log("i am writin second", list[$(this).attr('value')] = $(this).html());
// console.log(list[$(this).attr('id')] = $(this).html())
// });
console.log(IDs)
console.log(tts)
CSS
<style>
.ctList {
padding-top: 20px;
}
.ctList .dual-list .list-group {
margin-top: 8px;
}
.ctList .list-left li,
.list-right li {
cursor: pointer;
}
.ctList .list-arrows {
padding-top: 100px;
}
.ctList .list-arrows button {
margin-bottom: 20px;
}
.dual-list.list-left .well li.list-group-item .show {
display: none;
}
</style>
This is rendered HTML in browser if ony one li in right list . ANd if two li then another HTML will be rendered by diffrent i name coming from json and value .
point_in_first_quad
View More
<div id="point_in_first_quad" class="collapse valueDiv">
<label>tts</label> <input id="tts" type="text" value="10"><br>
<label>topic_level</label> <input id="topic_level" type="text" value="capable"><br>
<label>to_be_shown_individually</label> <input id="to_be_shown_individually" type="checkbox" checked=""> <br>
<label>check_for_geometry</label><input id="check_for_geometry" type="checkbox" checked=""><br>
</div>
Adjust your html to include classes or some other identifier, since you cannot have two elements with same ids, things like #topic_level, Probably add a class to help with selection, something like below should help
<div id="point_in_first_quad" class="collapse valueDiv">
<label class="tts-label">tts</label> <input id="tts" class="tts-value" type="text" value="10"><br>...
You added classes to element you want to use in your result.
Adjust the following to make your result object
var finalResult = [];
$('#accordion div').each(function(index, item) {
var $it = $(item);
var ob = {};
ob['name'] = $it.find('.tts-label').text();
ob['tts.value'] = $it.find('.tts-value').val();
ob['ifcheckboxcheck'] = $it.find('[type="checkbox"]').is(":checked");
finalResult.push(ob);
});
Since you have two checkbox field, add a class selector to the one you want to use in result.

Categories

Resources