How to make my button work after I've been writing? - javascript

Im trying to make some kind of "blog" buttons. I want to click on a button, and then it will write in my textarea for whatever button I clicked. But for some reason, it wont add if I've been writing or done anything in the textarea before I clicked.
<button onClick="knapp('lank')">Länk</button>
<button onClick="knapp('fet')">Fet</button>
<button onClick="knapp('bild')">Bild</button>
<br><br>
<textarea id='knappar' rows="10" cols="50"></textarea>
And my scriptcode is
function knapp(value)
{
var text;
switch(value){
case "fet":
text = '<b></b>';
break;
case "lank":
text = 'Klicka här';
break;
case "bild":
text = '<img src="https://www.hemsida.com">';
break;
}
var pp = document.createTextNode(text);
document.getElementById('knappar').appendChild(pp);
}
So when I click the button, it writes and append. But if I've been writing, or deleting something, it wont work.
I'm fairly new with Javascript, so sorry for noob question.

Try using
document.getElementById('knappar').value += text;
instead of
var pp = document.createTextNode(text);
document.getElementById('knappar').appendChild(pp);
Full Example
function knapp(value) {
var text;
switch (value) {
case "fet":
text = '<b></b>';
break;
case "lank":
text = 'Klicka här';
break;
case "bild":
text = '<img src="https://www.hemsida.com">';
break;
}
var pp = document.createTextNode(text);
document.getElementById('knappar').value += text;
}
<button onClick="knapp('lank')">Länk</button>
<button onClick="knapp('fet')">Fet</button>
<button onClick="knapp('bild')">Bild</button>
<br><br>
<textarea id='knappar' rows="10" cols="50"></textarea>

Related

Converting if statement to switch statement

I need to convert the if statement in the function to a switch statement for an assignment. What the function needs to do is have the user input be a displayed list item when they press the submit button. When the number of inputs equals 5, it says "Thanks for your suggestions."
I included the original if statement as a comment.
I'm not sure where to go from here so that it works the same as the if statement.
<article>
<div id="results">
<ul>
<li id="item1"></li>
<li id="item2"></li>
<li id="item3"></li>
<li id="item4"></li>
<li id="item5"></li>
</ul>
<p id="resultsExpl"></p>
</div>
<form>
<fieldset>
<label for="toolBox" id="placeLabel">
Type the name of a tool, then click Submit:
</label>
<input type="text" id="toolBox" />
</fieldset>
<fieldset>
<button type="button" id="button">Submit</button>
</fieldset>
</form>
</article>
<script>
// global variables
var i=1;
var listItem = "";
// function to add input to list
function processInput()
{
/*
if (i<=5)
{
listItem = "item" + i;
document.getElementById(listItem).innerHTML = document.getElementById("toolBox").value;
document.getElementById("toolBox").value = "";
if (i==5)
{
document.getElementById("resultsExpl").innerHTML = "Thanks for your suggestions.";
}
i++;
}
*/
switch (i) {
case 5:
document.getElementById("resultsExpl").innerHTML = "Thanks for your suggestions.";
break;
case default:
listItem = "item" + i;
document.getElementById(listItem).innerHTML = document.getElementById("toolBox").value;
document.getElementById("toolBox").value = "";
i++;
}
}
// adds backward compatible event listener to Submit button
var submitButton = document.getElementById("button");
if (submitButton.addEventListener) {
submitButton.addEventListener("click", processInput, false);
} else if (submitButton.attachEvent) {
submitButton.attachEvent("onclick", processInput);
}
</script>
I'll quote Douglas Crockford from: Javascript the good parts
The switch statement is a competent feature. Like most competent
features, it has loads of problems with it- the requirement of using
break after every statement within a case, procedural control flow,
out-of-place syntax, handling of code blocks, and much much more!
Unfortunately, solving these problems would require us to rewrite how
it operates at the core and the spec would entirely change, which, for
a language like JavaScript, would create massive backwards
compatibility issues.
Bottom line: Stick to if/else if/else statements.
I was able to figure it out. I realized I put 'case default' instead of 'default'. I had to include some of the code from default to case 5 for it to display the last input as well as the message. I also placed i++ outside of the switch statement so that it stops after the 5th iteration but doesn't replace the last input.
switch (i) {
case 5:
listItem = "item" + i;
document.getElementById(listItem).innerHTML = document.getElementById("toolBox").value;
document.getElementById("toolBox").value = "";
document.getElementById("resultsExpl").innerHTML = "Thanks for your suggestions.";
break;
default:
listItem = "item" + i;
document.getElementById(listItem).innerHTML = document.getElementById("toolBox").value;
document.getElementById("toolBox").value = "";
}
i++;

How can I merge javascript code with html form that triggers when we perform some action like "submit" and gives output?

I created a function using switch case in javascript.
function convert(x){
switch(x) {case "c": return "d"; case "a": return "o"; case "t": return "g";}
}
var str = "cat";
var result = "";
for(var i = 0; i < str.length; i++)
{
result += convert(str[i]) ;
}
console.log(result);
In this program,I gave default value of str = "cat" which gives output
dog. But instead of passing default value, I want to pass value via html form and print output. So I created a simple html form.
<html>
<head>
<script language="JavaScript">
function showOutput() {
document.getElementById('display').innerHTML = document.getElementById("user_input").value;
}
</script>
</head>
<body>
<form>
<label><b>Please give your input: </b></label>
<input type="text" name="message" id="user_input">
</form>
<input type="submit" onclick="showOutput();"><br/>
<label>Your output is : </label>
<p><span id='display'></span></p>
</body>
</html>
The layout of this HTML form is shown.
Now I want to input value as "cat " and when I click submit, I want output as "dog" using javascript code which I created earlier that has the "convert" function.
You need to put the loop inside the showOutput function so it will convert the user inputs and display the result in display span when the button is clicked.
NOTE 1: I suggest the use of addEventListener() instead of inline-event onClick when you attach events like :
document.querySelector('[type="submit"]').addEventListener('click', showOutput, false);
NOTE 2: You may need to put the submit input inside the form to validate the structure of your HTML code, you could also use .textContent attribute instead of .innerHTML since you're just assigning text and no HTML code.
document.querySelector('[type="submit"]').addEventListener('click', showOutput, false);
function showOutput() {
event.preventDefault();
var str = document.getElementById("user_input").value;
var result = "";
for (var i = 0; i < str.length; i++) {
result += convert(str[i]);
}
document.getElementById('display').textContent = result;
}
function convert(x) {
switch (x) {
case "c":
return "d";
case "a":
return "o";
case "t":
return "g";
}
}
<form>
<label><b>Please give your input: </b></label>
<input type="text" name="message" id="user_input">
<input type="submit">
</form>
<br/>
<label>Your output is : </label>
<p><span id='display'></span></p>
You can place the code inside showOutput(). Then assign the returned result from the function to the element.
I will also suggest you to use textContent() instead of innerHTML() when dealing with text only content as it is faster, safer, and more predictable.
function showOutput() {
var str = document.getElementById("user_input").value;
var result = "";
for(var i = 0; i < str.length; i++){
result += convert(str[i]) ;
}
document.getElementById('display').textContent = result;
}
function convert(x){
switch(x) {
case "c": return "d";
case "a": return "o";
case "t": return "g";
}
}
<form>
<label><b>Please give your input: </b></label>
<input type="text" name="message" id="user_input">
</form>
<input type="submit" onclick="showOutput();"><br/>
<label>Your output is : </label>
<p><span id='display'></span></p>

How can I remove the input before cloning a div?

I've found a few answers to this question on stack overflow, but it's not working for me.
At the moment, my code looks like this (I removed the other divs so it's not too long to read) :
<div id="dynamicInput">
<div id="duplicater">
<input type="text" placeholder="Event Title" name="title">
<input type="text" placeholder="url" name="url">
</div>
</div>
and the javascript :
var i = 0;
var original = document.getElementById('duplicater');
function duplicate() {
var clone = original.cloneNode(true);
clone.id = "duplicate" + ++i;
original.parentNode.appendChild(clone);
}
It works great, but if I put some text before pressing the button "add event", it also clones the text, and I don't want that.
I've tried to add .find('input').val('') on the first line, but it's not working, I can't even clone anymore. The error in my console is method find not found.
The same thing happens with all the solutions I've found on the forum : or it disabled the button and I can't duplicate anymore, or it works but clones the text.
How can I do this?
Thanks for your help !!
You can loop through the elements in your div and clear them individually.
var i = 0;
var original = document.getElementById('duplicater');
var onClick = function() {
var clone = original.cloneNode(true);
clone.id = "duplicate" + ++i;
for (var i = 0; i < clone.childNodes.length; i++) {
var e = clone.childNodes[i];
if (e.tagName) switch (e.tagName.toLowerCase()) {
case 'input':
switch (e.type) {
case "radio":
case "checkbox": e.checked = false; break;
case "button":
case "submit":
case "image": break;
default: e.value = ''; break;
}
break;
case 'select': e.selectedIndex = 0; break;
case 'textarea': e.innerHTML = ''; break;
default: break;
}
}
original.parentNode.appendChild(clone);
};
$('#button').click(onClick);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.4.4/jquery.min.js"></script>
<div id="dynamicInput">
<div id="duplicater">
<input type="text" placeholder="Event Title" name="title">
<input type="text" placeholder="url" name="url">
</div>
</div>
<input type="button" id="button" value="Clone" />

How to populate circle type percentage validation in jQuery

I have five input fields, I need to validate all the fields by showing a circle type validation modal. It will be incremented dynamically.
Please find attached sample validation images.
Here is the code:
$("#field1, #field2, #field3").blur(function() {
var getImageName = $('#step-dwld').attr('src').slice(7, 30);
if( !this.value ){
$('#step-dwld').attr('src', 'images/'+getImageName);
} else{
switch (getImageName) {
case "step-bg.png":
$('#step-dwld').attr('src', "images/step-1.png");
break;
case "step-1.png":
$('#step-dwld').attr('src', "images/step-2.png");
break;
case "step-2.png":
$('#step-dwld').attr('src', "images/step-3.png");
break;
}
}
});
Because of your vague question without or with very less code it is hard for us to guess what your code is and your HTML structure, you need to create a Minimal, Complete, and Verifiable example so that others can help you.
However check this it might give you an idea on how to do it, I don't now your code this why and based on guesswork I implemented a similar one to simulate it
JS Fiddle
var validate = $('.validate'), score= 0;
validate.on('change', function(){
score = 0;
validate.each(function(){
if($(this).val() != ''){
score += 100 / validate.length;
}
console.log(score);
setImage(score);
});
});
function setImage(score){
var url;
switch (score){
case 20:
url = '20%';
break;
case 40:
url = '40%';
break;
case 60:
url = '60%';
break;
case 80:
url = '80%';
break;
case 100:
url = '100%';
break;
default:
url = '0%';
}
var img = '<img src="//placehold.it/100x100/?text=' +url+ '">';
$('#img').html(img);
}
#img{width:100px;height:100px;border:1px solid gray;margin:10px 0;}
input[type="text"]{display:block;margin:2px 0;}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
<div id="img"></div>
<input type="text" class="validate">
<input type="text" class="validate">
<input type="text" class="validate">
<input type="text" class="validate">
<input type="text" class="validate">
<button id="done">I'm Done!</button>

Dynamically toggle placeholder color with JavaScript

I have an HTML input, as well as some buttons.
<input type="number" placeholder="" id="id"/>
<button onclick="myfunction()" >Click Me</button>
<button onclick="toggle()">toggle</button>
The first button has this JavaScript function
var myfunction=function(){
if(bool){
a=document.getElementById('id');
a.placeholder='Invalid Character';
}
};
bool=false;
and the second button's function is this:
toggle=function(){
bool=!bool;
};
Basically, click the second button to change whether
bool
is true or false. The first button will set a placeholder if the value of bool is true. I want to figure out how to DYNAMICALLY set the color of a placeholder with JavaScript. I have found how to do it with CSS, but I need JavaScript. No jQuery or other frameworks please.
Thanks!
Travis J I specifically said that this is not a duplicate, as I CANNOT use CSS, like the question you mistakenly marked this as a duplicate of
I can ONLY use javscript, not css.
May be this is the not the RIGHT way to add inline styles, but this is the only way i found to full fill the OP requirement.
var placeholderColor = '#f0f';
var FontColor = '#000';
bool = true;
function toggle() {
bool = !bool;
}
function myfunction() {
if (bool) {
a = document.getElementById('id');
a.placeholder = 'Invalid Character';
a.style.color = placeholderColor;
}
}
function textChange() {
a = document.getElementById('id');
if (a.value != '') a.style.color = FontColor;
else {
a.placeholder = 'Invalid Character';
a.style.color = placeholderColor;
}
}
<input type="text" id="id" onkeyup='textChange()' />
<button onclick="myfunction()">Click Me</button>
<button onclick="toggle()">toggle</button>

Categories