Bonjour, I am working on a jQuery project with the following scenario:
1/ There are 3 forms on the landing page for user to enter 3 different names.
2/ When user enter a name (#term1/term2/term3) in any of the #form, an image associated will appear.
The order of entering the names should not be restricted.
Eg. If user enters "Karen" in one of the forms, the name "Karen" will be printed and an associated image will be printed. If user enter "Baby Kevin", the name "Baby Kevin" will be printed next to "Karen" (ideally with a comma separating the names) and an associated image will be added next to the previous image.
I have encountered a problem where:
When a name is being entered, it would print the whole string of all the formsrather than appending it.
Eg. If I have entered "Wallace" previously, and when I enter "Karen" in another #form after, it would print "WallaceWallaceKaren".
If I submit the #form with the #button, the associated image would not show.
$(document).ready(function () {
$("#info").hide();
var displayContent = function () {
$("#info").show();
var content1 = $('#term1').val();
content1 = content1.toLowerCase().replace(/\b[a-z]/g, function (letter) {
return letter.toUpperCase();
});
var content2 = $('#term2').val();
content2 = content2.toLowerCase().replace(/\b[a-z]/g, function (letter) {
return letter.toUpperCase();
});
var content3 = $('#term3').val();
content3 = content3.toLowerCase().replace(/\b[a-z]/g, function (letter) {
return letter.toUpperCase();
});
var name1 = content1;
var $nameText1 = $("#name"),
str = name1;
html = $.parseHTML(str),
nodeNames = [];
$nameText1.append(html);
var name2 = content2;
var $nameText2 = $("#name"),
str = name2;
html = $.parseHTML(str),
nodeNames = [];
$nameText2.append(html);
var name3 = content3;
var $nameText3 = $("#name"),
str = name3;
html = $.parseHTML(str),
nodeNames = [];
$nameText3.append(html);
}
$('#search').click(displayContent);
$('#term1').keypress(function (event) {
if (event.which == 13) {
displayContent();
$('#figure').prepend('<img src = "http://placebear.com/100/100" />');
}
});
$('#term2').keypress(function (event) {
if (event.which == 13) {
$('#figure').prepend('<img src = "http://placebear.com/80/80" />');
displayContent();
}
});
$('#term3').keypress(function (event) {
if (event.which == 13) {
$('#figure').prepend('<img src = "http://placebear.com/50/50" />');
displayContent();
}
});
});
#content {
width: 400px;
height: 100px;
}
#figure {
position: fixed;
margin-left: 200px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<section id="form">
<section id="fetch">
<input type="text" placeholder="Please enter your name here" id="term1" />
<button type="button" id="search">OK</button>
<input type="text" placeholder="Please enter your name here" id="term2" />
<button type="button" id="search">OK</button>
<input type="text" placeholder="Please enter your name here" id="term3" />
<button type="button" id="search">OK</button>
</section>
<section id="info">
<h4>Take a look inside with:</h4>
<section id="content">
<h5 id="name"></div>
<div id="figure"></div>
</section>
</section>
</section>
fiddle
I cleared out your code and its working now. You can give it a try.
$(document).ready(function(){
$("#info").hide();
var displayContent = function(){
$("#info").show();
var str = [],
imgs = ["http://placebear.com/100/100","http://placebear.com/101/101","http://placebear.com/102/102"];
$("#fetch input[type=text]").each(function(i){
var v = $(this).val();
if(v != ""){
str.push(v.toUpperCase());
if($("#figure").find("#image_"+i).length == 0){
$('#figure').prepend('<img src="' + imgs[i] + '" id="image_'+i+'" />');
}
}else{
$("#figure").find("#image_"+i).remove();
}
})
$("#name").html(str.join(", "));
}
$('#search').click(displayContent);
$("#fetch input[type=text]").keypress(function(event){
if(event.which == 13){
displayContent();
}
});
});
Plus your html has some problem <h5 id="name"></div> should be <h5 id="name"></h5>
Here is the fiddle https://jsfiddle.net/f9m65to6/1/
Instead of append use $("#term2").val($("#term2").val()+"newValue")
Related
I would need help to move forward with my code. I want each time the user writes (,) between two words, they should be separated and form two li elements in a list. Right now the whole code works but I would get tips on how to make a comma separated text.
var names = [];
function convert_to_list()
{
var theName = document.getElementById("enter").value;
if (theName == "" || theName.length == 0)
{
return false; //stop the function since the value is empty.
}
names.push(theName);
document.getElementById("converted_list").children[0].innerHTML += "<li>"+names[names.length-1]+"</li>";
}
<form>
<fieldset>
<textarea id="enter" onkeyup=""></textarea>
<input onclick="convert_to_list()"value="Konvertera" type="button"/>
<div id="converted_list"><ul></ul></div>
</form>
</fieldset>
You could do something like I did in this codepen.
Use the split function to split a string when it encounters a specified character, in your case a comma.
The HTML (pug) would look like this:
form
label
span seperated list
input#js-seperatedList(type="text")
ul.results
And this will be your JavaScript code:
const inputValue = document.querySelector('#js-seperatedList')
const results = document.querySelector('.results');
inputValue.addEventListener('keyup', (e) => {
results.innerHTML = ''
const res = e.target.value.split(",")
for (let i = 0; i < res.length; i += 1) {
const e = document.createElement('li');
e.innerHTML = res[i]
results.appendChild(e)
}
})
Use split() function to separate the words using comma and then create li element and append into final ul element.
const btnEnter = document.getElementById("btnEnter");
btnEnter.addEventListener("click", convert_to_list);
const ulElements = document.getElementById("converted_list").children[0];
function convert_to_list() {
const theName = document.getElementById("enter").value;
if (theName.length <= 0) {
return false;
}
const list = theName.split(",");
const liElements = [];
for (const value of list) {
const li = document.createElement('li');
li.innerHTML = value.trim();
ulElements.appendChild(li);
}
}
<html>
<head></head>
<body>
<form>
<fieldset>
<textarea id="enter" onkeyup=""></textarea>
<input id="btnEnter" value="Konvertera" type="button"/>
<div id="converted_list"><ul></ul></div>
</fieldset>
</form>
</body>
</html>
i would recommend using addEventListener which is much simpler than calling functions inside html elements , and to do what you asking the split() method can do that with any string , if there is something you don't understand with this code i am happy to help
document.querySelector('.btnclick').addEventListener('click', function () {
const theName = document.getElementById('enter').value;
if (theName.includes(',')) {
theName.split(',').map(function (e) {
if (e !== '')
return document
.querySelector('#converted_list')
.insertAdjacentHTML('afterbegin', `<li>${e}</li>`);
});
} else if (theName !== '' || theName.length !== 0) {
document
.querySelector('#converted_list')
.insertAdjacentHTML('afterbegin', `<li>${theName}</li>`);
}
});
<form>
<fieldset>
<textarea id="enter" onkeyup=""></textarea>
<input class="btnclick" value="Konvertera" type="button" />
<div id="converted_list">
<ul></ul>
</div>
</form>
document.querySelector("form").onclick=(ev,v)=>{
if (ev.target.tagName==="BUTTON") {
ev.preventDefault();
v=ev.target.previousElementSibling.value.trim();
ev.target.nextElementSibling.innerHTML=(v>""?"<li>"+v.replaceAll(",","</li><li>")+"</li>":"");
}
}
<html>
<head></head>
<body>
<form>
<fieldset>
<textarea id="enter" onkeyup=""></textarea>
<button>Konvertera</button>
<div id="converted_list"><ul></ul></div>
</fieldset>
</form>
</body>
</html>
I'm trying to add a functionality to textarea which will add <br> tag to innerHTML of textarea when Enter is pressed.
Here is my codepen.
I've tried this with texareaElement.val(); but it adds directly to textarea, but it shouldn't be seen by user. It should be on the background.
function textAreaNewLine(element, event) {
// 13 is the keycode for "enter"
if (event.keyCode == 13) {
var elVal = element.val();
element.val(elVal + '<br>');
}
}
$('#ta').on('keypress', function(event) {
var el = $(this);
textAreaNewLine(el, event);
$('.main').html($('#ta').val());
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<textarea rows="4" cols="50" id="ta"></textarea>
<div class="main"></div>
If I understand your question correctly, You can add an empty line like:
Introduce another variable
var emptyLine = "\n";
and then append this to the value.
Check the fiddle below
function textAreaNewLine(element, event) {
// 13 is the keycode for "enter"
if (event.keyCode == 13) {
var elVal = element.val();
var emptyLine = "\n";
element.val(elVal + emptyLine );
}
}
$('#ta').on('keypress', function(event) {
var el = $(this);
textAreaNewLine(el, event);
$('.main').html($('#ta').val());
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<textarea rows="4" cols="50" id="ta"></textarea>
<div class="main"></div>
Hello,
I am making a simple text changer website where I want the user to be able to select what options to use. Right now I have two options; myConvertOption which capitalizes every odd letter in a word and I have myScrambleOption which randomly mixes up each word a bit.
Right now whenever you click on Caps (checkbox_1) it already executes the function where I only want it to execute whenever the user clicks on the "Convert" button + it also puts spaces in between each letter now.
The Scramble button (checkbox_2) doesn't do anything for some reason, except for console logging the change.
JSfiddle: https://jsfiddle.net/MysteriousDuck/hLjytr2p/1/
Any help and suggestions will be greatly appreciated!
P.S I am new to Javascript.
Checkbox event listeners:
checkbox_1.addEventListener('change', function () {
console.log("checkbox_1 changed");
if (this.checked) {
myConvertFunction();
} else {
//Do nothing
}
})
checkbox_2.addEventListener('change', function () {
console.log("checkbox_2 changed");
if (this.checked) {
myScrambleFunction(text);
} else {
//Do nothing
}
})
Checkbox HTML:
<div class="checkbox">
<input type="checkbox" id="checkbox_1" >
<label for="checkbox_1">Caps</label>
</div>
<div class="checkbox">
<input type="checkbox" id="checkbox_2" >
<label for="checkbox_2">Scramble</label>
</div>
this works properly..
You just had to add the event on the button and then test which check box was checked, and other little things
<!doctype html>
<html>
<head>
</head>
<body>
<div class="container">
<h1> Text Changer </h1>
<h2> CAPS + randomize letters text changer</h2>
<div class="checkbox">
<input type="checkbox" id="checkbox_1">
<label for="checkbox_1">Caps</label>
</div>
<div class="checkbox">
<input type="checkbox" id="checkbox_2">
<label for="checkbox_2">Scramble</label>
</div>
<textarea type="text" autofocus="true" placeholder="input text" id="inputText" value="Input Value" spellcheck="false" style="width: 300px;"></textarea>
<button class="button button1" id="convertText">Convert</button>
<textarea type="text" placeholder="converted text" id="convertedText" value="Clear" readonly="true" spellcheck="false" style="width: 300px;"></textarea>
<button class="button button1" id="copyText">Copy</button>
</div>
<script>
var text = document.getElementById("inputText").value;
var convertText = document.getElementById("convertText");
var checkbox_2 = document.getElementById("checkbox_2");
var checkbox_1 = document.getElementById("checkbox_1");
//Capitalize every odd letter
function myConvertFunction() {
var x = document.getElementById("inputText").value;
var string = "";
for (let i = 0; i < x.length; i++) {
if (i % 2 == 0) {
string = string + x[i].toUpperCase();
} else {
string = string + x[i];;
}
}
return string;
}
//Scramble words
function myScrambleFunction(text) {
let words = text.split(" ");
words = words.map(word => {
if (word.length >= 3) {
return word.split('').sort(() => 0.7 - Math.random()).join('');
}
return word;
});
return words.join(' ');
}
document.getElementById("copyText").addEventListener("click", myCopyFunction);
//Copy textarea output
function myCopyFunction() {
var copyText = document.getElementById("convertedText");
copyText.select();
document.execCommand("copy");
alert("Copied the text: " + copyText.value);
eraseText();
}
//Delete textarea output
function eraseText() {
document.getElementById("convertedText").value = "";
document.getElementById("inputText").value = "";
document.getElementById("inputText").focus();
}
//don't add the event to the radio buttons (previously checkboxes), add it to the convert button, and in its function test which radio button has been checked
convertText.addEventListener('click', function() {
if (checkbox_1.checked && checkbox_2.checked) {
console.log("doing both options");
document.getElementById("convertedText").value = myScrambleFunction(myConvertFunction());
} else if (checkbox_2.checked) {
console.log("proceeding scrumble");
document.getElementById("convertedText").value = myScrambleFunction(text);
} else if (checkbox_1.checked) {
console.log("proceeding cap");
document.getElementById("convertedText").value = myConvertFunction();
}
})
</script>
</body>
</html>
You're never updating var text.
You need to update it before using it if you want the value to be something other than an empty string.
checkbox_2.addEventListener('change', function () {
console.log("checkbox_2 changed");
if (this.checked) {
text = document.getElementById("inputText").value;
myScrambleFunction(text);
} else {
//Do nothing
}
i would like to know how i can make it so when people input something it goes in a bulleted list, in the middle of the screen. Like but in javascript?
I got my code from: How to display input back to the user on an HTML page?
<html><head></head><body>
<input id="title" type="text" maxlength="276" onkeyup="Allow()" >
<input type="submit" value="Save/Show" onclick="insert()" />
<div id="display"></div>
<script type="text/javascript">
var titles = [];
var titleInput = document.getElementById("title");
var messageBox = document.getElementById("display");
function Allow(){
if (!user.title.value.match(/[a-zA-Z1-9]$/) && user.title.value !="") {
user.title.value="";
alert("Please Enter only alphabets");
}
}
function insert () {
titles.push(titleInput.value);
clearAndShow();
}
function clearAndShow () {
titleInput.value = "";
messageBox.innerHTML = "";
messageBox.innerHTML += "To Do: " + titles.join(", ") + "<br/>";
}
</script>
</body>
</html>
jsbin example: https://jsbin.com/xahidolibu/edit?html,output
I've modified your code to:
create a list instead of comma deliminated string on clearAndShow()
added css to center align the list
jsbin: https://jsbin.com/lamebopidu/1/edit?html,css,output
I'm trying to create a simple "search field", what it does is it searches if typed in text is equal to any data-attr of the boxes in the content and if so, hide everything but what found, something similar (this ain't working):
css:
.filter-div {
display: none;
}
html:
<label for="search">Search Input:</label>
<input type="search" name="filter" id="search" value="" />
<div class="filter-div" data-filter="one">one</div>
<div class="filter-div" data-filter="two">two</div>
<div class="filter-div" data-filter="three">three</div>
<div class="filter-div" data-filter="four">four</div>
<div class="filter-div" data-filter="five">five</div>
jquery:
// save the default value on page load
var filter = $('.input').val();
// on submit, compare
if ( $('.input').val() = $("data-filter") {
$(this).show();
}
I am also not sure if the content should be filtered with a button click or found content should pop up as click-able text in the search, or should all happen auto? Finally probably I will have to check it against more than one data-attr.
Anyone?
$('#search').on('keyup', function() {
var val = $.trim(this.value);
if (val) {
$('div[data-filter=' + val + ']').show();
} else $('div[data-filter]').hide();
});
Working sample
According to demo fiddle example in comment
var divs = $('div[data-filter]');
$('#search').on('keyup', function() {
var val = $.trim(this.value);
divs.hide();
divs.filter(function() {
return $(this).data('filter').search(val) >= 0
}).show();
});
divs.on('click', function() {
divs.not(this).hide();
var text = $.trim($(this).text());
$('#search').val(text);
});
Working sample
JavaScript:
var filter_div = $('[data-filter]');
$('#search').keyup(function(){
var val = $.trim(this.value);
filter_div.hide();
if(val.length == 0) return;
filter_div.filter(function(){
return $(this).data('filter').indexOf(val)>-1
}).show();
});
Fiddle: http://jsfiddle.net/iambriansreed/xMwS5/