I want to make a form that contains a filed. Value of field will replace a string between double bracket in the template. here example :
first, I type value in field with id "username".
second, the string between <textarea></textarea> with double bracket {{username}} (which is It has been around since it was loaded) will replace by value that I type in first form.
I try the same thing like this but it's not work with my case.
Here's a way how you could do it:
const textarea = document.querySelector('textarea');
const inputs = [...document.querySelectorAll('input[id]')];
const template = textarea.value;
function update() {
textarea.value = inputs.reduce((acc, i) => acc.replace(new RegExp(`\\{\\{\\s*${i.id}\\s*\\}\\}`, 'g'), i.value), template);
}
inputs.forEach(e => e.addEventListener('input', update));
update();
<label for="username">Username:</label>
<input id="username" />
<br />
<label for="age">Age:</label>
<input id="age" />
<br /><br />
<textarea readonly="readonly">user: {{username}} age: {{age}}</textarea>
Alternatively,
Split template from the result, this way you can define the template and update the username or any other fields without needing to go through it and fix after you entered first char which is what will happen if the template is ever predefined.
// define fields
let fields = {
'username': document.querySelector('input[name="username"]'),
'when': document.querySelector('input[name="when"]')
}
// working textareas
const template = document.querySelector('textarea[name="template"]');
const textarea = document.querySelector('textarea[name="template-rendered"]');
// get fields values and render into textarea value
function renderTemplate() {
let vars = {}
for (let field in fields)
if (fields[field].value) vars[field] = fields[field].value
textarea.value = template.value.replace(/\{{[ ]{0,}([\w\_-]{1,})[ ]{0,}}}/gi, function(...match) {
return typeof vars[match[1]] !== 'undefined' ? vars[match[1]] : `{{ ${match[1]} }}`
})
}
// template update event
template.addEventListener('input', renderTemplate);
// attach input events
for (let field in fields)
fields[field].addEventListener('input', renderTemplate);
div {
margin-bottom: 10px;
}
textarea {
height: 50px;
width: 100%
}
<div>
<label for="username">Username:</label>
<input name="username" />
</div>
<div>
<label for="when">When:</label>
<input id="when" name="when" />
</div>
<div>
<label for="username">Template:</label>
<textarea id="template" name="template">Hello {{ username }}, how are you {{ when }}?</textarea>
</div>
<div>
<label for="result">Result:</label>
<textarea id="result" name="template-rendered"></textarea>
</div>
after a few tries finally.
function myFunction(value) {
String.prototype.replaceAt = function(index,index2, replacement,awal) {
return this.substr(awal.length-index, index+2) + replacement + this.substr(index2);
}
var p=document.getElementById("p");
var str = p.value;
var index1 = str.indexOf("{{");
var index2 = str.indexOf("}}");
var awalan=str.split('{{')[0];
p.value=(str.replaceAt(index1,index2, value,awalan));
}
<input onInput="myFunction(this.value)"/>
<br>
<br>
<Textarea id="p">my name is {{username}} im living on earth.</textarea>
Related
I need to display some numbers, strings from a class named Student, but i can't figure it out how i can change the id from children element. I have to use JavaScript.
what i tried to do:
class Student{
static count = 0;
constructor(nume, prenume, data_nasterii, foaie_matricola){
this.IdClasa = ++Student.count;
//definirea atributelor
this.nume = nume;
this.prenume = prenume;
this.data_nasterii = data_nasterii;
this.foaie_matricola = foaie_matricola;
}
afiseazaVarsta(){
}
afiseazaNotele(){
}
calculeazaMedia(){
}
adaugaNota(nota_noua){
}
}
var Stud = [new Student("Name", "Name1", "2000.01.01", "0123123"),
new Student("Green", "Blue", "2022/12.12", "321321")];
function afisareStudenti(){
let i = 0; let bol = false;
for(let x=1; x<=Student.count; x++) {
console.log(document.getElementById("AfisareStudenti"+x)==null);
if(document.getElementById("AfisareStudenti"+x)==null)
{
i = x;
bol = true;
break;
} else {
bol = false;
}
}
if((i<=Student.count)&&(bol==true)){
for(i; i<=Student.count; i++) {
console.log("i="+i);
var div = document.querySelector('#AfisareStudenti1');
var divClone = div.cloneNode(true);
console.log(divClone);
divClone.id = 'AfisareStudenti'+(i);
div.after(divClone);
var NumeStud = document.getElementById("NumeStudent"+(i-1));
var PrenumeStud = document.getElementById("PrenumeStudent"+(i-1));
var dataNastStud = document.getElementById("intData"+(i-1));
var FoaiaMatStud = document.getElementById("FoaiaMatStud"+(i-1));
NumeStud.id = "NumeStudent"+(i);
PrenumeStud.id = "PrenumeStud"+(i);
dataNastStud.id = "intData"+(i);
FoaiaMatStud.id = "FoaiaMatStud"+(i);
}
}
}
and this is the html file(the div that i want to clone):
<!--AFISARE-->
<div id="AfisareStudenti1">
<h2> Afisare Student 1</h2>
<label>Ce student doriti sa modificati? </label>
<form>
<label>Nume:</label><br>
<input type="text" id="NumeStudent1"><br>
<label>Prenume:</label><br>
<input type="text" id="PrenumeStudent1"><br>
<label>Data Nasterii:</label><br>
<input type="date" id="intData1"><br>
<label>Foaie matricola:</label><br>
<input type="text" id="FoaiaMatStud1"><br><br>
<input class="butoane" type="submit" value="Afisare"
onclick="afisareMeniuAfisStudenti()">
</form>
</div>
the class is saved in a dynamic array (could be n object of the class) so i have to make somehow to display the information dynamic. My version changes the id from all elements with the same id (every incrementation of i, the idnumber from id is incremented also). I tried to create that div with document.createElement but is impossible(at least for me) xD . I started coding in javascript 2 days ago, so please take it slow on me :(
I think i found the problem, but it doesn't solve it. (i need to put (i-1) when calling for getting the ids). (Newbie mistake)
Having commented ...
"I have the feeling that if provided with the broader picture the audience could be of much more help since the OP could be provided back with leaner/cleaner and better maintainable approaches."
... I nevertheless hereby lately provide a template-based approach which, besides supporting the OP's id based querying of student-items, is also easier to read and to maintain.
The code provided within the example-code's main function does not just implement the usage of the template-based node-creation via template literals and DOMParser.parseFromString but also prevents the default behavior of each student-form's submit-button by making use of event-delegation.
function createStudentElement(studentId) {
const markup =
`<div class="student-item" id="AfisareStudenti${ studentId }">
<h2> Afisare Student ${ studentId }</h2>
<label>Ce student doriti sa modificati? </label>
<form>
<label>Nume:</label><br>
<input type="text" id="NumeStudent${ studentId }"><br>
<label>Prenume:</label><br>
<input type="text" id="PrenumeStudent${ studentId }"><br>
<label>Data Nasterii:</label><br>
<input type="date" id="intData${ studentId }"><br>
<label>Foaie matricola:</label><br>
<input type="text" id="FoaiaMatStud${ studentId }"><br><br>
<input
class="butoane" type="submit" value="Afisare"
onclick="afisareMeniuAfisStudenti(${ studentId })"
>
</form>
</div>`;
const doc = (new DOMParser).parseFromString(markup, 'text/html');
return doc.body.removeChild(doc.body.firstElementChild);
}
// the button click handler.
function afisareMeniuAfisStudenti(studentId) {
console.log({ studentId })
}
function main() {
const itemsRoot = document.querySelector('.student-items');
// - prevent any form-submit by making use of event-delegation.
itemsRoot.addEventListener('submit', evt => evt.preventDefault());
// - just for demonstration purpose ...
// ... create student-items from a list of student IDs.
[1, 2, 3, 4, 5].forEach(studentId =>
itemsRoot.appendChild(
createStudentElement(studentId)
)
);
}
main();
.as-console-wrapper { left: auto!important; width: 50%; min-height: 100%; }
<div class="student-items"></div>
Tom's answer above is what you want for the element id problem that you asked about.
For your code in particular, you are going to have a couple other problems:
Because the final input is type="submit", its going to reload the page by default when it is clicked. The name of the "onclick" function also needs to match the function you defined (afisareStudenti).
You have:
<input class="butoane" type="submit" value="Afisare" onclick="afisareMeniuAfisStudenti()">
Change this to:
<input class="butoane" type="submit" value="Afisare" onclick="afisareStudenti(event)">
Now, when you click that button, it will call the afisareStudenti function and pass in the "event". So if you change:
function afisareStudenti(){
let i = 0; let bol = false;
to:
function afisareStudenti(event){
event.preventDefault()
let i = 0; let bol = false;
This will correctly call your function, and prevent the "default" action of that submit button from reloading the page.
To change the id attribute of children elements, you could use Element.querySelector() on divClone.
Because if you use Document.querySelector() or Document.getElementById() you will get the first element that matches your selector (i.e.children of div#AfisareStudenti1).
let i = 2;
var div = document.querySelector('#AfisareStudenti1');
var divClone = div.cloneNode(true);
divClone.id = 'AfisareStudenti'+(i);
divClone.querySelector("h2").innerText = "Afisare Student " + i;
var NumeStud = divClone.querySelector("#NumeStudent1");
var PrenumeStud = divClone.querySelector("#PrenumeStudent1");
var dataNastStud = divClone.querySelector("#intData1");
var FoaiaMatStud = divClone.querySelector("#FoaiaMatStud1");
NumeStud.id = "NumeStudent"+(i);
PrenumeStud.id = "PrenumeStud"+(i);
dataNastStud.id = "intData"+(i);
FoaiaMatStud.id = "FoaiaMatStud"+(i);
div.after(divClone);
<div id="AfisareStudenti1">
<h2> Afisare Student 1</h2>
<label>Ce student doriti sa modificati? </label>
<form>
<label>Nume:</label><br>
<input type="text" id="NumeStudent1" /><br>
<label>Prenume:</label><br>
<input type="text" id="PrenumeStudent1" /><br>
<label>Data Nasterii:</label><br>
<input type="date" id="intData1" /><br>
<label>Foaie matricola:</label><br>
<input type="text" id="FoaiaMatStud1" /><br><br>
<input class="butoane" type="submit" value="Afisare" onclick="afisareMeniuAfisStudenti()" />
</form>
</div>
I'm a beginner in web development and I have an HTML form where a person can add his address , address number, region and postal code . In this form the address and the region have to contain only char letters .
(ex. Lakewood : correct Lakewood13 : error) . If any of these two variables contains a number I have to enter my data again to continue . Else, I move to the next page . I'm a complete beginner in javascript which I need to use to check my variable types and I would appreciate your help with guiding me to solve this problem .
This is my code with my HTML form with the address number and the region which are the variables we need in this problem :
function checkdata(){
//the two elements we need to check
var a = document.getElementById("address");
var r = document.getElementById("region");
if(typeof(a.value) === 'string'&&(typeof b.value) ==='string'){
//continue to next page(but how can I check if numbers are in the strings ?)
}
else{
//go back to form and enter again(how can I enter the elements again ? )
}
}
<div class = "form-area" id = "forma">
<form action="/action.page.html" class = "sign-form" >
<div class = "form-container">
<h1> Enter purchase data below : </h1>
<label for="addrs"> Address Name</label>
<input type = "text" placeholder = "Enter address name " id = "address" name = "addr" required/>
<label for="regn" > Region </label>
<input type = "text" placeholder = "Enter region " id = "region" name = "reg" required/>
</div>
<button type="submit" class="continuebtn" onclick = "checkdata()">Continue</button>
</form>
</div>
Thank you in advance .
You can try using regex to check if string contains any number in it:
if(!(/\d/.test(a.value)) && !(/\d/.test(b.value))){
Please Note: You also have to return false to prevent the default event if the condition is false and prefix return the function call in onclick attribute.
Demo:
function checkdata(){
//the two elements we need to check
var a = document.getElementById("address");
var r = document.getElementById("region");
if(!(/\d/.test(a.value)) && !(/\d/.test(r.value))){
alert('form submit');
}
else{
alert('no submit');
return false;
}
}
<div class = "form-area" id = "forma">
<form action="/action.page.html" class = "sign-form" >
<div class = "form-container">
<h1> Enter purchase data below : </h1>
<label for="addrs" Address Name</label>
<input type = "text" placeholder = "Enter address name " id = "address" name = "addr" required/>
<label for="regn" > Region </label>
<input type = "text" placeholder = "Enter region " id = "region" name = "reg" required/>
</div>
<button type="submit" class="continuebtn" onclick = "return checkdata()">Continue</button>
</form>
</div>
You can write a function for validity, then you can check for dependencies based on that **
function checkData() {
let adress = document.getElementById('address');
let region = document.getElementById('region');
function isValid(e) {
let isTrue;
for (let char in e) {
typeof e[char] !== 'string' ? alert('Please only type strings') : (isTrue = true);
}
return isTrue;
}
isValid(adress.value) && isValid(region.value) ? console.log('next page') : console.log('error');
}
checkData();
**
So need to check if the strings are containing numbers or not
hope you find more insight here: Check whether an input string contains a number in javascript
working demo :
// check if string contains number
function hasNumber(myString) {
return /\d/.test(myString);
}
function checkdata(e) {
e.preventDefault()
//the two elements we need to check
var a = document.getElementById("address");
var r = document.getElementById("region");
var isAddressContainsNumber = hasNumber(a.value);
var isRegionContainsNumber = hasNumber(r.value);
console.log(isAddressContainsNumber, isRegionContainsNumber)
if (isAddressContainsNumber === false && isRegionContainsNumber === false) {
console.log('None of string contains number')
} else {
console.log('One or Both string contains number')
}
}
const form = document.querySelector('.sign-form');
form.addEventListener('submit', checkdata);
<div class="form-area" id="forma">
<form class="sign-form">
<div class="form-container">
<h1> Enter purchase data below : </h1>
<label for "addrs" Address Name</label>
<input type="text" placeholder="Enter address name " id="address" name="addr" required/>
</label>
<label for "regn" > Region </label>
<input type="text" placeholder="Enter region " id="region" name="reg" required/>
</label>
</div>
<button type="submit" class="continuebtn">Continue</button>
</form>
</div>
I would recommend going through the string and getting the ASCII value of each character. Numbers 0-9 are ASCII characters 48-57. Javascript uses UTF-16 and the appropriate method (charCodeAt) returns a 16-bit UTF-16 value, but UTF-16 characters 0-127 match ASCII. So:
var testString = "abcd123";
var isValid = true;
for (var i=0;i<testString.length;i++)
{
if (testString.charCodeAt(i) > 47 && testString.charCodeAt(i) < 58)
{
isValid = false;
}
}
if (!isValid)
{
//Code here to alert the user
alert("There's a number in there!");
}
You are using typeof in wrong way, try this way
typeOf(variable you want to check)
this is the string:
Hi <input type="text" placeholder="Person Full Name">,<span><br></span><span><br></span><span><span>This is a sample email template for </span></span><input type="text" placeholder="Deal Title"> associated with <input type="text" placeholder="Deal Owner"><span><br></span><span><br></span><span><span><br></span></span><span><span><span>Regards,</span></span></span><span><span><span><span><br></span></span></span></span><input type="text" placeholder="Organization Name"><span><br></span><span>dlkgmffkgmkm </span><input type="text" placeholder=""> dslkfmlgdmglkfnkl <input type="text" placeholder=""><br>
I am also using an Editor in my textarea.
$(".btn-removehtml").click(function() {
html = $('.email-textarea').Editor("getText");
replaceInput = html.find('input').replaceWith(function() {
return this.innerHTML;
}).end().html();
});
You can try this..
var string = '<input type="text" placeholder="Person Full Name">,<span><br></span><span><br></span><span><span>';
var newString = $(string).not('input');
$('body').append(newString);
For all use input you can do this.
var newString = $(string).find('input').remove().end();
call the below function to replace the all the input in to static value "abcd"
function parseEmailTemplate(html) {
let myRegex = /<input\s[^>]*>/gi;
let match = myRegex.exec(html);
if (match) {
value="abcd";
html = html.replace(match[0], value);
html = parseEmailTemplate(html);
}
return html;
}
<p><input type="text" name="adcode" id="cityName"
style="border:none;color:green;"/></p>
<script>
window.onload = function() {
document.getElementById('cityName').value = GetDivElement();
}
</script>
The above code, I am not able to call the "GetDivElement" in paragraph
<p id="cityName"></p>
How to pass the GetElementId in p id??
If you want to get the GetDivElement() method's return value to the paragraph, you can do it like below:
window.onload = function() {
let getDivElement = () => {
return 'Div element data';
};
let inputbox = document.getElementById('cityInput');
let cityParagraph = document.getElementById('cityValue');
inputbox.value = cityParagraph.innerHTML = getDivElement();
}
<div>
<input id="cityInput" />
<p id="cityValue"></p>
</div>
As I understood from your later comment, if you want to get the paragraph value if the id='coimbatore' which you get from the GetDivElement() method you can do the following:
window.onload = function() {
let getDivElement = () => {
return 'coimbatore';
};
let paraId = getDivElement();
let textboxId = `${paraId}CityInput`;
let inputbox = document.getElementById(textboxId);
let cityParagraph = document.getElementById(paraId);
console.log(`Text field value is : ${inputbox.value}`);
console.log(`Paragraph value is : ${cityParagraph.innerHTML}`);
}
<div>
<input id="delhiCityInput" value="delhi input"/>
<p id="delhi">
Delhi city data
</p>
</div>
<div>
<input id="mumbaiCityInput" value="mumbai input"/>
<p id="mumbai">
Mumbai city data
</p>
</div>
<div>
<input id="coimbatoreCityInput" value="coimbatore input"/>
<p id="coimbatore">
Coimbatore city data
</p>
</div>
Couple of things you need to understand here is,
You can't set the same id for multiple html elements
If you want to get the value from a paragraph you should use innerHTML
Hope this helps.
I want to get only the first letter of what is written in the input. Can help me?
<input id="texte" type="text" placeholder="type your name here" oninput="copyText('texte', 'text')">
<div id="text">first letter here</div>
<script type="text/javascript">
function copyText(texteId, text1Id) {
var data = document.getElementById(texteId).value;
document.getElementById(text1Id).innerHTML = data;
}
</script>
Yes you can split the variable data as an array:
function copyText(texteId, text1Id) {
var data = document.getElementById(texteId).value[0];
document.getElementById(text1Id).innerHTML = data;
}
<input id="texte" type="text" placeholder="type your name here" oninput="copyText('texte', 'text')">
<div id="text">first letter here</div>
Use [number] to get the value at some point.
Or you could use the slice() function:
function copyText(texteId, text1Id) {
var data = document.getElementById(texteId).value;
document.getElementById(text1Id).innerHTML = data.slice(0,1);
}
<input id="texte" type="text" placeholder="type your name here" oninput="copyText('texte', 'text')">
<div id="text">first letter here</div>
Or as suggested in the other answer charAt().
Use charAt(0) to get the first character:
function copyText(inputId,displayId) {
var data = document.getElementById(inputId).value;
var firstLetter = data.charAt(0);
document.getElementById(displayId).innerHTML = "The first letter is: " + firstLetter;
}
<label for ="texte">Type your name here</label>
<input id="texte" type="text" onkeyup="copyText('texte','text')">
<p id="text"></p>
function copyText( texteId, text1Id ) {
var d = document;
d.g = d.getElementById;
var data = d.g( texteId ).value[0];
d.g( text1Id ).innerHTML = data;
}
<input id="texte" type="text" placeholder="type your name here" oninput="copyText('texte', 'text')">
<div id="text">first letter here</div>
In JavaScript you may treat a string as if it were an array. So by specifying the zeroeth index of value, the code grabs the first letter and that becomes the content of the div with the id of "text" using that element's innerHTML property.
const input = document.querySelector('#texte');
const text = document.querySelector('#text');
// keydown and keyup are alternate events
input.addEventListener('input', function() {
text.innerHTML = this.value[0];
});