How to add table when pressing a button - javascript

I am trying to make some kind of calendar where I can enter some tasks I already have the design template but I want to be able to add a new table (day) when I press a button.
In the image above you can see what I want to do.
This is the template I am using:
HTML
<tr>
<th>
<div class="dls">
<div class="select">
<select name="dls" id="dls">
<option value="1" selected="selected">Monday</option> <option value="2">Tuesday</option> <option value="3">Wednesday</option> <option value="4">Thursday</option> <option value="5">Friday</option> <option value="6">Saturday</option> <option value="7">Sunday</option>
</select>
</div>
</div>
</th>
</tr>
<tr>
<td>
<input type="text" name="publisher" form="pubName">
<input type="text" name="publisher" form="pubName">
<input type="text" name="publisher" form="pubName">
<input type="text" name="publisher" form="pubName">
</td>
</tr>
CSS
body { font-size: 13px; }
.dls { font-size: 13px; text-align: center; background: transparent; border: none; border-radius: 6px; overflow: hidden; position: relative; }
.dls .select{ height: 22px; width: 125px; background-position: center; text-align: center; }
.dls .select select{ background: transparent; line-height: 1; border: 0; padding: 0; border-radius: 0; width: 125px; height: 22px; position: relative; z-index: 10; font-size: 13px; color: #ffffff; }
table th { text-align: center; background-color: #006fc4; border: 1px solid #006fc4; color: #fff; width: 128px; height: 22px; }
table td { text-align: center; border: 1px solid #006fc4; padding: 2px 2px; width: 128px; height: 22px; }
ul { list-style-type: none; } input { text-align: center; width: 125px; height: 22px; font-size: 13px; }

As someone commented on your post, try and go through some tutorials about DOM Manipulation, but since he told you were to learn it, I'll give you the code to do this, and you can learn the rest later.
The easiest method to do what you want is just to insert a HTML tag in the code.
The first thing you should go ahead and do is make a variable with the div you need to insert/copy
var div = "<option value='1' selected='selected'>Monday</option>"
Now you have to insert the div somewhere.
document.getElementById("dls").innerHTML += div;
The code above inserts the HTML code you placed in the variable "div" into the element with the id of "dls".
Now obviously you don't just want to insert a bunch of divs with the text "Monday" and value="1"
So were going to make this more customizable...
First make we'll be making a function:
function insertNew(value, day) {
}
Now you have a function named insertNew() with two arguments, named value and day, so you can change it to insertNew(2, "Tuesday") but right now it does nothing no matter what, so we'll add a bit of code to the function.
First we'll be making a let variable in the function, so delete the original "div" variable, the difference between "var" and "let" is let only exists in that function and will be deleted after the function is done, it has a few more attributes but that's all you gotta worry about right now, but to be able to make the function easier to use we'll be making it more automatic.
function insertNew(value, day) {
let div = "<option value='" + value + "' selected='selected'>" + day + "</option>";
return div; // Return only spits the value out to the console, much like console.log(), but return stops the function from doing anymore code.
}
Now if you were to do insertNew(3, "Wednesday"), you'd get
<option value='3' selected='selected'>Wednesday</option>
So now you can then make it insert the code as well.
function insertNew(value, day) {
let div = "<option value='" + value + "' selected='selected'>" + day + "</option>";
document.getElementById("dls").innerHTML += div;
}
And it would insert with the right content, but to make the number automatically be filled out, you will have to create a variable outside the function, then every time the function has run increase the value of that function, and when you run the function instead of typing a number into the "value" argument of the function, simply type the name of the variable that counts up.
var number = 1;
function insertNew(value, day) {
number++; // ++ just simply adds one to the integer much like number = number + 1, they do the same.
let div = "<option value='" + value + "' selected='selected'>" + day + "</option>";
document.getElementById("dls").innerHTML += div;
}
Now when you wanna run the function just run insertNew(number, "Tuesday") and every time you run it, the number will be increased by one, and if you really wanted to automate it, you could also add all the names of the days to an array and then cycle through it, and therefore only have to execute the function and not worry about changing anything...
Hope this helps!
EDIT: I noticed the script was inserting the wrong divs compared to what you wanted, but the code is adaptable just by changing the HTML in the variables, you can easily fix it!

Related

How to update the actual true value="" of a input field when another field is entered

I have reviewed tonnes of articles and all solutions only update the visually displayed value as opposed to the actual value within the input tag itself.
When I click on a button a modal appears with a text input to enter a code. We will call it input1
Upon entering the code and exiting the modal the button updates to the code entered and a hidden input value gets updated as well. However the actual tags value="" remains the same.
I have tried numerous ways but all seem to only update the visual and not the true value.
Here is what I have so far but it only updates the value you see in the browser not within the tag itself.
let promoModal = document.getElementById("promoModal");
let promoBtn = document.getElementById("promo");
let promoSpan = document.getElementsByClassName("promoClose")[0];
promoBtn.onclick = function() {
promoModal.style.display = "block";
}
promoSpan.onclick = function() {
promoModal.style.display = "none";
}
window.onclick = function(event) {
if (event.target == promoModal) {
promoModal.style.display = "none";
}
}
function updatePromo() {
let promoValue = document.getElementById("promo-value");
let producePromo = document.getElementById("promo");
let copyPromo = document.getElementById("promo-value-copy");
producePromo.innerHTML = promoValue.value;
copyPromo.innerHTML = promoValue.value;
}
/* THE MODAL */
.modal {
display: none;
position: fixed;
z-index: 1;
padding-top: 100px;
left: 0;
top: 0;
width: 100%;
height: 100%;
overflow: auto;
.modal-content {
background-color: #fefefe;
margin: auto;
padding: 5px 20px;
border: 1px solid #888;
width: 280px;
position: relative;
}
}
/* The Close Button */
.adultClose,
.promoClose {
color: #aaaaaa;
position: absolute;
right: 5px;
top: 0px;
font-size: 22px;
font-weight: bold;
cursor: pointer;
}
.close:hover,
.close:focus {
color: #000;
text-decoration: none;
cursor: pointer;
}
<button id="promo" type="button" class="promo">
<span class="promoCode">Promo Code +</span>
</button>
<input type="hidden" id="promo-value-copy" value="test">
<!-- Promo Modal -->
<div id="promoModal" class="modal">
<div class="modal-content">
<span class="promoClose">×</span>
<input type="text" class="promo-value" id="promo-value" value="" placeholder="Promotional code" onchange="updatePromo()">
</div>
</div>
I stripped the styling to get to the meat and potatoes.
How can I update the actual value="test" to the new value using javascript?
The innerHTML is used for changing HTML content, so for instance you can use it for changing the content of a paragraph <p id="text-to-change"></p>.
To change the input value you can use the .value property of the object.
Try to change the following line copyPromo.innerHTML = promoValue.value; with copyPromo.value = promoValue.value;
You need to change the value like this:
document.getElementById("promo-value-copy").value = promoValue.value;
so going with Barmar's suggestion I was able to update my updatePromo function to both produce the value as well as update the DOM value.
Here is the updated function. I hope it helps the community.
function updatePromo() {
let promoValue = document.getElementById("promo-value");
let producePromo = document.getElementById("promo");
let copyPromo = document.getElementById("promo-value-copy");
producePromo.innerHTML = promoValue.value;
copyPromo.innerHTML = promoValue.value;
copyPromo.setAttribute("value", promoValue.value); // suggestion given by Barmar
}
I had to leave the other element as it adds the text after the form field which is actually needed for this project however typically would not be needed.

Format currency input field with dollar sign & commas

I have a revenue input field in a javascript/jquery form:
Need a dollar sign :before
add commas as the currency increases
I have a dollar sign showing via css, but issues centering it and ensuring the field entry point is next to it without overlapping. Unsure how to do the commas. Any suggestions or tips are welcome!
HTML:
<form id="rev-calculator">
<label for="price">Monthly Revenue</label>
<div class="fields">
<input type="number" name="price" id="price" min="0" max="10000000000" required data-type="number"> </input>
<br>
</form>
CSS:
<style>
.body {
text-align: left;
}
.fields {
margin: 0 10px 0 0;
}
.fields:before {
content: "$";
text-align: center;
position: relative;
left:30px;
}
#price {
border-radius: 5px;
margin: 15px;
padding: 10px;
color: black;
}
</style>
JS:
<script>
$('#rev-calculator').on('click', 'button', function(e) {
e.preventDefault();
var price = $("#price").val();
console.log(price);
})
</script>
codepen: https://codepen.io/kedarPE/pen/JjroYyb
input field
Well here's a way, though in truth not as simple as I hoped when I started down this path. You can use Intl.NumberFormat to get the comma in there (according to locale). To accomodate decimals, I sniff for them in the beginning and append them to the result.
To allow for the comma, I made this a text field with a pattern attribute. Also, I adjusted your CSS to make it a little nicer looking with the $
$('#price').keydown(function(e) {
setTimeout(() => {
let parts = $(this).val().split(".");
let v = parts[0].replace(/\D/g, ""),
dec = parts[1]
let calc_num = Number((dec !== undefined ? v + "." + dec : v));
// use this for numeric calculations
// console.log('number for calculations: ', calc_num);
let n = new Intl.NumberFormat('en-EN').format(v);
n = dec !== undefined ? n + "." + dec : n;
$(this).val(n);
})
})
.body {
text-align: left;
}
.fields {
margin: 0 10px 0 0;
}
.fields:before {
content: "$";
text-align: center;
position: relative;
left: 35px;
}
#price {
border-radius: 5px;
margin: 15px;
padding: 10px 10px 10px 20px;
color: black;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<form id="rev-calculator">
<label for="price">Monthly Revenue</label>
<div class="fields">
<input type="text" pattern="[0-9.,]+" name="price" id="price" required data-type="number" />
<br>
</form>
I'm surprised the unique answer for this issue has a lot of votes because it has a tiny but major flaw: the event shouldn't be keydown, it should be keyup. If you use keydown, it won't read the keys you are pressing at the moment but the previous one. So, please update your answer.

AppendTo but each new append is unique but still uses the same jquery

I'm wondering if it's possible to on each appendTo make the new div unique but still use the same jquery.
As you can see in the mark-up below, each new div shares the same jquery so doesn't work independently.
Within my Javascript i'm selecting the ID to fire each function.
I've tried just adding + 1 etc to the end of each ID, but with that it changes the name of the ID making the new created DIV not function.
I've thought of using DataAttribues, but i'd still have the same issue having to create multiple functions all doing the same job.
Any ideas?
Thanks
$(function() {
var test = $('#p_test');
var i = $('#p_test .upl_drop').length + 1;
$('#addtest').on('click', function() {
$('<div class="file-input"><div class="input-file-container upl_drop"><label for="p_test" class="input-file-trigger">Select a file...<input type="file" id="p_test" name="p_test_' + i + '" value=""class="input-file"></label></div><span class="remtest">Remove</span><p class="file-return"></p></div>').appendTo(test);
i++;
});
$('body').on('click', '.remtest', function(e) {
if (i > 2) {
$(this).closest('.file-input').remove();
i--;
}
});
});
var input = document.getElementById( 'file-upload' );
var infoArea = document.getElementById( 'file-upload-filename' );
input.addEventListener( 'change', showFileName );
function showFileName( event ) {
// the change event gives us the input it occurred in
var input = event.srcElement;
// the input has an array of files in the `files` property, each one has a name that you can use. We're just using the name here.
var fileName = input.files[0].name;
// use fileName however fits your app best, i.e. add it into a div
textContent = 'File name: ' + fileName;
$("#input-file-trigger").text(function () {
return $(this).text().replace("Select a file...", textContent);
});
}
/*
#### Drag & Drop Box ####
*/
.p_test{
display: inline-block;
}
.upl_drop{
border: 2px dashed #000;
margin: 0px 0px 15px 0px;
}
.btn--add p{
cursor: pointer;
}
.input-file-container {
position: relative;
width: auto;
}
.input-file-trigger {
display: block;
padding: 14px 45px;
background: #ffffff;
color: #1899cd;
font-size: 1em;
cursor: pointer;
}
.input-file {
position: absolute;
top: 0; left: 0;
width: 225px;
opacity: 0;
padding: 14px 0;
cursor: pointer;
}
.input-file:hover + .input-file-trigger,
.input-file:focus + .input-file-trigger,
.input-file-trigger:hover,
.input-file-trigger:focus {
background: #1899cd;
color: #ffffff;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<div class="p_test" id="p_test">
<div class="file-input">
<div class="input-file-container upl_drop">
<input class="input-file" id="file-upload" type="file">
<label tabindex="0" for="file-upload" id="input-file-trigger" class="input-file-trigger">Select a file...</label>
</div>
<div id="file-upload-filename"></div>
</div>
<button class="btn--add" id="addtest">
Add
</button>
</div>
I'd advise against using incremental id attributes. They become a pain to maintain and also make the logic much more complicated than it needs to be.
The better alternative is to use common classes along with DOM traversal to relate the elements to each other, based on the one which raised any given event.
In your case, you can use closest() to get the parent .file-input container, then find() any element within that by its class. Something like this:
$(function() {
var $test = $('#p_test');
$('#addtest').on('click', function() {
var $lastGroup = $test.find('.file-input:last');
var $clone = $lastGroup.clone();
$clone.find('.input-file-trigger').text('Select a file...');
$clone.insertAfter($lastGroup);
});
$test.on('click', '.remtest', function(e) {
if ($('.file-input').length > 1)
$(this).closest('.file-input').remove();
}).on('change', '.input-file', function(e) {
if (!this.files)
return;
var $container = $(this).closest('.file-input');
$container.find(".input-file-trigger").text('File name: ' + this.files[0].name);
});
});
.p_test {
display: inline-block;
}
.upl_drop {
border: 2px dashed #000;
margin: 0px 0px 15px 0px;
}
.btn--add p {
cursor: pointer;
}
.input-file-container {
position: relative;
width: auto;
}
.input-file-trigger {
display: block;
padding: 14px 45px;
background: #ffffff;
color: #1899cd;
font-size: 1em;
cursor: pointer;
}
.input-file {
position: absolute;
top: 0;
left: 0;
width: 225px;
opacity: 0;
padding: 14px 0;
cursor: pointer;
}
.input-file:hover+.input-file-trigger,
.input-file:focus+.input-file-trigger,
.input-file-trigger:hover,
.input-file-trigger:focus {
background: #1899cd;
color: #ffffff;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<div class="p_test" id="p_test">
<div class="file-input">
<div class="input-file-container upl_drop">
<input class="input-file" type="file">
<label tabindex="0" for="file-upload" class="input-file-trigger">Select a file...</label>
</div>
<div class="file-upload-filename"></div>
</div>
<button class="btn--add" id="addtest">Add</button>
</div>
Note that I've made a couple of other optimisations to the code. Firstly it now makes a clone() of the last available .file-input container when the Add button is clicked. This is preferred over writing the HTML in the JS file as it keeps the two completely separate. For example, if you need to update the UI, you don't need to worry about updating the JS now, as long as the classes remain the same.
Also note that you were originally mixing plain JS and jQuery event handlers. It's best to use one or the other. As you've already included jQuery in the page, I used that as it makes the code easier to write and more succinct.
Finally, note that you didn't need to provide a function to text() as you're completely over-writing the existing value. Just providing the new string is fine.

My div won't change width with my javascript function

I have made a makeshift progress bar with two divs, styled with css to fit one in another to make the progress bar. I have a button that changes the width of the inside div to go up when I click the button, but the button click does not change the width of the div. I made sure I made no errors, the javascript console in my chrome browser gives no errors when I click the button. Anyways, here is my code:
function clickMe() {
var newExp = parseInt(document.getElementById("expHold").innerHTML);
document.getElementById("bar2").style.width = newExp + 'px';
document.getElementById("expHold").innerHTML += '+1';
document.getElementById("expHold").innerHTML = eval(document.getElementById("expHold").innerHTML);
}
#bar1 {
border: 2px solid gold;
height: 15px;
width: 100px;
background-color: blue;
border-radius: 8px;
}
#bar2 {
height: 15px;
width: 1px;
background-color: skyblue;
border-radius: 8px;
}
<div id="bar1">
<div id="bar2">
</div>
</div>
<p>
<input type="button" value="Click me" onClick="clickMe()" />
<span id="expHold" style="color:black;">1</span>
I would appreciate any help telling me what I am doing wrong, thanks!
Please do not use inline JavaScript. It reduces readability and maintainability.
You should use a JavaScript variable to store the exp, this way you don't have to repeatedly query the DOM, which is process intensive.
You should cache the DOM objects instead of creating new ones on each iteration.
You can increment the previously created exp variable by using the prefix increment modifier
The prefix increment modifier will return the incremented value.
The postfix increment modifier will return the value before incrementing.
var exp = 0, current;
var bar1 = document.getElementById("bar1");
var bar2 = document.getElementById("bar2");
var hold = document.getElementById("expHold");
var max = bar1.clientWidth;
document.getElementById('my-button').onclick = function() {
// Don't go past the end.
if(bar2.clientWidth < max) {
current = ++exp;
hold.textContent = current;
bar2.style.width = current + 'px';
}
}
#bar1 {
border: 2px solid gold;
height: 15px;
width: 100px;
background-color: blue;
border-radius: 8px;
}
#bar2 {
height: 15px;
width: 0px;
background-color: skyblue;
border-radius: 8px;
}
<div id="bar1">
<div id="bar2">
</div>
</div>
<p>
<input type="button" value="Click me" id="my-button" />
<span id="expHold" style="color:black;">0</span>

Javascript if slider value = 20 , display text

I made a slider using html and CSS which displays its value on change. I styled it using CSS using the <style> tag. I then went on to making the value display text. I want to display "Starter" when the slider hits 20.
I don't know what I am doing wrong and why this isn't working for me. I would like to use the most user-friendly version of this. If possible, please explain what I did wrong.
<html>
<style>
input[type="range"] {
-webkit-appearance: none;
width: 100%;
height: 25px;
border: 1px solid;
background-color: #0066FF;
}
input[type="range"]::-webkit-slider-thumb{
-webkit-appearance: none;
width: 25px;
height: 25px;
border: 1px solid;
background-color: #FFF;
}
</style>
</html>
<form oninput="amount.value=rangeInput.value">
<input type="range" id="rangeInput" name="rangeInput" step="20" value="0">
<div align="center" style="font-size:25px;"><output name="amount" for="rangeInput">0</output></div>
</form>
<script type="text/javascript">
var rangeInput = document.getElementById("rangeInput").value
if(rangeInput = 20){
text = "starter"
}
How can i get my slider to RESET on value 0?
at the moment, if i go from 20 to 0, it stays displaying Starter , i would like it to remove that. Is this possible?
you need '==' instead of '=' with your if statement
var rangeInput = document.getElementById("rangeInput").value
if(rangeInput == 20){
text = "starter"
}
See this question, as well: Range Slider Event Handler Javascript
You're going to want to look into event listeners-- you want to have a listener bound to the slider so that when the user changes the value, your code can respond accordingly.
You need to listen for onchange event. Also, you need to use == instead of = to compare values. The following code should work -
function updateValue() {
var rangeInput = document.getElementById("rangeInput").value
if (rangeInput == 20) {
document.getElementById("text").innerHTML = 'starter'
} else {
document.getElementById("text").innerHTML = ''
}
}
input[type="range"] {
-webkit-appearance: none;
width: 100%;
height: 25px;
border: 1px solid;
background-color: #0066FF;
}
input[type="range"]::-webkit-slider-thumb {
-webkit-appearance: none;
width: 25px;
height: 25px;
border: 1px solid;
background-color: #FFF;
}
<form oninput="amount.value=rangeInput.value">
<input type="range" id="rangeInput" name="rangeInput" step="20" value="0" onchange="updateValue()">
<div align="center" style="font-size:25px;">
<output name="amount" for="rangeInput">0</output>
</div>
</form>
<div id="text"></div>

Categories

Resources