How to append HTML content using Jquery - javascript

All what I want to do is, when the user clicks on a button, the content of the div should append at the bottom. My code works fine if I paste the content inside the div in the javascript displayed below:
My question:
1.) Without having to copy paste the code that was in the HTML to JAVASCRIPT is there any other way I could get this done.
2.) I want the name and also the value attribute of the input field to be unique (like append a number at the end ). How can I do this ?
My jQuery looks like this:
$(document).ready(function(){
$("#btn").click(function(){
$("#boxid").append('<br/>
<div class="input-group">
<input type="text" class="form-control" id="myid" placeholder="hey" value="2">
<div class="input-group-addon">?</div>
</div>
');
});
});
HTML
<button id="btn">Add another row</button>
<form action="gone/" method="get">
<div id="boxid">
<div class="input-group">
<input type="text" class="form-control" id="myid" placeholder="hey" value="2">
<div class="input-group-addon">?</div>
</div>
</div>
</form>

You can use $.clone().
$(document).ready(function() {
var counter = $('.form-control').last().val();//Get the last .form-control value, in case you decide to have more than one by default (this way the counter can start from 2 e.g)
$("#btn").click(function() {
counter++; //Increase counter
$("#boxid").append($('.input-group').eq(0).clone()); //Clone the existing first .input-group
$("#boxid .input-group").last().find('.form-control').attr('name', counter).val(counter); //Select the last appended .input-group, find the .form-control input, change input's name and value with the counter
});
});
.input-group{
margin-bottom: 1em;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button id="btn">Add another row</button>
<form action="gone/" method="get">
<div id="boxid">
<div class="input-group">
<input type="text" class="form-control" id="myid" placeholder="hey" value="1" name="1">
<div class="input-group-addon">?</div>
</div>
</div>
</form>
Initialize counter with the last input's value
In case of click on #btn increase counter.
Append to #boxid the clone of the first (.eq(0)) .input-group (It doesn't really matter if it's the first, just used it as first = template).
Select the last .input-group inside #boxid and change its name and value with the counter.
I left your <br>behind, is not used nowadays, a more correct way is using css margin (a margin of 1em is like 1 text line)

Try this code :
$(document).ready(function(){
$("#btn").click(function(){
if(checkUnique('myid')){//to check unique id
$("#boxid").append('<br/>
<div class="input-group">
<input type="text" class="form-control" id="myid" placeholder="hey" value="2">
<div class="input-group-addon">?</div>
</div>
');
}
else{
$("#boxid").append('<br/>
<div class="input-group">
<input type="text" class="form-control" id="myid1" placeholder="hey" value="2">
<div class="input-group-addon">?</div>
</div>
');
}
});
});
function checkUnique(ex){
if($('#'+ex).length==0){
return true;}
else
{return false;}
}

When i need something like this is, i use a hidden div containing template elements. When ever i need a realization of a template, i simply copy the template, change some placeholders and add it to my target element.
PS: include https://jsfiddle.net/cvf2f7dn/1/ of #Illep
css
#templates { display: none }
html
<div id="targetDiv"></div>
<div id="templates">
<div id="templeateForInputGroup">
<div class="input-group">
<input type="text" class="form-control" id="myid%%counter%%" placeholder="hey" value="%%counter%%">
<div class="input-group-addon">?</div>
</div>
</div>
</div>
<button id="addmore">Add more</button>
js
$('#addmore').click(add);
String.prototype.replaceAll = function(search, replacement) {
var target = this;
return target.replace(new RegExp(search, 'g'), replacement);
};
var counter = 0;
function add(){
var cloneHTML = $('#templeateForInputGroup').html().toString();
cloneHTML = cloneHTML.replaceAll('%%counter%%', counter);
counter++;
$('#targetDiv').append(cloneHTML);
}

Related

Prevent input to get cleared when the parend is modified

Can I have some inputs on this ?
Issue
When a form or a parent element of a form is modified, the text that was typed inside the inputs of the form get cleared. As this snipper show :
function modifyParent() {
document.getElementById("parent").innerHTML += "<br>a line get added";
}
<div id="parent">
<form>
<input type="text" id="child">
</form>
<button type="button" onclick="modifyParent()">click</button>
</div>
Hello everyone,
Solution 1
I found a first esay way to prevent it if I know where the parent is modified. As this snipper show
function modifyParent() {
var child = document.getElementById("child");
child.setAttribute("value", child.value)
document.getElementById("parent").innerHTML += "<br>a line get added";
}
<div id="parent">
<form>
<input type="text" id="child" value="">
</form>
<button type="button" onclick="modifyParent()">click</button>
</div>
This solution look great, but only if i know where ans when the parent is modified. Also if i have a multiple inputs i need to loop on document.getElementsByTagName("input").
Solution 2
Since i dont know how many buttons i have and how many inputs, this is my best solution so far :
function modifyParent() {
setInputValues();
document.getElementById("parent").innerHTML += "<br>a line get added";
}
function setInputValues() {
for (var c of document.getElementsByTagName("input"))
c.setAttribute("value", c.value);
}
<div id="parent">
<form>
<input type="text" value="">
<input type="text" value="">
<input type="text" value="">
<input type="text" value="">
</form>
<button type="button" onclick="modifyParent()">click</button>
</div>
It work well for multiple inputs but i have to call the setInputValues() function before i modify any parent everytime. I started to consider to add setInterval on this function but I stop here because i'm starting to go a bit far and it's very likely that their is a better way.
Any help will be apreciated
A cleaner solution is to use a new element for the messages. This way you can set the messages inside a container without messing with the inputs.
const messageBox = document.querySelector(".messages");
function modifyParent() {
messageBox.innerHTML += "<br>a line get added";
}
<div id="parent">
<form>
<input type="text" value="">
<input type="text" value="">
<input type="text" value="">
<input type="text" value="">
</form>
<button type="button" onclick="modifyParent()">click</button>
<div class="messages"></div>
</div>
Another quick notice, innerHTML is vulnerable for XSS attacks Try using createElement and appendChild if possible.
const parent = document.getElementById("parent");
function modifyParent() {
const br = document.createElement("br");
const text = document.createTextNode("a line get added");
parent.appendChild(br);
parent.appendChild(text);
}
<div id="parent">
<form>
<input type="text" value="">
<input type="text" value="">
<input type="text" value="">
<input type="text" value="">
</form>
<button type="button" onclick="modifyParent()">click</button>
<div class="messages"></div>
</div>

Add and remove input texts on button click

I have a form that allows a user to create custom questions.
The user needs to insert the title for the question and then choose the type of the question.
If the type of question is radio button, checkbox or a select menu it should appear a div "availableOptions" that shows by default two input texts so the user can insert some option values.
Doubt:
When this "availableOptions" div appears there is also a button "add new option" that when is clicked it should appear another input text so the user can insert a new option value. Each option should also have always a remove button associated that when is clicked the user can remove that input text, but it should be always a minimum of one input text.
Do you know how to do this properly? I have the working example below but it's working neither the append nor the remove.
Example: https://jsfiddle.net/udx6pp8u/15/
HTML:
<form id="" method="post" class="clearfix" action="">
<div class="form-group">
<label for="inputName">Title</label>
<input type="text" class="form-control" id="inputName">
</div>
<div class="form-group">
<label for="exampleFormControlSelect1">Type of Field</label>
<select class="form-control" id="customQuestionType">
<option>Text</option>
<option>Long text</option>
<option id="optionQuestion">Checkboxes</option>
<option id="optionQuestion">Radiobuttons</option>
<option id="optionQuestion">Select Menu </option>
</select>
</div>
<div class="form-group" id="availableOptions">
<label for="inputName">Available Options </label>
<div class="option">
<input type="text" class="form-control">
<button id="removeOption">Remove Option</button>
</div>
<div class="option">
<input type="text" class="form-control">
<button id="removeOption">Remove Option</button>
</div>
<div class="form-group">
<button type="button" class="btn btn-outline-primary mt-3" id="addNewOption">Add new Option</button>
</div>
</div>
<input type="submit" class="btn btn-primary float-right mt-3" value="Store"/>
</form>
CSS:
#availableOptions{display:none;}
jQuery:
var selected_option = $('#customQuestionType option:selected').attr('id');
if (selected_option == "optionQuestion") {
$('#availableOptions').show();
if ($('#addNewOption').click(function() {
$('#availableOptions')
.append('<div class="option"><input type="text" class="form-control"><button id="removeOption">Remove Option</button></div>');
}));
if ($('#removeOption').click(function() {
$('#availableOptions') // how to remove the clicked otpion?
}));
}
Try this:
Note: Don't use id. Use class instead. One document should only have one unique id. Using multiple id="removeOption" will coz your script to behave incorrectly and also choose the first found and ignore the rest having the same id
$('#customQuestionType').change(function(){
var selected_option = $('option:selected', this).val();
if (selected_option == "optionQuestion") {
$('#availableOptions').show();
$('#addNewOption').click(function() {
$('#availableOptions').append('<div class="option"><input type="text" class="form-control"><button id="removeOption">Remove Option</button></div>');
});
}
});
$(document).on('click', '.removeOption', function(e) {
e.preventDefault();
$(this).closest('.option').remove();
})
DEMO:
https://jsfiddle.net/dL7opvak/21/
EDITED

not hiding dropdown when focus changes

Let's imagine I have three inputs :
<input type="text" id="a">
<input type="text" id="b">
<input type="text" id="c">
and one div table that should drop down when writing some data into input "a" or input "b".
Well the logic I want to to take is:{
if you click and add some data to input a show that table to me->table appears->if I click on input b dont hide that div, however if I click somewhere else for example in input c, hide the table.
It's been 3rd day I cannot do this.
P.S. My boss told not to use $timeout. It should be done with blur and focus
Just wrap input a and b in same class and then use blur and focus on that class.
$(document).ready(function(){
$('#showab').hide();
$("input.change").focus(function(){
$('#showab').show();
});
$("input.change").blur(function(){
$('#showab').hide();
});
});
input{
display:block;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input class="change" type="text" id="a">
<input class="change" type="text" id="b">
<input type="text" id="c">
<div id="showab">table here</div>
$("#showData").hide();
function lookup(arg) {
var id = arg.getAttribute('id');
var value = this.value;
console.log(id);
if (id === "a" || id === "b") {
$("#showData").show();
} else {
$("#showData").hide();
}
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" id="a" onkeyup="lookup(this);" onClick="lookup(this);">
<input type="text" id="b" onkeyup="lookup(this);" onClick="lookup(this);">
<input type="text" id="c" onkeyup="lookup(this);" onClick="lookup(this);">
<div id="showData">A Or B is Clicked here</div>
You want to make use of classes when hiding or showing your div containing the table.
Also take note of the Jquery focus (click into) and blur (click out of) classes
$(".show").focus(function()
{
$('#showTable').show();
});
$(".show").blur(function()
{
$('#showTable').hide();
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input class="show" type="text" id="a">
<input class="show" type="text" id="b">
<input class="dontShow" type="text" id="c">
<div id="showTable" hidden="hidden">
<table>
<thead>
<tr><th>test 1</th><th>test 2</th></tr>
</thead>
<tbody>
<tr><td>1</td><td>2</td></tr>
<tr><td>3</td><td>4</td></tr>
</tbody>
</table>
</div>

Additional input fields when filling up previous

Im trying to add additional fields in case when my user has filled up one group of inputs. So the idea is that when he finishes filling up the last input in that group, another group of inputs for same kind of items collapses/appears under existing one. One group of items consists of three inputs. After filling up that one, another group of inputs would appear under. I will present my code under. Hope someone can help me!
<div class="new-providers">
<div class="provider-append" id="toggleExtraProvider">
<div class="form-group">
<label>Provider</label>
<input type="text" class="form-control" id="practiceProvider" placeholder="Full provider name with coredentials" />
</div>
<div class="form-group">
<label>NPI</label>
<input type="text" class="form-control" id="providerNPI" placeholder=" NPI" />
</div>
<div class="form-group">
<label>MM #</label>
<input type="text" class="form-control" id="providerM" placeholder="M Provider #" />
</div>
<hr />
</div>
</div>
I tried appending the provider-append class on to the new-providers class
This is my jQuery script:
<script type="text/javascript">
$(document).ready(function() {
$("#toggleExtraProvider div.form-group input").each(function() {
if($(this).val() =! "") {
var target = $("new-providers");
target.append(".provider-append");
}
});
});​
</script>
You need to check for empty input box in a particular div use filter() for that
and use jQuery clone() to clone the parent div (input group) if all input box filled. And you should use change event instead of input, Since input will be overkill here it will run each time when you change a single character in text box on the other hand change event fires when user finish typing and input box loose focus.
$(document).ready(function () {
$(document).on("change",".provider-append input",function(){
var allHaveText;
var parentDiv = $(this).closest("div.provider-append");
emptyInputs=parentDiv.find("input[type=text]").filter(function () {
return !this.value;
});
if(emptyInputs.length==0)
{
newGroup = parentDiv.clone().appendTo(".new-providers");
newGroup.find("input[type=text]").each(function(){
$(this).val("");
});
}
});
});
Here is a working sample
$(document).ready(function () {
$(document).on("change",".provider-append input",function(){
var allHaveText;
var parentDiv = $(this).closest("div.provider-append");
emptyInputs=parentDiv.find("input[type=text]").filter(function () {
return !this.value;
});
if(emptyInputs.length==0)
{
newGroup = parentDiv.clone().appendTo(".new-providers");
newGroup.find("input[type=text]").each(function(){
$(this).val("");
});
}
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="new-providers">
<div class="provider-append">
<div class="form-group">
<label>Provider</label>
<input type="text" class="form-control" placeholder="Full provider name with coredentials" />
</div>
<div class="form-group">
<label>NPI</label>
<input type="text" class="form-control" placeholder=" NPI" />
</div>
<div class="form-group">
<label>MM #</label>
<input type="text" class="form-control" placeholder="M Provider #" />
</div>
<hr />
</div>
</div>
I hope it will help you.

Jquery add data-rel attribute to all input fields and remove name attribute

I need to somehow have data-rel value to input field and remove name from same input field on specific class.
The code i had done so far is working to remove name from that specific field. but i can't add data-rel to that same field.
Here is the code.
$('.vf-sortable-holder').each(function() {
var empty_sortable = $(this).closest('.option').find('.empty-sortable').find('input');
var sortable_name = empty_sortable.attr('name');
input.attr('data-rel', sortable_name);
empty_sortable.removeAttr('name');
});
So html look like this
<div class="option">
<div class="vf-sortable-holder">
<div class="empty-sortable hidden">
<input type="text" name="example">
</div>
</div>
</div>
<div class="option">
<div class="vf-sortable-holder">
<div class="empty-sortable hidden">
<input type="text" name="example">
</div>
</div>
</div>
So my js code works to remove name attribute but i actually need to change name with data-rel either to remove name from html with js code and add data-rel or somehow to rename name to data-rel in the end i need it to look like this:
<div class="option">
<div class="vf-sortable-holder">
<div class="empty-sortable hidden">
<input type="text" data-rel="example">
</div>
</div>
</div>
<div class="option">
<div class="vf-sortable-holder">
<div class="empty-sortable hidden">
<input type="text" data-rel="example">
</div>
</div>
</div>
Is this what you are looking for?
$('.vf-sortable-holder').each(function() {
var empty_sortable = $(this).find('input');
var sortable_name = empty_sortable.attr('name');
empty_sortable.attr('data-rel', sortable_name).removeAttr('name');;
});
Also remove the '.' from your vf-sortable class name in the HTML.
Selecting .vf-sortable-holder, then the parent .option, then the .empty-sortable and finally the input, all inside loops, seems like jumping through a lot of hoops ?
$('.option .vf-sortable-holder .empty-sortable input').attr('data-rel', function() {
return this.name;
}).prop('name','');
Remove the . in the class name(.vf-sortable-holder)
<div class="option">
<div class="vf-sortable-holder">
<input type="text" name="example" />
</div>
</div>
<div class="option">
<div class="vf-sortable-holder">
<input type="text" name="example2" />
</div>
</div>
then
jQuery(function () {
$('.vf-sortable-holder input').attr('data-rel', function () {
var name = this.name;
$(this).removeAttr('name');
return name;
})
})
Demo: Fiddle

Categories

Resources