Create html element with jquery based on user input - javascript

So after searching a while I haven't been able to find an existing question that seems to address this in a way that I can relate to with my specific issue. If there is already a good thread on this that I missed, my apologies in advance and feel free to just post a link to it and call me a dummy!
In plain english, here's the goal: I basically want to generate some html with jquery but with a couple of twists. There will basically be two sets of content that will alternate with every other number, I'll call them content-a and content-b. The user is prompted to enter a number, let's say user enters 4. Upon submitting this value, the markup is then generated like so: (1)content-a (2)content-b (3)content-a (4)content-b.
So here's a bit of code that hopefully will help a little.
I'm aware of how to generate html, but that's about as far as I've gotten so far, my js is definitely a weak point and needs lots of practice:
$("#targetDIV").html("<h1>Hello World!</h1> <p>This is a big fat test</p>");
The markup is simple enough, almost seems pointless to post it in here since it's kind of obvious but I'll do it anyway:
<div id="targetDIV" style="border: 3px solid purple">
</div>
The desired output though would be something like this, based on the value the user chooses but let's just stick with the 4 example:
<div id="targetDIV" style="border: 3px solid purple">
<!-- Content A -->
<h1>Hello World!</h1>
<p>This is a big fat test</p>
<!-- Content B -->
<h1>Hello Universe!</h1>
<p>This is a super mega big fat test</p>
<!-- Content A -->
<h1>Hello World!</h1>
<p>This is a big fat test</p>
<!-- Content B -->
<h1>Hello Universe!</h1>
<p>This is a super mega big fat test</p>
</div>
Hopefully there's enough here to go on or to at least point me in the right direction, thanks in advance for any wisdom any of you might offer up!

Here is a full, working live example that does exactly what you're looking for.
The following code will take a numerical input from the user, then append alternating sets of content according to the number the user inputted:
var num = prompt("Enter a number");
var contenta = "<h1>Hello World!</h1> <p>This is a big fat test</p>";
var contentb = "<h1>Hello Universe!</h1> <p>This is a super mega big fat test</p>";
var targetDiv = $("#targetDIV");
console.log(targetDiv);
for (var i = 0; i < num; i++) {
if (i % 2 === 0) targetDiv.append(contenta);
else targetDiv.append(contentb);
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="targetDIV" style="border: 3px solid purple">
</div>

You could assign the two html strings to the indices of an array.
var str1 = "<h1>Hello World!</h1> <p>This is a big fat test</p>"
var str2 = "<h1>Hello Universe!</h1> <p>This is a super mega big fat test</p>"
var responses = [str1, str2];
Then, you can use a for loop that will repeat as many times as the user's input.
And in each iteration of the loop, you could perhaps $('#targetDIV').append(responses[i % 2]);

You could do something like this.
$('#number').change(function() {
var ind = $(this).val()
$('#target-div').append($('#holder div').get(ind))
});
This keeps the HTML in a hidden div, then extracts your desired content by its index. Not the best way but works.
JSFiddle

If you are simply alternating between two content sets, you can simply store them as a JS array, say content, and generate/insert them on the fly.
The key is to empty your target element when the user updates the change count, and access the correct element in the array based on the modulus of the array size, i.e. content[i%content.length]. This method allows you to arbitarily increase the size of your content array, and the script will keep inserting elements by going through the list, and repeat from the start when it reaches the end.
$(function() {
var content = [
'<h1>Hello World!</h1> <p>This is a big fat test</p>',
'<h1>Hello Universe!</h1><p>This is a super mega big fat test</p>'
];
$('#count').on('change', function() {
$('#targetDIV').empty();
var count = parseInt($(this).val());
for (var i = 0; i < count; i++) {
$('#targetDIV').append(content[i%content.length]);
}
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input id="count" type="number" min="0" step="1" value="0" placeholder="0" />
<div id="targetDIV" style="border: 3px solid purple"></div>

I am not an expert js dev but cooked something quick and easy for you.
link to codepen:http://codepen.io/anon/pen/OVdMow

$(function() {
var A = '<!-- Content A --><h1>Hello World!</h1><p>This is a big fat test</p>';
var B = '<!-- Content B --><h1>Hello Universe!</h1><p>This is a super mega big fat test</p>';
var targetDiv = $('#targetDIV');
$('#listCount').on('input', function() {
targetDiv.empty();
for(var i = 0; i < +this.value; i++) {
targetDiv.append( i % 2 == 0 ? A : B );
}
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="number" name="listCount" id="listCount"/>
<div id="targetDIV" style="border: 3px solid purple">
</div>

function generateElments() {
var num = $("#numOfElements").val();
var writeA = true;
var aElement = "<p>I am <strong>A</strong>!</p>";
var bElement = "<p>I am <strong>B</strong>!</p>";
for (var i = 0; i < num; i++) {
$("#elements-container").append(writeA ? aElement : bElement);
writeA = !writeA;
};
};
Here is a working plunker of what you need!
http://plnkr.co/edit/qI1LtBwDwu7KIKFzUehB?p=preview

Related

How to swap contents of header tag - HTML/Javascript

I have the following:
function changeFirst() {
let p = document.getElementById("firstElement")[0].innerhtml;
alert(p);
if (p = "<h1>This is the 1st element</h1>") {
document.getElementById("firstElement").innerHTML = "<h1>Changed first</h1>"
} else {
document.getElementById("firstElement").innerHTML = "<h1>Switched back first</h1>"
}
}
<div id="firstElement">
<h1>This is the 1st element</h1>
</div>
<button onclick="changeFirst()">Change first element</button>
I basically want the button to alternate the contents of the firstElement div. Why doesn't this work?
Thank you
document.getElementById returns ONE element
Also = is assignment, you want == or === for comparison
Could you possibly mean this:
function changeFirst() {
let h = document.querySelector("#firstElement h1");
h.textContent = h.textContent==="This is the 1st element" ? "Changed first" : "This is the 1st element"
}
<div id="firstElement">
<h1>This is the 1st element</h1>
</div>
<button type="button" onclick="changeFirst()">Change first element</button>
Here is exactly what you asked for. You were close.
1) when including javascript, you can just use script tags and it will work fine, when you use JSON or JQuery, that's when you have to use an include tag of a .js file. javascript code can be notated with script type = text/javascript.
2) when making a comparison in javascript: use three equal signs (===)
when making a non variable type-sensitive comparison: use two equal signs (==)
when setting a variable: use one equal sign (=)
https://www.geeksforgeeks.org/difference-between-and-operator-in-javascript/
3) When calling dynamic header, it is not an array, so you don't need [0], you are just comparing the innerhtml of the dynamic header div and it is only one header, arrays are for multiple things. Keep working on code, as you seem to have a good start, and made some minor syntax errors.
<!DOCTYPE html>
<html>
<body>
<button onclick="changeHeader()">Click me</button>
<div id="dynamicHeader"><h1>Hello World</h1></div>
<p>Clicking the button changes the header.</p>
<script>
function changeHeader() {
if (document.getElementById("dynamicHeader").innerHTML === "<h1>Hello World</h1>") {
document.getElementById("dynamicHeader").innerHTML = "<h1>Goodbye World</h1>";
} else {
document.getElementById("dynamicHeader").innerHTML = "<h1>Hello World</h1>"
}
}
</script>
</body>
</html>
Try like this. Here I introduced a flag and switched it to check content.
var changed = false;
function changeFirst() {
if (!changed) {
changed = true;
document.getElementById("firstElement").innerHTML = "<h1>Changed first</h1>";
} else {
changed = false;
document.getElementById("firstElement").innerHTML = "<h1>Switched back first</h1>";
}
}
<div id="firstElement">
<h1>This is the 1st element</h1>
</div>
<button onclick="changeFirst()">Change first element</button>

Highlighting text content using the content from an another div

I want to highlight the text content in paragraph using text content from an another div. So there is the "increase overall code" in the the first div. I want that these words from the main paragraph to be highlighted by using the first div. Thank you for the possibility to ask for help here!
function highlight() {
var htext = document.getElementById("torles");
var inputText = document.getElementById("inputText");
var innerHTML = inputText.innerHTML;
var index = innerHTML.indexOf(text);
if (index >= 0) {
innerHTML = innerHTML.substring(0, index) + "<span class='highlight'>" + innerHTML.substring(index, index + text.length) + "</span>" + innerHTML.substring(index + text.length);
innerHTML.innerHTML = innerHTML;
}
}
.highlight {
background-color: red;
}
<html>
<body>
<div class="col-md-10 bordered selectborder fragment" id="torles">increase overall coder
</div>
<button onclick="highlight()">Highlight</button>
<div class="col-md-10 para bordered" id="inputText">
<strong><p>Significantly Reduce Costs and Improve Quality with an Experienced, Professional Global Coding Solution. Health Information Management (HIM) Directors and CFOs are seeking innovative ways to reduce expenses, maintain DNFB goals, and increase overall coder quality.</p></strong>
</div>
</body>
</html>
So, there were a couple things; but first, here's a working example.
function highlight() {
var text = document.getElementById("torles").textContent;//you want the text not the node
var inputText = document.getElementById("inputText");
var innerHTML = inputText.innerHTML;
var index = innerHTML.indexOf(text);
if (index >= 0) {
innerHTML = innerHTML.substring(0, index) + "<span class='highlight'>" + innerHTML.substring(index, index + text.length) + "</span>" + innerHTML.substring(index + text.length);
inputText.innerHTML = innerHTML;//this line was incorrect
}
}
.highlight {
background-color: red;
}
<html>
<body>
<div class="col-md-10 bordered selectborder fragment" id="torles">increase overall coder</div><!-- make sure there's no line break after "coder"-->
<button onclick="highlight()">Highlight</button>
<div class="col-md-10 para bordered" id="inputText">
<strong><p>Significantly Reduce Costs and Improve Quality with an Experienced, Professional Global Coding Solution. Health Information Management (HIM) Directors and CFOs are seeking innovative ways to reduce expenses, maintain DNFB goals, and increase overall coder quality.</p></strong>
</div>
</body>
</html>
Anyway, there were three main things (and a typo). Firstly, you had a line break in your HTML after increase overall coder, and so it would try to find that string with the line break in the text, so it would just not find it.
Second, you mixed up what your variables actually mean; to start off, the text variable (which you misspelled as htext) was a node, not a string. Also, you tried to set the innerHTML of innerHTML, but your variable innerHTML was just a string. You want to set the innerHTML of the node (inputText in this case).

JavaScript Display Image and Text Rather than Alert Message

I'm a newbie and starting to learn coding. I have a question regarding the famous "How many fingers am I holding up?" project. So instead of an alert message, I want the actual image of a finger with 1-5 and the message of either it is correct or not.
I think there are jquery codes.. but i don't want to jump to jquery and learn hardcore javascript first. I'm stuck with creating image Arrays and cannot manage to make the image come up.
Here's the code I have:
<body>
<p>How many fingers am I holding up?</p>
<p><input type="text" id="guess"> <button id="checkGuess">Guess!</button></p>
<div id="image"></div>
<div id="text"></div>
<script type="text/javascript">
var imgArray = new Array();
imgArray[1] = new Image();
imgArray[1].src="images/1.png";
imgArray[2] = new Image();
imgArray[2].src="images/2.png";
imgArray[3] = new Image();
imgArray[3].src="images/3.png";
imgArray[4] = new Image();
imgArray[4].src="images/4.png";
imgArray[5] = new Image();
imgArray[5].src="images/5.png";
document.getElementById("checkGuess").onclick = function() {
var randomNumber = Math.random();
randomNumber = randomNumber * 6;
randomNumber = Math.floor(randomNumber);
if (document.getElementById("guess").value == randomNumber) {
doument.getElementById("image").innerHTML = imgArray[num] + alert("Well done! You got it!");
} else {
alert("Nope! The number was " + randomNumber);
}
}
</script>
</body>
Thanks Guys! Appreciate your help!
Cheers!
Char
I think you can do something like this fiddle.
https://jsfiddle.net/6a4p2po4/5/
What I did was to make the imgArray an array of src of images, and updated the img src depending on the result.
I noticed while working you have some typos and unset variables.
For example, "doument" is misspelled, and "'num'" is not set.
doument.getElementById("image").innerHTML = imgArray[num] + alert("Well done! You got it!");
It might help to use Chrome or another browser to check the console (F12). It will definitely help you debug.
Using console.log() instead of alert() will make it show up as a log instead of a pop up window, so you can check the values that you stored on variables, i.e. console.log(randomNumber);
You're on the right track! Good job so far!
You said
So instead of an alert message, I want the actual image of a finger...
which leads me to think that we never want to call alert() and instead want to display an image and a message. Assuming I am correct in my supposition, here is some code...
<html>
<head>
<!-- some other stuff... -->
<!-- CSS is your friend! -->
<style>
.hidden {
display: none;
}
</style>
</head>
<body>
<p>How many fingers am I holding up?</p>
<p>
<input type="text" id="guess">
<button id="checkGuess" onclick="checkGuess()">Guess!</button>
</p>
<div id="image">
<!-- We can put the images in here then just hide/show them, which is much easier! -->
<img class="hidden" src="./images/1.png"/>
<img class="hidden" src="./images/2.png"/>
<img class="hidden" src="./images/3.png"/>
<img class="hidden" src="./images/4.png"/>
<img class="hidden" src="./images/5.png"/>
</div>
<div id="text"></div>
<script>
function checkGuess(){
var actualFingerCount = Math.floor(Math.random() * (5 - 1 + 1)) + 1;
//the `+` casts the value into a number
var userGuess = +document.getElementById('guess').value;
//get all of our images
var images = document.querySelectorAll('img');
//hide all of them just to be safe
images.forEach(function(img){
img.classList.add('hidden');
});
//then show the one we want
images[actualFingerCount - 1].classList.remove('hidden');
var textDiv = document.getElementById('text');
if(actualFingerCount === userGuess) {
textDiv.innerHTML = 'Yay, you got it!';
}
else {
textDiv.innerHTML = 'Whoops, try again! The number was ' + actualFingerCount + '.';
}
}
</script>
</body>
</html>
And there you have it!
Notice that this is a contrived example. In the real world, you should never define functions in the global namespace, nor should you rely on elements being in a certain order, like I did with the images. Maybe you can take it and improve it to follow better coding standards!

Increment text in HTML

I am trying to perform this pseudo-code, but can't seem to succeed with my limited knowledge of javascript/jquery..
for i = 0; i < 60; i++
{
<p>This is person *i*</p>}
This will then create 60 HTML lines saying This person is... and its respective number.
I have made a program in VB.NET writing out this code for me, but it makes the HTML document very large.
Is it possible to have these lines displayed without the really written in the file?
In JavaScript you would want to do something like:
for( i = 0; i < 60; i++) {
document.write("<p>This is person "+i+"</p>");
}
Note that you want do call this while the page is loading (place the <script> in where you would want these elements to be), document.write will clear the DOM if it already finished loading. Otherwise you would add this into some container like so:
for( i = 0; i < 60; i++) {
document.getElementById("myContainer").innerHTML += "<p>This is person "+i+"</p>";
}
This should look like this in Html/javascript:
<script>
for(i = 0; i < 60; i++){
document.write("<p>This is person "+i+"</p>");
}
</script>
You can also use jquery:
<script type="text/javascript">
$(function() {
var contents = [];
for (var i=0;i<600;i++) {
contents.push("This is person " + i);
}
$("#content").html(contents.join("<br/>"))
});
<body>
<div id="content">
</div>
</body>
My suggestion would be to use a data binding library like AngularJS. This will greatly reduce the amount of HTML & Javascript you have to write.
JS
var app = angular.module('app', []);
app.controller('Main', ['$scope', function($scope){
$scope.numOfP = [1,2,3];
}]);
HTML
<div ng-app="app">
<div ng-controller="Main">
<p ng-repeat="p in numOfP track by $index">This is person {{ $index }}</p>
</div>
</div>
This will repeat your block of HTML for the give number of array elements in numOfP.
FIDDLE

how to concatenate text with image in a variable

Hello first i am basic to java script i have a some on mouse over divs which every one
contains information along images. the problem is that i want to combine text with an image
inside a variable whenever i am mouse hovering each divs so the information along the image
should change as i did program for every one of them
the problem is that how to combine the text and image inside a variable
but i don't know how to do that here is the code:
<script type="text/javascript">
function ENGshowElements(){
var Engineering = "Your In Engineering Section <br> <img src='a.jpg'>";
document.getElementById("contents").innerHTML = Engineering;
}
function CONshowElements(){
var Construction = "Your In Construction Section";
document.getElementById("contents").innerHTML = Construction;
}
function LLCshowElements(){
var LLCDubia = "Your In LLC Dubia Section";
document.getElementById("contents").innerHTML = LLCDubia;
}
function WASshowElements(){
var WasteManagement = "Your In Waste Management Section";
document.getElementById("contents").innerHTML = WasteManagement;
}
function TRAshowElements(){
var Transportation = "Your In Transportation Section";
document.getElementById("contents").innerHTML = Transportation;
}
function LOGshowElements(){
var Logistics = "Your In Logistics Section";
document.getElementById("contents").innerHTML = Logistics;
}
</script>
<div class="firstbox" id="Engineering" onmouseover="ENGshowElements(); return false; " >Engineering</div>
<div class="secbox" id="Construction" onmouseover="CONshowElements(); return false; ">Construction</div>
<div class="thirdbox" id="LLCDubia" onmouseover="LLCshowElements(); return false; " >LLC Dubia</div>
<div class="fourthbox" id="WasteManagement" onmouseover="WASshowElements(); return false; " >Waste Management</div>
<div class="fivthbox" id="Transportation" onmouseover="TRAshowElements(); return false; " >Transportations</div>
<div class="sixthbox" id="Logistics" onmouseover="LOGshowElements(); return false; " >Logistics</div>
DEMO: jsFiddle
HTML:
<div class="firstbox" id="Engineering">Engineering</div>
<div class="secbox" id="Construction">Construction</div>
<div class="thirdbox" id="LLCDubia">LLC Dubia</div>
<div class="fourthbox" id="WasteManagement">Waste Management</div>
<div class="fivthbox" id="Transportation">Transportations</div>
<div class="sixthbox" id="Logistics">Logistics</div>
<div id="contents"></div>
JS:
document.getElementById('Engineering').onmouseover = ENGshowElements;
document.getElementById('Construction').onmouseover = CONshowElements;
document.getElementById('LLCDubia').onmouseover = LLCshowElements;
document.getElementById('WasteManagement').onmouseover = WASshowElements;
document.getElementById('Transportation').onmouseover = TRAshowElements;
document.getElementById('Logistics').onmouseover = LOGshowElements;
function ENGshowElements() {
var Engineering = "Your In Engineering Section <br> <img src='a.jpg'>";
document.getElementById("contents").innerHTML = Engineering;
}
function CONshowElements() {
var Construction = "Your In Construction Section";
document.getElementById("contents").innerHTML = Construction;
}
function LLCshowElements() {
var LLCDubia = "Your In LLC Dubia Section";
document.getElementById("contents").innerHTML = LLCDubia;
}
function WASshowElements() {
var WasteManagement = "Your In Waste Management Section";
document.getElementById("contents").innerHTML = WasteManagement;
}
function TRAshowElements() {
var Transportation = "Your In Transportation Section";
document.getElementById("contents").innerHTML = Transportation;
}
function LOGshowElements() {
var Logistics = "Your In Logistics Section";
document.getElementById("contents").innerHTML = Logistics;
}
=> jsfiddle http://jsfiddle.net/Gy5rH/
just for the sake of making things clear, and pointing out that you're probably going the wrong way, here is a better alternative. It could probably be done mostly using css but here's something more easier to maintain.
Instead of using multiple triggers, We will use only one click function on every button. Each button will have a "data-target" which is the id of an other element.
Our markup will look like this:
<html>
<head>
<style>
#source { display: none; }
</style>
<script>
// Our click event
function clickEvent (ev) {
// Get the target in the dom
// While checking more about event should be good because
// Target may not be the element you're looking for in some cases.
var target = ev.target.dataset['target'];
var obj = document.getElementById(target);
// change the content with the one found
document.getElementById('content').innerHTML = obj.innerHTML;
}
function loaded() {
var docs = document.getElementsByClassName("btn");
// Transform to array
docs = Array.prototype.slice.call(docs);
docs.forEach(function(elem) {
// Assign click event to all elements
elem.onclick = clickEvent;
});
}
</script>
</head>
<body onload="loaded()">
<div>
<button class="btn" data-target="Engineering-Source">Engineering</button>
...
</div>
<div id="content"></div>
<div id="source">
<div id="Engineering-Source">
Your In Engineering Section <br> <img src='a.jpg'>
</div>
...more after
</div>
</body>
</html>
I added comments, but it's a nice way to do. Avoiding "vanillajs" might not be a bad thing but. It can be done without much pain in vanillajs.
That said, here are some reasons why it's good. The content remains in the html instead of javascript. If a web spider will download your page, there are far more chances that it will look for html content instead of text in javascript source.
In my example, some things might not exists in old browser like "dataset" and "forEach".
Note
That said, a pure "css" way of doing this is possible but might make the structure of the document harder to edit. On the other hand, there are ways to mix css and js to keep a minimum of js and as much as possible html/css to keep the styles in line.
Anyway, my example above should be working in some browsers to give an idea how to do it. I recommend using libraries like jQuery or prototype if you're not familiar with Javascript yet. The code above shouldn't definitely end up in production.

Categories