Better way to code rather than using whole new code with `insertAdjacentHTML` - javascript

I am trying to add new input and button when clicking certain button.
<div class="form-group row">
<label>...</label>
<div class="col-sm-9 input-group" id="aa">
<input class="form-control mr-2" id="bbb" name="bbb" required type="text">
<div class="input-group-append">
<button type="button" class="btn btn-block btn-outline-info float-right" onclick="add()">Add</button>
</div>
</div>
</div>
Here is my question.
By clicking on button, I want to add same input and button under input(id="aa"). And every time when clicking on new button I want to add new input and button again.
I tried to solve by using insertAdjacentHTML. But this requires long whole new code. So wondering if there is more simple way to add new input and button.
※ Code I am trying to add
<div class="col-sm-9 input-group" id="aa">
<input class="form-control mr-2" id="bbb" name="bbb" required type="text">
<div class="input-group-append">
<button type="button" class="btn btn-block btn-outline-info float-right" onclick="add()">Add</button>
</div>
</div>
Next I am trying to change adding button to delete button when new input and button is clicked. Can use remove method. But I need each id of new input and button. So wondering if there is specific way to assign different id to new input and button every time I add one?
Hope someone can show me at least where I can refer to.

Don't use the ID, use relative addressing, parentNode, closest etc. And use cloneNode to get the stuff you want to duplicate
Note, you do need "new long code" for this
window.addEventListener("load",function() {
document.addEventListener("click",function(e) { // delegation
var elem = e.target;
if (elem.className.indexOf("btn") == 0) {
var div = elem.closest("div.form-group");
if (elem.innerText=="Add") {
var newDiv = div.cloneNode(true); // deep cloning
newDiv.querySelector(".btn").innerText="Del";
// here you may want to rename the input field too
div.parentNode.appendChild(newDiv);
}
else {
div.parentNode.removeChild(div);
}
}
});
});
<div class="form-group row">
<label>...</label>
<div class="col-sm-9 input-group">
<input class="form-control mr-2" name="bbb" required type="text">
<div class="input-group-append">
<button type="button" class="btn btn-block btn-outline-info float-right">Add</button>
</div>
</div>
</div>

Related

Get the second children of the parent div?

I basically have this generated html and I need to get into the input element (the second child of the div) and take his value.
I started from the first child button and I managed to get to the parent <div> by using var parent = $(elem).closest("div"); (this in a javascript function called with the onClick event).
I then saved the parent in a variable and now I'm trying to get to the second element without results. I tried everything but I'm just not able to get in there even with closest() starting from the first button.
I can't use any id or anything like that to search for the elements, I need to get there by navigating the DOM, any solution?
<div class="px-3" id="' . $row["idEvent"] . '">
<button type="button" class="btn bg-light border rounded-circle"><i class="fas fa-minus" onClick="decreaseQuantity(this)"></i></button>
<input type="text" class="form-control w-25 d-inline" value="' . $row["TicketQuantity"] . '">
<button type="button" class="btn bg-light border rounded-circle"><i class="fas fa-plus"></i></button>
</div>
function decreaseQuantity(e){
var closestdiv = jQuery(e).parent();
var inputval = closestdiv.find('input').val();
alert(inputval);
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="px-3" id="event">
<button type="button" class="btn bg-light border rounded-circle" onClick="decreaseQuantity(this)">Minus<i class="fas fa-minus" ></i></button>
<input type="text" class="form-control w-25 d-inline" value="2">
<button type="button" class="btn bg-light border rounded-circle">Plus<i class="fas fa-plus"></i></button>
</div>
Please try this. I hope you will get your answer
.closest() will always traverse the DOM upward until it finds a match.
There are multiple ways to do what you're trying to accomplish.
Here's 3 ways of doing it
$('button').on('click', function() {
var parent = $(this).parent();
alert(parent.find('input').val());
//OR
alert(parent.children('input').val());
//OR
alert($(this).siblings('input').val());
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="px-3">
<button class=" btn bg-light border rounded-circle">
-
</button>
<input type="text" class="form-control w-25 d-inline" value="value">
<button type="button" class="btn bg-light border rounded-circle">
+
</button>
</div>
This code works well as long as you don't have more than one input field.
If you had more that one input field, you would need to access the input field with a class.

how to append an existing form on button click using jQuery

Given some html, a form named InterfacesIx and a button named addInterfacesIx
<div class="step-new-content white-text">
<p class="text-monospace"><small>helps you rollout a configlet about blahblah</small></p>
<form name="InterfacesIx">
<div class="row">
<div class="md-form col-12">
<input type="text" name="xxx" class="form-control white-text" placeholder="123"><label for="xxx">asn</label>
</div>
<div class="md-form col-12">
<textarea name="yyy" class="md-textarea form-control white-text" rows="3"></textarea><label for="yyy">notes</label>
</div>
</div>
<br><br><br>
</form>
<div class="col-12 text-center">
<button type="button" name="addInterfacesIx" class="btn btn-block btn-flat"><i class="fas fa-plus"></i></button>
</div>
</div>
I would like to clone/duplicate the form when the user clicks on the addInterfacesIx button using jQuery I guess.
The jQuery that I am trying looks like this:
<script>
$(document).ready(() => {
$('addInterfacesIx').click(function(){
$('InterfacesIx').clone().insertBefore('addInterfacesIx');
});
});
</script>
When I do console.log($('InterfacesIx')); nothing gets printed out. Is the selector wrong ?
When inspecting the form element on the browser I get:
copy attribute shows name="InterfacesIx"
copy selector path shows #stepper-navigation > li > div.step-new-content.white-text > form
copy xml shows //*[#id="stepper-navigation"]/li/div[2]/form
Would you be so kind to advise what I am doing wrong and how to achieve the desired result ?
Your selector $('addInterfacesIx') is not valid. If you want to grab an element by name you should use attribute selector, something like this: $( "form[name='addInterfacesIx']"). However, as mentioned before, grabbing element by class or ID is definitely better.
$('addInterfacesIx') and $('InterfacesIx') aren't valid selectors. I'd suggest putting id/class attributes on the relevant elements and then selecting them by that.
I also assume that the form elements should be siblings, as such try using insertAfter() and placing the new form after the last one currently in the DOM. Your current logic would place the new form inside the button container. Try this:
jQuery(($) => {
$('#addInterfacesIx').click(function() {
$('.interfacesIx:first').clone().insertAfter('.interfacesIx:last');
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="step-new-content white-text">
<p class="text-monospace"><small>helps you rollout a configlet about blahblah</small></p>
<form name="InterfacesIx" class="interfacesIx">
<div class="row">
<div class="md-form col-12">
<input type="text" name="xxx" class="form-control white-text" placeholder="123"><label for="xxx">asn</label>
</div>
<div class="md-form col-12">
<textarea name="yyy" class="md-textarea form-control white-text" rows="3"></textarea><label for="yyy">notes</label>
</div>
</div>
<br><br><br>
</form>
<div class="col-12 text-center">
<button type="button" name="addInterfacesIx" id="addInterfacesIx" class="btn btn-block btn-flat"><i class="fas fa-plus"></i></button>
</div>
</div>
You are confusing the fact that a name attribute is not normally used as a jQuery selector - the name attribute is normally used for keys to form values when they are submitted to the server. You can select elements using the name attribute, as indicated by the code below, but using id and class attributes is preferred.
<form id="InterfacesIx" name="InterfacesIx">
...
</form>
<div class="col-12 text-center">
<button type="button" id="addInterfacesIx" class="btn btn-block btn-flat"><i class="fas fa-plus"></i></button>
</div>
<script>
$(document).ready(() => {
$('#addInterfacesIx').click(function(){
// $('#InterfacesIx') is better
$('[name=InterfacesIx]').clone().insertBefore('addInterfacesIx');
});
});
</script>

How to create dynamic element in a dynamic form

this is my code for first element, inside of first dynamic form
<input type="text" class=" form-control" id="pPilihan" style="font-size: 1rem;" name="p_pilihan[]" required placeholder="Masukan Nama Pilihan, contoh: Merah / XL">
Tambah
this is my code for add input element
<div class="copy d-none">
<div class="control-group input-group" style="margin-top:10px">
<input type="text" class="form-control" id="pPilihan" style="font-size: 1rem;" name="p_pilihan[]" required placeholder="Masukan Nama Pilihan, contoh: Merah / XL">
<div class="input-group-btn">
<button class="btn btn-danger remove" type="button"><i class="glyphicon glyphicon-remove"></i> Hapus</button>
</div>
</div>
</div>
and this is my js
$(document).ready(function() {
$("body").on("click", ".add-more", function(){
var html = $(".copy").html();
$(".after-add-more").before(html);
});
$("body").on("click",".remove",function(){
$(this).parents(".control-group").remove();
});
});
The question is not clear to me but I can see a bug in your code, you simply can't have two elements having the same id. Each time 'add more' button is clicked the input element with id="pPilihan" is getting repeated, which is wrong. You can solve this by using a counter to produce a dynamic id (if you need one).

How to clear text id in javascript

I have a one text box search, and one button,when i add the text and click button, related data will be getting but when i click another search.that is taking same id,previous id not clearing. how to clear that id
<div class="col-lg-4 col-sm-4 col-xs-12">
<i class="glyphicon glyphicon-search"></i>
<div class="form-group">
<input type="text" class="form-control" id="isbncollegeid" data-ng-model="isbncollege" placeholder=" Search By college ISBN" name="isbncollegeid">
</div>
</div>
<div class="col-sm-4">
<br />
<div class="form-group">
<input type="hidden" id="bookcollgeIsbn" name="bookcollgeIsbn" />
<button type="button" class="btn btn-sky" id="IsbntcolDetails" data-ng-disabled="LibraryIsbnForm.$invalid" data-ng-click="DetailscolByISBN()">Get Details<i class="fa fa-exclamation"></i>
</button>
<button type="button" class="btn btn-sky" id="clear" data-ng-click="ClearISbnCollege()">Clear<i class="fa fa-exclamation"></i>
</button>
</div>
</div>
In your ClearISbnCollege just make isbncollege model empty
$scope.ClearISbnCollege = function() {
$scope.isbncollege = "";
}
When you will click the Clear button, input will be emptied.
You can use below line of code after getting results in javascript:
document.getElementById('elementid').value = "";
in Jquery:
$('#elementid').val("");

How to delete total div content using Javascript/Jquery

I need to delete the last textarea in a div.
<div id="container">
<!-- question 1st box starts here -->
<div class="col-md-4">
<div class="questionparts">
<div class="form-group">
<label for="title">Questions</label>
<textarea class="form-control" name="questions0" id="questions0" placeholder="Questions" style="background:#FFFFFF;" rows="2"></textarea>
</div>
<div class="clear"></div>
<div class="questionshowp">
<h4 class="page-title">Multiple Choice</h4>
<h6>Your audience can select from these answers:</h6>
<div class="form-group">
<input name="questions1" id="questions1" class="form-control firstsec" placeholder="Text, Image URL, or LaTeX" value="" type="text">
<div class="secondsec">
<button type="button" class="btn btn-sm btn-success" style="line-height:12px;"><i class="fa fa-plus" aria-hidden="true"></i></button>
<button type="button" class="btn btn-sm btn-danger" style="line-height:12px;"><i class="fa fa-minus" aria-hidden="true"></i></button>
</div>
</div>
<div class="clear"></div>
</div>
</div>
</div>
<!-- question 1st box end here -->
<!-- question 2nd box starts here -->
<div class="col-md-4">
<div class="questionparts">
<div class="form-group">
<label for="title">Questions</label>
<textarea class="form-control" name="questions0" id="questions0" placeholder="Questions" style="background:#FFFFFF;" rows="2"></textarea>
</div>
<div class="clear"></div>
<div class="questionshowp">
<h4 class="page-title">Multiple Choice</h4>
<h6>Your audience can select from these answers:</h6>
<div class="form-group">
<input name="questions1" id="questions1" class="form-control firstsec" placeholder="Text, Image URL, or LaTeX" value="" type="text">
<div class="secondsec">
<button type="button" class="btn btn-sm btn-success" style="line-height:12px;"><i class="fa fa-plus" aria-hidden="true"></i></button>
<button type="button" class="btn btn-sm btn-danger" style="line-height:12px;"><i class="fa fa-minus" aria-hidden="true"></i></button>
</div>
</div>
<div class="clear"></div>
</div>
</div>
</div>
<!-- question 2nd box end here -->
</div>
Here I need to delete the last textarea ('in this case 2nd box') always. Check javascript below.
function deleteQuestionField(){
var textareas = $('#container textarea');
console.log('hii',textareas);
if (textareas.length !== 0) {
textareas.last().remove();
}
}
This function is called from a button click event but its not deleting the last textarea.
Simply use jQuery's .remove() (see here for more info):
Give your div that you want to remove a unique id and then call it:
HTML:
....
<!-- question 2nd box starts here -->
<div class="col-md-4" id="someUniqueId">
....
Javascript:
function deleteQuestionField(){
var textareas = $('#container textarea');
console.log('hii',textareas);
if (textareas.length !== 0) {
$("#someUniqueId").remove(); //This will remove the unique id element
}
}
You have the html() function in jQuery
http://api.jquery.com/html/ to remove all codes between an element
The remove() function you used delete the selected element
If you want to delete the content of the textarea, try to use the val() function instead.http://api.jquery.com/val/
$('textarea').val('');
If I understand it correctly if the first textarea is not empty you want to remove the second 'box' . If this is the case you should select the first textarea and not textarea in general (I assume)
firstly add an ID to the second div <div class="col-md-4" id="remove_this"> and call the ID in the remove function
So probably it would be something like:
function deleteQuestionField(){
var textareas = $('#questions0'); //if you want general just use textarea ( `$('#container textarea');`)
console.log('hii',textareas);
if (textareas.length !== 0) {
$("#remove_this").remove();
}
}
Documentation about the .remove function HERE
You want to delete total div ,but you are making delete only textarea element
textareas.last().remove();
//change above code to like below ,it will delete the whole div
$(".col-md-4").last().remove();
With Jquery
$("#item_id").empty();
It works

Categories

Resources