I have a textarea, where the user can write his name.
<h2><textarea name="txt_company" rows="5" id="company_text"></textarea><textarea name="txt_visitor" rows="5" id="visitor_text">
</textarea><textarea name="text_rp" rows="5" id="rp_text">
</textarea></h2>
When pressing the button
<input type="submit" class="wmfg_btn" name="submit_form" id="submit_form_btn" value="Code generieren..." onclick="generatecode();" />
the output with the entered name will be displayed as an alert:
function generatecode() {
var text_company = document.getElementById("text_company").value;
var text_visitor = document.getElementById("text_visitor").value;
var text_rp = document.getElementById("text_rp").value;
alert('Blablabla' + text_company + 'blablabla' + text_visitor + 'blablabla' + text_rp + 'blabla.');
}
Now, my problem is, that if the user puts in for example 2 names with a line break between, my output should be expanded with <br> after each variable.
Like for example:
alert('Blablabla' + text_company + '**ADDITION**blablabla' + text_visitor + 'blablabla' + text_rp + 'blabla.')
But im stuck right now, I cant find a good solution...
Im open for any advice!
you could try to add \n as a line break for the entry.
function generatecode() {
var text_company = document.getElementById("text_company").value + " \n"; // added line break
var text_visitor = document.getElementById("text_visitor").value + " \n"; // added line break
var text_rp = document.getElementById("text_rp").value + " \n"; // added line break
alert('Blablabla' + text_company + 'blablabla' + text_visitor + 'blablabla' + text_rp + 'blabla.');
}
EDIT: Added \n to all "text_' variables
You can use the method indexOf to detect if the value of the textarea contains "\n" and according to the result (-1 if no line break) you can add or not a line break to the value of the textarea.
<textarea name="test" rows="5" id="test"></textarea>
<input type="button" onclick="alertValue()" />
<script>
function alertValue(){
var test = document.getElementById("test").value;
if(test.indexOf("\n") != -1){
test += "\n";
}
}
</script>
In addition, take care of your textearea ids: text_company != company_text.
Related
I want to reverse my line order while keeping the style of words and the order I created.
HTML:
<textarea id="mytext"">
Buy - 3 Potatoes $6.25
Sold - 3 Napkins $7.12
Buy - 5 Fries $11.62
Sold - 7 Potatoes $14.32
</textarea>
<div id = "myresult"></div>
As you can see I did the order of words and style the words I just need to reverse the lines now.
I'm working on notepad++ and still pretty new to Javascript.
Script:
var mytext = document.getElementById('mytext');
var result = document.getElementById('myresult');
var lines = mytext.value.split('<br>');
result.innerHTML = '';
for(let i = 0;i < lines.length;i++){
var line = lines[i];
var list = [];
list.unshift(line);
list.unshift("<br>");
var word = line.split(' ');
var n1 = line.match(/[0-9]+/g);
var n2 = line.match(/[0-9]+\.[0-9]+/g);
var check = line.match(/Buy/);
var check2 = line.match(/Sell/);
if(check) {
result.innerHTML += "<span style='color:green;'>" + word[0] + "</span>" + ' ' + word[2] + ' ' + word[3] + ' total:$' + (n1[0]*[n2]).toFixed(2) + "<br>";
}
else if(check2) {
result.innerHTML += "<span style='color:blue;'>" + word[0] + "</span>" + ' ' + word[2] + ' ' + word[3] + ' total: $' + (n1[0]*[n2]).toFixed(2) + "<br>";
}
else {
result.innerHTMl + " ";
}
}
As you can see I already style the colors and fix the order. I just need to reverse the line and display it in innerHTML.
My idea was to make a array[], and then for every line in the for loop try to unshift the line and br but everytime it give errors sometimes it gives me a bunch of commas, and one time it it displays no colors or give me a bunch of random words.
Result should look like what is after the snippet run. This is what I want innerHTMl after the code is run. The code has to display innerHTMl inside the div please.
<div id="result">
<span style='color:blue;'>Sold</span> 7 Potatoes total: $100.24<br>
<span style='color:green;'>Buy</span> 5 Fries total: $58.1<br>
<span style='color:blue;'>Sold</span> 3 Napkins total: $21.36<br>
<span style='color:green;'>Buy</span> 3 Potatoes total: $18.75<br>
</div>
In continuation of my comment above, you could use js reverse() before anything else on creating new elements.
E.g.
var lines = mytext.value.split("\n").reverse();
I wanna add an if/else statement that prints "Only Number are accepted", for older browsers, where they allow you to add a string in a input with type=number.
var bttn = document.getElementById("agebttn");
bttn.addEventListener("click", bttnClicked);
function calculate(startingYear) {
var dateObj = new Date()
var currentYear = dateObj.getFullYear()
return currentYear - startingYear;
}
function bttnClicked() {
console.log("bttn clicked");
var age = parseInt(document.getElementById('age').value);
var yearsAlive = calculate(age);
var html = "You entered " + age;
html += "<br />You have been alive for " + yearsAlive + " years";
document.getElementById('answer').innerHTML = html;
}
<body>
<h1>Age Calculator</h1>
<input type="number" id="age" placeholder="Enter your birthyear">
<input type="button" id="agebttn" value="Calc" />
<div id="answer">
</div>
</body>
You can check if you were able to parse int or not using isNaN function here:
function bttnClicked() {
console.log("bttn clicked");
var age = parseInt(document.getElementById('age').value);
if(isNaN(age)){
document.getElementById('answer').innerHTML = "<b>Only Numbers Accepted</b>";
return;
}
var yearsAlive = calculate(age);
var html = "You entered " + age;
html += "<br />You have been alive for " + yearsAlive + " years";
document.getElementById('answer').innerHTML = html;
}
CMIIW
from what i see , you want to print that result from your script logic into your
div tag with ID = answer right? and you want to get only number input?
you would want to use !isNan(age) function to validate your input so when they validate and got not a number input , it will throw you back error message on your else condition
Trying to get this string I have in JavaScript to appear in a paragraph in my HTML page by mousing over another paragraph.
function showInfo()
{
for (i = 0; i < object2; i = i + 1)
{
var myParagraph = "Name of Business: " + info.insurance[i].name + "\nState: " + info.insurance[i].state + "\nDiscount: " + info.insurance[i].discount + "\n" + "(" + i + 1 + "of" + object2 + ")"
}
}
myDiscount.addEventListener("mouseover", showInfo, false);
myDiscount.addEventListener("mouseout", showInfo, false);
<p id="discount">Show me the discounts!</p>
<p id="myP"></p>
If you want to show the next element of the info.insurance array each time you mouse over the paragraph, you shouldn't be using a for loop. That will do it all at once, not once for each mouseover. You need to put the counter in a global variable, and just increment it each time you call the function.
Yuo show it by assigning it to the innerHTML of the paragraph. You also need to use <br> rather than \n to make newlines (unless the style of the paragraph is pre).
var insurance_counter = 0;
function showInfo() {
var myParagraph = "Name of Business: " + info.insurance[insurance_counter].name + "<br>State: " + info.insurance[insurance_counter].state + "<br>Discount: " + info.insurance[insurance_counter].discount + "<br>(" + (insurance_counter + 1) + "of" + object2 + ")";
document.getElementById("myP").innerHTML = myParagraph;
insurance_counter++;
if (insurance_counter >= object2) { // wrap around when limit reached
insurance_counter = 0;
}
}
I want to print a multiplication table of user input number. But nothing's happening in the click But what's the mistake? or have I jump into this program early?
<body>
<p>Multiplication table</p>
<input placeholder="Enter the number" type="text" name="number" id="quest"/>
<br />
<button onclick="multFunction()">Process</button>
<br />
<p id="multiply"></p>
<script>
function multFunction() {
var a = document.getElementsById("quest").value;
var i = 1;
for (i = 1 ; i < 11 ; i++) {
var c = parseInt(a) * parseInt(i);
document.getElementById("multiply").innerHTML = a + "x" + i + "=" + c;
}
}
</script>
There's a couple of mistakes in your code:
var a = document.getElementsById("quest").value;
Should be:
var a = document.getElementById("quest").value;
// ^ No "s" there.
Next, you don't want to replace the innerHTML each time, you want to add a new row to it, instead. However, writing to innerHTML that often isn't a good idea. (each write to it causes your browser to re-parse the DOM)
Replace:
document.getElementById("multiply").innerHTML = a + "x" + i + "=" + c;
With:
result += a + " x " + i + " = " + c + '</br>';
And add result = ''; at the front of your function. Then, after the loop, write result to the innerHTML
Here's a working demo:
function multFunction() {
var a = document.getElementById("quest").value;
var i = 1;
var result = '';
for (i = 1 ; i < 11 ; i++) {
var c = parseInt(a) * parseInt(i);
result += a + " x " + i + " = " + c + '</br>';
}
document.getElementById("multiply").innerHTML = result;
}
<p>Multiplication table</p>
<input placeholder="Enter the number" type="text" name="number" id="quest"/>
<br />
<button onclick="multFunction()">Enter the number</button>
<br />
<p id="multiply"></p>
Fix getElementsById at the first line in multFunction() it should be
getElementById
using browser console or plugins like Firebug will make it easier for you to catch such errors
What i am trying to achieve is adding the javascript loops and the named variables into an sql database, some of them are already added to an external script so work fine however some which i have named in the SQL script at the bottom still need adding, however as the database won't accept a colon ":" they won't enter it and is returning an error, looking at the code at the bottom with replace function im sure you can see what i am trying to achieve but failing miserably, help is much appreciated!
window.status = 'Loading contingency scripts - please wait...';
audit('Loading contingency scripts');
var conting = {
i: 0,
start: function() {
window.status = 'Loading form - please wait...';
var t = '';
t += '<form name="frm_conting" id="frm_conting" onsubmit="return false;">';
t += '<table width="100%" cellspacing="1" cellpadding="0">';
t += '<tr><td>Date (DD/MM/YY):</td><td><input type="text" size="8" value="' + current_date + '" id="date"></td></tr>';
t += '<tr><td>Time Started:</td><td><select id="timefrom"><option></option>';
for (h = 8; h < 23; h++) {
for (m = 0; m < 46; m = m + 15) {
t += '<option value=' + nb[h] + ':' + nb[m] + '>' + nb[h] + ':' + nb[m] + '</option>';
};
};
t += '</select></td></tr>';
t += '<tr><td>Time Finished:</td><td><select id="timeto"><option></option>';
for (h = 8; h < 23; h++) {
for (m = 0; m < 46; m = m + 15) {
t += '<option value=' + nb[h] + ':' + nb[m] + '>' + nb[h] + ':' + nb[m] + '</option>';
};
};
t += '</select><tr><td>Extension #:</td><td><input type="text" size="5" value="' + my.extension + '" id="staffid"></td></tr>';
t += '<tr><td>Desk ID:</td><td><input type="text" size="5" value=' + my.deskid + ' id="desk"></td></tr>';
t += '<tr><td>Number of calls:</td><td><input type="text" size="5" id="calls"></td></tr>';
t += '<tr><td>Avid ID:</td><td><input type="text" size="5" id="avid"></td></tr>';
t += '<tr><td><input type="button" value="Submit" onClick="conting.save()"></td>';
t += '</table>';
t += '</form>';
div_form.innerHTML = t;
window.resizeTo(400, 385);
window.status = '';
},
save: function() {
var conting_date = frm_conting.date.value;
if (!isdate(conting_date)) {
alert("You have entered an incorrect date.");
return false;
};
var conting_timefrom = frm_conting.timefrom.value;
var conting_timeto = frm_conting.timeto.value;
if (conting_timefrom == '' || conting_timeto == '') {
alert("You need to enter a starting & finishing time.");
return false;
};
if (conting_timefrom > conting_timeto) {
alert("The time you have entered is after the finish time.");
return false;
};
var conting_staffid = frm_conting.staffid.value;
if (conting_staffid.length != 5) {
alert("You have entered an incorrect extension number.");
return false;
};
var conting_desk = frm_conting.desk.value;
if (conting_desk.length != 5) {
alert("You have entered an incorrect desk ID.");
return false;
};
var conting_calls = frm_conting.calls.value;
if (isNaN(conting_calls)) {
alert("You have not entered amount of calls.");
return false;
};
var conting_avid = frm_conting.avid.value;
if (isNaN(conting_avid)) {
alert("You have entered an incorrect avid ID.");
return false;
};
if (conting_avid.length != 5) {
alert("You have entered an incorrect avid ID.");
return false;
};
conn.open(db["contingency"]);
rs.open("SELECT MAX(prac_id) FROM practice", conn);
var prac_id = rs.fields(0).value + 1;
var prac_timefrom = parseFloat(frm_conting.timefrom.value);
var prac_timeto = parseFloat(frm_conting.timefrom.value);
var prac_calls = frm_conting.calls.value;
var prac_avid = frm_conting.avid.value;
rs.close();
var q = "INSERT INTO practice (prac_id, prac_staffid, prac_date, prac_timefrom, prac_timeto, prac_extension, prac_desk, prac_calls, prac_avid) VALUES (" + prac_id + "," + my.id + ", " + current_date + ", " + prac_timefrom + ", " + prac_timeto + ", " + my.extension + ", " + my.deskid + ", " + prac_calls + ", " + prac_avid + ")";
var q = "UPDATE SELECT practice REPLACE ('isNaN', ':', 'isNull')"
alert(prac_timefrom);
rs.open(q, conn);
conn.close();
}
};
window.status = '';
This bit of code looks extremely dubious.
var q = "INSERT INTO practice (prac_id, prac_staffid, prac_date, prac_timefrom, prac_timeto, prac_extension, prac_desk, prac_calls, prac_avid) VALUES (" + prac_id + "," + my.id + ", " + current_date + ", " + prac_timefrom + ", " + prac_timeto + ", " + my.extension + ", " + my.deskid + ", " + prac_calls + ", " + prac_avid + ")";
var q = "UPDATE SELECT practice REPLACE ('isNaN', ':', 'isNull')"
alert(prac_timefrom);
rs.open(q, conn);
you should use parameterised queries to avoid SQL injection. Additionally even without any deliberate SQL injection attempts this code will fail if any of the form fields contain the ' character.
You are assigning to the variable q twice and aren't executing the result of the first assignment. (And declaring it twice actually?!)
There is no syntax such as UPDATE SELECT it would need to be something like UPDATE practice SET SomeColumn = REPLACE (SomeColumn, 'isNaN', 'isNull') presumably except see 4 and 5.
I'm not clear what the Replace is meant to be doing anyway. What are the 3 parameters you have given it?
It would be better to do the Replace on the value before inserting into the database rather than inserting it wrong then updating it to the new value.