JQuery add elements with bootstrap styling - javascript

I am trying to add a button to a specific HTML element using jQuery similar to, (https://www.w3schools.com/jquery/jquery_dom_add.asp)
My issue is that when I try and run the code,
var txt1 = "<button type = "button" class = "btn btn-primary">text</button>";
$("#thing1").append(txt1); // Append new elements
I don't get the styling I am wanting and it is messing up another part of my code unless I do the same as above, except without the bootstrap styling like,
var txt1 = "<button">text</button>";
$("#thing1").append(txt1); // Append new elements
It works fine with the second example except for that the button styling doesn't use bootstrap like I am wanting in the first example and am not sure as to why?
A more complete picture of the code is below,
<script>
function askName(){
var name = prompt("What's your name?");
var message = "Hello " + name + ", would you like to build a table?"
document.getElementById('output').innerHTML = message;
var txt1 = "<button type = "button" class = "btn btn-primary">text</button>";
$("#thing1").append(txt1); // Append new elements
};
function tables(){
var txt1 = "<p>Text.</p>"; // Create text with HTML
var txt2 = $("<p></p>").text("Text."); // Create text with jQuery
var txt3 = document.createElement("p");
txt3.innerHTML = "Text."; // Create text with DOM
$("body").append(txt1, txt2, txt3); // Append new elements
}
</script>
<script>
$(document).ready(function(){
$("button").click(function(){
$("div").animate({
left: '250px',
opacity: '0.5',
height: '150px',
width: '150px'
});
});
});
</script>
</head>
<body>
<div class="container-fluid">
<button type = "button" class= "btn btn-primary" onclick="askName()">
Want to chat?
</button>
</div>
<h3 style = "text-align: center"class="text-primary" id="output"></h3>
<div id = thing1>
</div>
</body>
</html>

I think you just have a problem where you should be mixing your " and your '
try this:
var txt1 = "<button type = 'button' class = 'btn btn-primary'>text</button>";

Maybe the problem is with your quotes
var txt1 = "<button type = "button" class = "btn btn-primary">text</button>";
$("#thing1").append(txt1); // Append new elements
try
var txt1 = '<button type = "button" class = "btn btn-primary">text</button>';
$("#thing1").append(txt1); // Append new elements

Related

How to create html element using JavaScript and create class/id to it

I want to create html element using JavaScript and add class or id, so I can edit this element later.
I know how to create element:
<html>
<body>
<div id="new">
<p id="p1">a</p>
<p id="p2">b</p>
</div>
<script>
var tag = document.createElement("p");
var text = document.createTextNode("c");
tag.appendChild(text);
var element = document.getElementById("new");
element.appendChild(tag);
</script>
</body>
</html>
But I don't know how to add class or id to element that don't have id or class at beggining.
You can do it like this:
<script>
let myP = document.createElement("p");
// If you need change CSS you can do it like:
myP.setAttribute("style", "color: red");
myP.id='myP-ID'
myP.className = 'myP-Class'
myP.innerHTML = "SomeText for my P tag";
document.body.appendChild(myP);
</script>
you can add class :
tag.classList.add("gg");
and you can add class and id :
tag.setAttribute("id", "ff");
tag.setAttribute("class", "bb");
you can simply target the id where you want create the element and then just create the element and give it text content and just append it ,simple.
<script>
const parentdiv = document.querySelector(".new");
let tag = document.createElement("p");
tag.textContent = 'c';
tag.id = p3;
parentdiv.appendChild(tag);
</script>

onchange will run a function to create an html element the first time, but won't do it the second time

I'm trying to make a chat program in javascript that doesn't show the next question until someone types an answer for the first question.
This function works to display the first question ("paragraph one") and then display the second question ("paragraph two"), but it won't work a third time.
I keep getting an error:
"Uncaught TypeError: Cannot set property 'onchange' of null."
I have tried it with onkeyup and jquery's .keyup() function, but it gives me the same error. When I use the debugger to see the html that is generated, it shows the second paragraph, so I don't understand why the computer is saying it's null.
How can I solve this?
<div id = "div1">
</div>
<script>
function setElement(text, id, id2){
var para = document.createElement("p");
var node = document.createTextNode(text);
para.appendChild(node);
var element = document.getElementById("div1");
element.appendChild(para);
para.id = id;
var inputBox = document.createElement("input");
element.appendChild(inputBox);
inputBox.id = id2;
}
setElement("This is paragraph one.", "p1", "i1");
document.getElementById("i1").onchange = function(){setElement("This is paragraph two.", "p2", "i2")};
document.getElementById("i2").onchange = function(){setElement("This is paragraph three.", "p3", "i3")};
//Uncaught TypeError: Cannot set property 'onchange' of null
</script>
document.getElementById("i2").onchange = function(){setElement("This is paragraph three.", "p3", "i3")};
That element doesn't exist when the javascript runs so it throws an error. You would need to run this line of code after creating the new element.
function setElement(pnum){
var para = document.createElement("p");
var node = document.createTextNode("this is paragraph " + pnum + ".");
para.appendChild(node);
var element = document.getElementById("div1");
element.appendChild(para);
para.id = "p" + pnum;
var inputBox = document.createElement("input");
element.appendChild(inputBox);
inputBox.id = "i" + pnum;
pnum++;
inputBox.onchange = function(){setElement(pnum)};
}
setElement(1);
The above change will keep creating the paragraphs and input fields.
I'm not sure what you're actually trying to accomplish with this, but here is a simulation of a chat app that runs entirely in front-end javascript within a browser window.
function setElement(caller){
var outputs = document.getElementsByClassName("output");
Array.prototype.forEach.call(outputs, function(o) {
o.appendChild(makePara(caller, o));
o.scrollTop = o.scrollHeight;
});
caller.value = "";
}
function makePara(caller, o) {
var para = document.createElement("p");
var node = document.createTextNode(caller.value);
para.appendChild(node);
if (o.parentElement != caller.parentElement.parentElement) {
para.style.textAlign = "right";
para.style.backgroundColor = "#ffeeee";
} else {
para.style.textAlign = "left";
para.style.backgroundColor = "#eeffee";
}
return para;
}
var inputBox1 = document.getElementById("input1");
var inputBox2 = document.getElementById("input2");
inputBox1.onchange = function(){setElement(this)};
inputBox2.onchange = function(){setElement(this)};
.chat {
display: inline-block;
width: 200px;
padding: 20px;
border: 1px solid black;
}
.output {
width: 200px;
height: 200px;
overflow-y: scroll;
overflow-x: wrap;
}
<div id="div1" class="chat">
<h4>Chat window 1</h4>
<div id="txt1" class="output"></div>
<div id="inpt1">
<input type='text' id="input1" />
</div>
</div>
<div id="div2" class="chat">
<h4>Chat window 2</h4>
<div id="txt2" class="output"></div>
<div id="inpt2">
<input type='text' id="input2" />
</div>
</div>
Here is what I ended up with, thanks to Momus and https://www.w3schools.com/css/tryit.asp?filename=trycss_display_js. Thanks also to everybody who kept telling me the elements didn't exist yet. I decided to make them exist first, and then use javascript to show them.
<div id = "div1">
<p id = "p1" style = "display:none;">Hi, I'm RiddleBot. What is your name?</p>
<input id = "i1" type = "text" style = "display:none;">
<p id = "p2" style = "display: none;">Hi. What do you like to do?</p>
<input id = "i2" type = "text" style = "display:none;">
<p id = "p3" style = "display: none;">I like to tell riddles. Do you want to hear one?</p>
<input id = "i3" type = "text" style = "display:none;">
<p id = "p4" style = "display: none;">In marble walls as white as...</p>
<input id = "i4" type = "text" style = "display:none">
</div>
<script>
function showElement(pnum){
var inputBox = document.getElementById("i" + pnum);
document.getElementById("p" + pnum).style.display = "block";
document.getElementById("i" + pnum).style.display = "block";
pnum++;
inputBox.onchange = function () {showElement(pnum)};
}
showElement(1);
</script>

How to add working dropify inputs dynamically

I have form which gets clone when user click on add more button .
This is how my html looks:
<div class="col-xs-12 duplicateable-content">
<div class="item-block">
<button class="btn btn-danger btn-float btn-remove">
<i class="ti-close"></i>
</button>
<input type="file" id="drop" class="dropify" data-default-file="https://cdn.example.com/front2/assets/img/logo-default.png" name="sch_logo">
</div>
<button class="btn btn-primary btn-duplicator">Add experience</button>
...
</div>
This my jquery part :
$(function(){
$(".btn-duplicator").on("click", function(a) {
a.preventDefault();
var b = $(this).parent().siblings(".duplicateable-content"),
c = $("<div>").append(b.clone(true, true)).html();
$(c).insertBefore(b);
var d = b.prev(".duplicateable-content");
d.fadeIn(600).removeClass("duplicateable-content")
})
});
Now I want every time user clicks on add more button the id and class of the input type file should be changed into an unique, some may be thinking why I'm doing this, it I because dropify plugin doesn't work after being cloned, but when I gave it unique id and class it started working, here is what I've tried :
function randomString(len, an){
an = an&&an.toLowerCase();
var str="", i=0, min=an=="a"?10:0, max=an=="n"?10:62;
for(;i++<len;){
var r = Math.random()*(max-min)+min <<0;
str += String.fromCharCode(r+=r>9?r<36?55:61:48);
}
return str;
} var ptr = randomString(10, "a");
var className = $('#drop').attr('class');
var cd = $("#drop").removeClass(className).addClass(ptr);
Now after this here is how I initiate the plugin $('.' + ptr).dropify().
But because id is still same I'm not able to produce clone more than one.
How can I change the id and class everytime user click on it? is there a better way?
Working Fiddle.
Problem :
You're cloning a div that contain already initialized dropify input and that what create the conflict when you're trying to clone it and reinitilize it after clone for the second time.
Solution: Create a model div for the dropify div you want to clone without adding dropify class to prevent $('.dropify').dropify() from initialize the input then add class dropify during the clone.
Model div code :
<div class='hidden'>
<div class="col-xs-12 duplicateable-content model">
<div class="item-block">
<button class="btn btn-danger btn-float btn-remove">
X
</button>
<input type="file" data-default-file="http://www.misterbilingue.com/assets/uploads/fileserver/Company%20Register/game_logo_default_fix.png" name="sch_logo">
</div>
<button class="btn btn-primary btn-duplicator">Add experience</button>
</div>
</div>
JS code :
$('.dropify').dropify();
$("body").on("click",".btn-duplicator", clone_model);
$("body").on("click",".btn-remove", remove);
//Functions
function clone_model() {
var b = $(this).parent(".duplicateable-content"),
c = $(".model").clone(true, true);
c.removeClass('model');
c.find('input').addClass('dropify');
$(b).before(c);
$('.dropify').dropify();
}
function remove() {
$(this).closest('.duplicateable-content').remove();
}
Hope this helps.
Try this:
$(function() {
$(document).on("click", ".btn-duplicator", function(a) {
a.preventDefault();
var b = $(this).parent(".duplicateable-content"),
c = b.clone(true, true);
c.find(".dropify").removeClass('dropify').addClass('cropify')
.attr('id', b.find('[type="file"]')[0].id + $(".btn-duplicator").index(this)) //<here
$(c).insertBefore(b);
var d = b.prev(".duplicateable-content");
d.fadeIn(600).removeClass("duplicateable-content")
})
});
Fiddle
This does what you specified with an example different from yours:
<div id="template"><span>...</span></div>
<script>
function appendrow () {
html = $('#template').html();
var $last = $('.copy').last();
var lastId;
if($last.length > 0) {
lastId = parseInt($('.copy').last().prop('id').substr(3));
} else {
lastId = -1;
}
$copy = $(html);
$copy.prop('id', 'row' + (lastId + 1));
$copy.addClass('copy');
if(lastId < 0)
$copy.insertAfter('#template');
else
$copy.insertAfter("#row" + lastId);
}
appendrow();
appendrow();
appendrow();
</script>
Try adding one class to all dropify inputs (e.g. 'dropify'). Then you can set each elements ID to a genereted value using this:
inputToAdd.attr('id', 'dropify-input-' + $('.dropify').length );
Each time you add another button, $('.dropify').length will increase by 1 so you and up having a unique ID for every button.

Deleting specific div's with JavaScript

I am trying to spawn different div's and remove them after they do their job. A simple version of my code is:
function eraseDiv(){
var c = document.getElementById("cn1");
c.parentNode.removeChild(child);
}
function spawnDiv(){
var x = document.getElementById("test");
var d = document.createElement("div");
d.id = "child";
d.style.width = "500px";
d.style.height = "30px";
var content = "Some text for testing!" + "<a href=\"?\" onclick=eraseDiv(); return false; > Delete</a>";
d.innerHTML = content;
if (document.getElementById("cn1").innerHTML.trim() == "")
document.getElementById("cn1").appendChild(d);
else
document.getElementById("cn2").appendChild(d);
}
<input type="submit" name="Submit" value="Spawn" onclick="spawnDiv(); return false;" />
<div id= "test">
<div id= "cn1"></div>
<div id= "cn2"></div>
</div>'
The problem is that when the first spawned div is deleted, all div's are deleted. Any help is appreciated on how to fix this.
How about something like this:
function eraseDiv(target){
var div = target.parentNode;
var container = div.parentNode;
container.removeChild(div);
}
function spawnDiv(){
var x = document.getElementById("test");
var d = document.createElement("div");
d.style.width = "500px";
d.style.height = "30px";
var content = "Some text for testing!" + "<button onclick=eraseDiv(this);> Delete</button>";
d.innerHTML = content;
if (document.getElementById("cn1").innerHTML.trim() == "")
document.getElementById("cn1").appendChild(d);
else
document.getElementById("cn2").appendChild(d);
}
<button type="button" name="submit" onclick="spawnDiv();">Spawn</button>
<div id= "test">
<div id= "cn1"></div>
<div id= "cn2"></div>
</div>
First thing, since you're returning false every time you obviously don't want to use the submit functionality of your submit input, so change it to a button instead.
Second thing, remove the ID from the spawned div since you should never have two divs with the same ID.
Third thing (like the first thing) since you're not using the link functionality of the anchor element, you should change it to a button instead (using CSS you can style this like an anchor if you want to).
Fourth thing, inside the delete button, add this as a parameter to the eraseDiv function. You can now access the button that was clicked using the function parameter rather than trying to find it by an ID.
The simplest fix to your code without modifying the functionality (and view of the page) of what you did is to replace the href="?" with href="#".
In your original code, when you do something like link with the "?" as the hyperlink, this actually performs a GET request which will reload the page. This is tricky because it makes it seem like your delete code is removing all the spawned divs from both cn1 and cn2 divs.
Changing the href=? to href=# prevents a GET request from happening. Below is a snippet that directly makes this change that results in the correct behavior of your original code (by deleting the spawned element in cn1). You will have to further modify your code to make it do what you want.
function eraseDiv(){
var c = document.getElementById("cn1");
c.parentNode.removeChild(c);
}
function spawnDiv(){
var x = document.getElementById("test");
var d = document.createElement("div");
d.id = "child";
d.style.width = "500px";
d.style.height = "30px";
var content = "Some text for testing!" + "<a href=\"#\" onclick=eraseDiv(); return false; > Delete</a>";
d.innerHTML = content;
if (document.getElementById("cn1").innerHTML.trim() == "")
document.getElementById("cn1").appendChild(d);
else
document.getElementById("cn2").appendChild(d);
}
<input type="submit" name="Submit" value="Spawn" onclick="spawnDiv(); return false;" />
<div id= "test">
<div id= "cn1"></div>
<div id= "cn2"></div>
</div>
Another way of doing it would be to create a id for div like this
<html>
<body>
<input type="submit" name="Submit" value="Spawn" onclick="spawnDiv(); return false;" />
<div id= "test">
<div id= "cn1"></div>
<div id= "cn2"></div>
</div>
<script>
function eraseDiv(j){
var c = document.getElementById('child'+j);
c.parentNode.removeChild(c);
}
var i=1;
function spawnDiv(){
var x = document.getElementById("test");
var d = document.createElement("div");
d.id = "child"+i;
d.style.width = "500px";
d.style.height = "30px";
var content = "Some text for testing!" + "<u ><a onclick=eraseDiv("+i+++"); > Delete</a></u>";
d.innerHTML = content;
if (document.getElementById("cn1").innerHTML.trim() == "")
document.getElementById("cn1").appendChild(d);
else
document.getElementById("cn2").appendChild(d);
}
</script>
</body>
</html>

HTML and JS : Capture Key Value pairs in HTML form

I have a Spring MVC application where I am required to capture a variable number of key value pairs based on user input. The HTML & JS part of the code to render the controls is as follows :
<tr>
<td><label>Attributes (Names & Value(s))</label></td>
<td><input id="Button1" type="button" value="Add" onclick="Button1_onclick()"/></td>
</tr>
<script language="javascript" type="text/javascript">
var NumOfRow = 1;
var attribs = {};
function Button1_onclick() {
NumOfRow++;
// get the reference of the main Div
var mainDiv = document.getElementById('MainDiv');
// create new div that will work as a container
var newDiv = document.createElement('div');
newDiv.setAttribute('id', 'innerDiv' + NumOfRow);
//create span to contain the text
var newSpan = document.createElement('span');
newSpan.innerHTML = "Attribute Type";
// create new textbox for type entry
var newTextBox = document.createElement('input');
newTextBox.type = 'text';
newTextBox.setAttribute('id', 'DimensionType' + NumOfRow);
//create span to contain the text
var newSpan2 = document.createElement('span');
newSpan2.innerHTML = "Attribute Value(s)";
// create new textbox for value entry
var newTextBox2 = document.createElement('input');
newTextBox2.type = 'text';
newTextBox2.setAttribute('id', 'DimensionValue' + NumOfRow);
// create remove button for each attribute
var newButton = document.createElement('input');
newButton.type = 'button';
newButton.value = 'Remove';
newButton.id = 'btn' + NumOfRow;
// attach event for remove button click
newButton.onclick = function RemoveEntry() {
var mainDiv = document.getElementById('MainDiv');
mainDiv.removeChild(this.parentNode);
NumOfRow--;
}
// append the span, textbox and the button
newDiv.appendChild(newSpan);
newDiv.appendChild(newTextBox);
newDiv.appendChild(newSpan2);
newDiv.appendChild(newTextBox2);
newDiv.appendChild(newButton);
// finally append the new div to the main div
mainDiv.appendChild(newDiv);
}
}
</script>
I am not sure how to send this captured data back to my controller when the form is submitted. Please advise. Also if there is a better way to capture such data, those suggestions are most welcome as well.
What about making Capture key event in a text field you can do this :
<html>
<head>
<script language="JavaScript" type = "text/javascript">
<!--
document.onkeypress = DisplayMsg;
function DisplayMsg(key_event)
{
if (document.all) //Checks for IE 4.0 or later
{
document.form1.text2.value = String.fromCharCode(event.keyCode);
}
else if (document.getElementById) //checks for Netscape 6 or later
{
document.form1.text2.value = String.fromCharCode(key_event.which);
}
else if (document.layers) //Checks for Netscape 4
{
document.form1.text2.value = String.fromCharCode(key_event.which);
}
}
//-->
</script>
<title>Capture Key Pressed</title>
</head>
<body>
<form name="form1">
<b>Type value in field: See what you typed:</b><br>
<input type = "text" name = "text1" onKeyPress="DisplayMsg(event)" size="20">
<input type = "text" name = "text2" onKeyPress="DisplayMsg(event)" size="20">
</form>
</body>
</html>

Categories

Resources