Generate text depends on another textbox value - javascript

I want to generate target textbox value depends on another textbox value with following conditions -
Assumed First TextBox value - "myfile name"
If first textbox value not start with "Copy of " then target value will "Copy of [1] myfile name".
If first textbox value "Copy of [1] myfile name" then target value will "Copy of [2] myfile name".
If first textbox value "Copy of [2] myfile name" then target value will "Copy of [3] myfile name".
i.e increment of the no.
Here is my code sample
How do I do this using jquery?
HTML:
<div class="panel">
<input type="text" id="filename" value="filename">
</div>
<div class="panel">
<input type="text" id="newfilename" value="">
</div>
<div class="panel">
<button type="button" id="btnGenerate">
Get File Name
</button>
</div>
JS:
$('#btnGenerate').click(function(){
var newname;
var oldname = $('#filename').val();
if(typeof oldname !== undefined || oldname != ''){
if(oldname.indexOf('Copy of')){
var nCount = parseInt(oldname.match(/\([.*]\)/),10) + 1;
newname = "Copy of [" + nCount[1] + "] " + oldname;
$('#newfilename').val(newname);
}else{
newname = "Copy of [1] " + oldname'
}
$('#newfilename').val(newname);
}
});

Updated fiddle.
You're so close, you've just to adjust the regex a little bitand add else statement :
$('#btnGenerate').click(function(){
var oldname = $('#filename').val();
if(typeof oldname !== undefined || oldname != ''){
//Adding '>-1' in this condition
if(oldname.indexOf('Copy of')>-1)
{
var nCount = parseInt(oldname.match(/\[(.*)\]/)[1],10) + 1;
var file_name = oldname.split('] ')[1];
var newname = "Copy of [" + nCount + "] " + file_name;
}else{
var newname = 'Copy of [1] '+oldname;
}
$('#newfilename').val(newname);
}
});
Hope this helps.
$('#btnGenerate').click(function(){
var oldname = $('#filename').val();
if(typeof oldname !== undefined || oldname != ''){
if(oldname.indexOf('Copy of')>-1){
var nCount = parseInt(oldname.match(/\[(.*)\]/)[1],10) + 1;
var file_name = oldname.split('] ')[1];
var newname = "Copy of [" + nCount + "] " + file_name;
}else{
var newname = 'Copy of [1] '+oldname;
}
$('#newfilename').val(newname);
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="panel">
<input type="text" id="filename" value="Copy of [1] filename">
</div>
<div class="panel">
<input type="text" id="newfilename" value="">
</div>
<div class="panel">
<button type="button" id="btnGenerate">
Get File Name
</button>
</div>

names = new Array()
$('#btnGenerate').click(function(){
var oldname = $('#filename').val();
names.push(oldname);
if(oldname != ''){
var nCount = $.grep(names, function (elem) {
return elem === oldname;
}).length;
var newname = "Copy of [" +nCount + "] " + oldname;
$('#newfilename').val(newname);
}
});
.panel{
display:block;
padding: 5px 10px;
}
.panel input{
width:100%;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="panel">
<input type="text" id="filename" value="Name">
</div>
<div class="panel">
<input type="text" id="newfilename" value="">
</div>
<div class="panel">
<button type="button" id="btnGenerate">
Get File Name
</button>
</div>
I hope this is what you are looking for.

Your code is working, but you have to change the regex from
/\([.*]\)/ to /\d+/

I've made the following adjustments to your code:
if(oldname.substr(0, 7) == "Copy of"){
var nCount = parseInt(oldname.match(/\[(\d+?)\]/)[1],10) + 1;
var newname = oldname.replace(/\[\d+?\]/, "["+nCount+"]");
$('#newfilename').val(newname);
}
else
{
$('#newfilename').val("Copy of [1] " + oldname); //prepend Copy of [1]
}
Look at oldname.substr(0, 7) == "Copy of" the former indexOf skipped the if, not executing the code.
now [(\d+?)\] does the magic. It takes out all numbers between [ and ] and groups them in (). \d+? means get all numbers that occur 1 or n times. ? makes it lazy so it stops at ].
var newname = oldname.replace(/\[\d+?\]/, "["+nCount+"]") simply do a replace on the [] block and replace it with nCount.
You can even optimize it using just a replace:
var newname = oldname.replace(/\[(\d+?)\]/, function(whole, group1){
return "[" + (parseInt(group1, 10)+1) + "]";
});
$('#btnGenerate').click(function(){
var oldname = $('#filename').val();
if(typeof oldname !== undefined || oldname != ''){
if(oldname.substr(0, 7) == "Copy of"){
var newname = oldname.replace(/\[(\d+?)\]/, function(whole, group1){
return "[" + (parseInt(group1, 10)+1) + "]";
});
$('#newfilename').val(newname);
}
else
{
$('#newfilename').val("Copy of [1] " + oldname); //prepend Copy of [1]
}
}
});
.panel{
display:block;
padding: 5px 10px;
}
.panel input{
width:100%;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="panel">
<input type="text" id="filename" value="Copy of [1] filename">
</div>
<div class="panel">
<input type="text" id="newfilename" value="">
</div>
<div class="panel">
<button type="button" id="btnGenerate">
Get File Name
</button>
</div>
On a whole different subject. You are building a filesystem kind of control. Wouldn't it be better that the copy amount is being determined by the amount of occurrences of that file name (and copies)?

Related

Button generated inside javascript code to onclick insert value in input type text in form

I have a very nice SEO-keyword suggestion tool working with CKeditor, it displays the most used word in the text while writing. The problem is that I want to make these generated keywords clickable one by one. So when you click on a keyword, it auto-fills an input-type text.
Here is the HTML code:
<!-- Textarea -->
<div class="form-group">
<label class="col-md-2 control-label" for="editor1">Insert your text here </label>
<div class="col-md-10">
<textarea class="form-control" id="editor1" name="editor1"><p>text example with ahöäåra</p></textarea>
</div>
</div>
<!-- KW density result -->
<div class="form-group">
<label class="col-md-2 control-label" for="editor1">Suggested SEO keywords</label>
<div class="col-md-10">
<div id="KWdensity" ></div>
</div>
</div>
Here is the javascript code:
<script type="text/javascript">
$(document).ready(function() {
CKEDITOR.replace('editor1');
$(initKW);
CKEDITOR.instances.editor1.on('contentDom', function() {
CKEDITOR.instances.editor1.document.on('keyup', function(event) {
$(initKW);
});
});
function KeyDensityShow(srctext, MaxKeyOut, keylenMin) {
var Output;
var words = srctext.toLowerCase().split(/[^\p{L}\p{M}\p{N}]+/u)
var positions = new Array()
var word_counts = new Array()
try {
for (var i = 0; i < words.length; i++) {
var word = words[i]
if (!word || word.length < keylenMin) {
continue
}
if (!positions.hasOwnProperty(word)) {
positions[word] = word_counts.length;
word_counts.push([word, 1]);
} else {
word_counts[positions[word]][1]++;
}}
word_counts.sort(function(a, b) {
return b[1] - a[1]
})
return word_counts.slice(0, MaxKeyOut)
} catch (err) {
return "";
}}
function removeStopWords(input) {
var stopwords = ['test', ];
var filtered = input.split(/\b/).filter(function(v) {
return stopwords.indexOf(v) == -1;
});
stopwords.forEach(function(item) {
var reg = new RegExp('\\W' + item + '\\W', 'gmi');
input = input.replace(reg, " ");
});
return input.toString();
}
function initKW() {
$('#KWdensity').html('');
var TextGrab = CKEDITOR.instances['editor1'].getData();
TextGrab = $(TextGrab).text();
TextGrab = removeStopWords(TextGrab);
TextGrab = TextGrab.replace(/\r?\n|\r/gm, " ").trim();
TextGrab = TextGrab.replace(/\s\s+/g, " ").trim();
if (TextGrab != "") {
var keyCSV = KeyDensityShow(TextGrab, 11, 3);
var KeysArr = keyCSV.toString().split(',');
var item, items = '';
for (var i = 0; i < KeysArr.length; i++) {
item = '';
item = item + '<b>' + KeysArr[i] + "</b></button> ";
i++;
item = '<button class="btn btn-default btn-xs" type="button" onclick="document.getElementById(thebox).value="head of gwyneth paltrow";"><span class="badge">' + KeysArr[i] + "</span> " + item;
items = items + item;
}
$('#KWdensity').html(items);
}}});
</script>
And here is some extra HTML for the input that needs to be auto-filled.
The keywords box:
<input type="text" id="thebox" value="" style="width:80%;height:30px;background:#000;color:#fff;"/>
<br><input type="button" value="this one is working" onclick="document.getElementById('thebox').value='test button is working';">
So if you write something, it will generate keywords buttons. When you click on one of these buttons, the keyword must be entered in the input text like this
keyword,
Here is a Fiddle DEMO.
Any idea how to fix that? I added a document.getElementById('thebox'). but it does not return anything
Your code in
item = '<button class="btn btn-default btn-xs" type="button" onclick="document.getElementById(thebox).value="head of gwyneth paltrow";"><span class="badge">' + KeysArr[i] + "</span> " + item;
Will add to the DOM (in other words, to the HTML of the page), the following bit:
<button
class="btn btn-default btn-xs"
type="button"
onclick="document.getElementById(thebox).value="head of gwyneth paltrow";"
>
Now, the resulting onclick above has some problems. First, notice that the quotes it uses in the string after .value= are actually closing the onclick declaration because they are not escaped. I mean, instead of
onclick="document.getElementById(thebox).value="head of gwyneth paltrow";"
^--- problem here ^--- and here
It should've been
onclick="document.getElementById(thebox).value=\"head of gwyneth paltrow\";"
^--- fixed here ^--- and here
Secondly, the argument to .getElementById(thebox) is thebox. Notice here that the way it is now, thebox is actually a variable, not a string. So instead of the above, what you want is:
onclick="document.getElementById(\"thebox\").value=\"head of gwyneth paltrow\";"
^--- ^--- fixed here
These fixes should be enough to make the clicks on the words set the "head of gwyneth paltrow" value in the textbox.
I believe, though, you want to actually set the key when the button is clicked. To do that, instead of having "head of gwyneth paltrow" after the .value, you should have the text of the key. All in all, here's how that line could be:
item = '<button class="btn btn-default btn-xs" type="button" onclick="document.getElementById(\'thebox\').value=\'' + key + '\';"><span class="badge">' + KeysArr[i] + "</span> " + item;
^-- ^-- ^^^^^^^^^^^^^^--- changed here (notice in the demo below I declare the key variable before using it here)
Updated fiddle here. Running demo below as well.
$(document).ready(function() {
CKEDITOR.replace('editor1');
$(initKW);
CKEDITOR.instances.editor1.on('contentDom', function() {
CKEDITOR.instances.editor1.document.on('keyup', function(event) {
$(initKW);
});
});
function KeyDensityShow(srctext, MaxKeyOut, keylenMin) {
var Output;
var words = srctext.toLowerCase().split(/[^\p{L}\p{M}\p{N}]+/u)
var positions = new Array()
var word_counts = new Array()
try {
for (var i = 0; i < words.length; i++) {
var word = words[i]
if (!word || word.length < keylenMin) {
continue
}
if (!positions.hasOwnProperty(word)) {
positions[word] = word_counts.length;
word_counts.push([word, 1]);
} else {
word_counts[positions[word]][1]++;
}
}
word_counts.sort(function(a, b) {
return b[1] - a[1]
})
return word_counts.slice(0, MaxKeyOut)
} catch (err) {
return "";
}
}
function removeStopWords(input) {
var stopwords = ['test', ];
var filtered = input.split(/\b/).filter(function(v) {
return stopwords.indexOf(v) == -1;
});
stopwords.forEach(function(item) {
var reg = new RegExp('\\W' + item + '\\W', 'gmi');
input = input.replace(reg, " ");
});
return input.toString();
}
function initKW() {
$('#KWdensity').html('');
var TextGrab = CKEDITOR.instances['editor1'].getData();
TextGrab = $(TextGrab).text();
TextGrab = removeStopWords(TextGrab);
TextGrab = TextGrab.replace(/\r?\n|\r/gm, " ").trim();
TextGrab = TextGrab.replace(/\s\s+/g, " ").trim();
if (TextGrab != "") {
var keyCSV = KeyDensityShow(TextGrab, 11, 3);
var KeysArr = keyCSV.toString().split(',');
var item, items = '';
var previousKeys = [];
for (var i = 0; i < KeysArr.length; i++) {
item = '';
var key = KeysArr[i];
previousKeys.push(key);
item = item + '<b>' + key + "</b></button> ";
i++;
item = '<button class="btn btn-default btn-xs" type="button" onclick="document.getElementById(\'thebox\').value=\'' + previousKeys.join(', ') + '\';"><span class="badge">' + KeysArr[i] + "</span> " + item;
items = items + item;
}
$('#KWdensity').html(items);
}
}
});
<script type="text/javascript" src="https://code.jquery.com/jquery-2.2.4.min.js"></script>
<script type="text/javascript" src="//cdn.ckeditor.com/4.6.1/standard/ckeditor.js"></script>
<link rel="stylesheet" type="text/css" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
<script type="text/javascript" src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
<!-- Textarea -->
<div class="form-group">
<label class="col-md-2 control-label" for="editor1">Insert your text here </label>
<div class="col-md-10">
<textarea class="form-control" id="editor1" name="editor1"><p>text example with ahöäåra</p></textarea>
</div>
</div>
<!-- KW density result -->
<div class="form-group">
<label class="col-md-2 control-label" for="editor1">Suggested SEO keywords</label>
<div class="col-md-10">
<div id="KWdensity" ></div>
</div>
</div>
The keywords box: <input type="text" id="thebox" value="" style="width:80%;height:30px;background:#000;color:#fff;"/>
<br><input type="button" value="this one is working" onclick="document.getElementById('thebox').value='test button is working';">

Validate user input with whitespace

How to in real-time format user input? For example, the user puts A9364470240ZGS001 to the input field, and using JavaScript format it in the input field in real-time to be like: A 936 447 02 40 ZGS 001?
<div class="childDumpFile">
<label for="ds">Dataset</label>
<input type="text" class="form-control" id="ds" name="ds" value="{{Request::get('ds') ?? ''}}">
</div>
I found the true answer. These expectations are naming as "input-mask" and if you'd like to use. You have to use 3. party libraries. Some of them listing in following sites:
Libraries 1
Libraries 2
I chose Cleave.js for your question. This is the demo:
<script src="https://nosir.github.io/cleave.js/dist/cleave.min.js"></script>
<script src="https://nosir.github.io/cleave.js/dist/cleave-phone.i18n.js"></script>
<script>
function loadFunction() {
// custom
var cleaveCustom = new Cleave('.input-custom', {
blocks: [1, 3, 3, 2, 2, 3, 3],
delimiter: ' ',
});
}
</script>
<body onload="loadFunction()">
A 936 447 02 40 ZGS 001
<div class="container">
<input class="input-custom" placeholder="Custom delimiter & blocks" />
</div>
</body>
If we suppose users have to write the characters one by one. This will work.
<body>
<input type="text" class="form-control" id="ds" name="ds" onkeypress="keyPress()" maxlength="23">
</body>
<script>
function keyPress() {
var field = document.getElementById("ds");
var text = field.value;
if(text.length == 1 || text.length == 5
|| text.length == 9 || text.length == 12
|| text.length == 15 || text.length == 19 ) {
var newText = text + " ";
field.value = newText;
}
}
</script>
Here is a little example.
<div class="childDumpFile">
<label for="ds">Dataset</label>
<input type="text" class="form-control" id="ds" name="ds">
</div>
<div class="test_ds"></div>
JS with jquery.
$("#ds").change(function(){
var ds_value = $("#ds").val();
var temp = ds_value;
temp = temp.substring(0,1) + " " + temp.substring(1, 4) + " " + temp.substring(4, 7) + " " + temp.substring(7, 9) + " " + temp.substring(9, 11) + " " + temp.substring(11, 14) + " " + temp.substring(14, 17);
$("#ds").val(temp);
$(".test_ds").html(temp);
});
Here is a demo -
https://jsfiddle.net/Kistlak/7bkdtev8
First, you need add onchange="getTimeNow()" oninput="getTimeNow()" in to input
<input type="text" class="form-control" id="ds" name="ds" value="{{Request::get('ds') ?? ''}}" onchange="getTimeNow()" oninput="getTimeNow()">
Finally, you get event input text
<script>function getTimeNow(){console.log(new Date())}</script>

Loading data on the same form page after submitting

I have a tiny problem with this college assignment. When the user inputs their data, an account id number is created. I've worked on that and it works like it should. But here's the problem: after the user clicks the submit button and the account id number is created, what they entered needs to be displayed below it. The assignment says I need to create a function called displayNewAccount and put in into one of the other functions. I put in inside the createEventListeners function. The text needs to be displayed in a custom ID (account) on the HTML page. The data entered into the first name input (fnameinput) should display after "First Name" (fname) and the last name input (lnameinput) should display after "Last Name" (lname) and so on. If the displayNewAccount function has to be moved inside another function then that is totally fine. I've looked online and found several examples, but I couldn't get them to work for me. What am I doing wrong? Thanks for the help.
HTML
<article>
<h2>New Account Information</h2>
<form>
<fieldset id="deliveryinfo">
<label>First Name</label><input type="text" id="fnameinput" name="fname">
<label>Last Name</label><input type="text" id="lnameinput" name="lname">
<label>Street Address</label><input type="text" id="addrinput" name="address">
<label>City</label><input type="text" id="cityinput" name="city">
<label>State</label><input type="text" id="stateinput" name="state">
<label>Zip</label><input type="text" id="zipinput" name="zip">
<label>Account ID</label><input type="text" id="accountidbox" name="accountid">
<input type="button" id="submitBtn" value="Create Account">
</fieldset>
<!-- New section -->
<fieldset>
<div id="account">
<!-- Data is displayed in here. -->
</div>
</fieldset>
</form>
</article>
JavaScript
var newAccountObject = {};
var newAccountSubmission;
function createID() {
var fname = document.getElementById("fnameinput");
var lname = document.getElementById("lnameinput");
var zip = document.getElementById("zipinput");
var account = document.getElementById("accountidbox");
var fields = document.getElementsByTagName("input");
var acctid;
var firstInit;
var lastInit;
if (fname !== "" || lname !== "" || zip !== "") {
firstInit = fname.value.charAt(0).toUpperCase();
lastInit = lname.value.charAt(0).toUpperCase();
acctid = firstInit + lastInit + zip.value;
account.value = acctid;
newAccountObject = {};
for(var i = 0; i < fields.length - 1; i++) {
newAccountObject[fields[i].name] = fields[1].value;
}
}
}
function createString() {
newAccountSubmission = JSON.stringify(newAccountObject);
}
function createEventListeners() {
var fname = document.getElementById("fnameinput");
var lname = document.getElementById("lnameinput");
var zip = document.getElementById("zipinput");
if (fname.addEventListener) {
fname.addEventListener("change", createID, false);
lname.addEventListener("change", createID, false);
zip.addEventListener("change", createID, false);
}
else if (fname.attachEvent) {
fname.attachEvent("onchange", createID);
lname.attachEvent("onchange", createID);
zip.attachEvent("onchange", createID);
}
if (button.addEventListener) {
button.addEventListener("click", createString, false);
}
else if (button.attachEvent) {
button.attachEvent("onclick", createString);
}
// Displays an account summary section when the "Create Account" button is clicked.
function displayNewAccount() {
document.getElementById("account").innerHTML = "First Name: " + fname + "<br>" + "Last Name: " + lname + "<br>" + "Address: " + addrinput + "<br>" + "City: " + cityinput + "<br>" + "State: " + stateinput + "<br>" + "Zip: " + zipinput + "<br>" + "Account ID: " + accountidbox;
}
if (window.addEventListener) {
window.addEventListener("click", displayNewAccount, false);
}
else if (window.attachEvent) {
window.attachEvent("onclick", displayNewAccount);
}
}
if (window.addEventListener) {
window.addEventListener("load", createEventListeners, false);
}
else if (window.attachEvent) {
window.attachEvent("onload", createEventListeners);
}

JQuery: Why am I getting an error?

My fiddle is here: http://jsfiddle.net/6yb7cv5c/
Visit the above fiddle, and you will see in the "result" window (bottom right) that when you click the 3 dots it changes into a textbox, you click out and it changes into text again, but clicking it again to change it into a textbox gives this error:
Uncaught TypeError: Cannot read property 'style' of undefined
which is this line:
$(this).find("span")[0].style.display="none";
The problem is in the static markup(at the beginning) the em element has a span as its child inside which you have the content, but when you edit it you are not putting it back
$(".editINPUT").blur(function () {
$(this)[0].style.display = "none";
if ($(this)[0].value == "") {
$(this).prev()[0].innerHTML = "<span>...</span>";
} else {
$(this).prev().html($('<span />',{text:this.value}))
}
$(this).prev().show();
//var i = $(this)[0].attr("id");
var i = $(this)[0].id;
var ii = $(this)[0].value;
console.log(i + " " + ii + " " + $("#tempData").data("data"));
});
$(document).ready(function() {
$(".editDIV").dblclick(function() {
var $this = $(this),
text = $this.find('span').text();
$("#tempData").data("data", text);
$this.find("span").hide();
$this.find("input").val(text).show().focus();
});
$(".editINPUT").blur(function() {
var $this = $(this),
value = this.value;
$this.hide();
var $span = $('<span />', {
text: value == "" ? '...' : this.value
});
$this.prev().html($span).show();
//var i = $(this)[0].attr("id");
var i = this.id;
var ii = this.value;
console.log(i + " " + ii + " " + $("#tempData").data("data"));
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div class="picFilename editDIV">
<em><span class="editESPAN" style="display:block;">...</span></em>
<input class="editINPUT" style="display:none;" type="text" id="2_1_c" />
</div>
<div class="picFilename editDIV">
<em><span class="editESPAN" style="display:block;">...</span></em>
<input class="editINPUT" style="display:none;" type="text" id="2_2_c" />
</div>
<div class="editDIV">
<span class="editESPAN" style="display:block;">asd</span>
<input class="editINPUT" style="display:none;" type="text" id="asdf1" />
</div>
<div class="editDIV">
<span class="editESPAN" style="display:block;">asd</span>
<input class="editINPUT" style="display:none;" type="text" id="asdf2" />
</div>
<div id="tempData"></div>

Javascript - cart only adds 1 item one even if 2 or 5 the item are buyed

My script is in just HTML and Javascript and I can't find what's wrong. I have a html-page that contains 8 products all with the same html-style. But when I click on product 2 or 8 it always only list the first product on the list. And I can't figure out what I need to do to get it to work. (some text in scripts are in my home language Swedish)
HTML code
<div id="Tama">
<h2>TAMA</h2>
<img src="images/trummor/tama.jpg">
<br/>
<p>TAMA Superstar. </p>
<p>Pris: 25000 kr</p>
<hr style="border: 1px solid #000;">
<form name="order">
<input type="hidden" id="IDnumber" value="004">
<input type="hidden" id="pris" value="25000">
<input type="hidden" id="item" value="Tama Superstar">
Välj antal:
<input type="text" id="antal" value="1" name="antal" onChange="this.value=CKquantity(this.value)" style="width:30px;" maxlength="1"> |
<input type="button" value="Köp" onclick="addElement(this.form);">
</form>
<hr style="border: 1px solid #000;">
<p>
Tillbaka till produkter
</p>
</div>
Javascript Cart File
// -- CHECK IF ANTAL IS A NUMBER -- //
function CKquantity(checkString) {
var strNewQuantity = "";
for ( i = 0; i < checkString.length; i++ ) {
ch = checkString.substring(i, i+1);
if ( (ch >= "0" && ch <= "9") || (ch == '.') )
strNewQuantity += ch;
}
if ( strNewQuantity.length < 1 )
strNewQuantity = "1";
return(strNewQuantity);
}
// -- ADD TO CART -- //
// still problem - only enter the first item on the list either you click on the
second or last product
function addElement(thisForm)
{
var itemId = document.getElementById('IDnumber').value
var itemName = document.getElementById('item').innerHTML;
var antal = document.getElementById('antal').value;
var pris = document.getElementById('pris').value;
var parent = document.getElementById('cart');
var newElement = document.createElement('li');
newElement.setAttribute('class','item');
var sum = antal * pris;
newElement.innerHTML = "("+itemId+") "+ antal + " x " + itemName + " - " + pris + " kr, Totalt: " + sum + " kr";
parent.appendChild(newElement);
}
JavaScript is Case Sensitive scripting language, which means its keywords should be written in the right-case. You should write function instead of FUNCTION.
Try This:
function addElement()
{
var itemName = document.getElementById('item').innerHTML;
var antal = document.getElementById('antal').value; // 'value' not 'VALUE'
var parent = document.getElementById('cart');
var newElement = document.createElement('li');
newElement.setAttribute('class','item');
newElement.innerHTML = antal + " x " + itemName;
parent.appendChild(newElement);
}

Categories