How can I remove the input before cloning a div? - javascript

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" />

Related

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 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>

Javascript ignoring variable in switch statement

Im trying to make a case statement but my variable for my first switch statement just goes to my default statement when i really have a string in my variable for the type of edge such as: "round", "square", "butt". I tested it with alert(tipoextremo) and it does contain the value "round", "square", or "butt".
For the second switch statement, i am trying to get my button names into the switch statement when i click a button in html and do that function inside the case, but when using alert("hi") it does not even go into the default statement meaning that it is being completely ignored in my javascript.
Botones
Borrar
Varias Lineas
Arco
Cuadratica
Berzier
Zig Zag
Espiral
<section id="parametros">
<form action="" method="post" name="parametro">
Color: <input type="text" name="btncolor" id="color" value="red"><br/>
Ancho: <input type="text" name="btnancho" id="ancho" value="10"><br/>
Tipo Extremo: <br/>
Round <input type="radio" name="btntipoextremo" value="round" id="tipoextremo" checked="checked"><br/>
Square <input type="radio" name="btntipoextremo" value="square" id="tipoextremo"><br/>
Butt <input type="radio" name="btntipoextremo" value="butt" id="tipoextremo"><br/>
<button name="btnOK" type="button" value="OK" onclick="parametros()">OK</button>
</form>
</section>
This is my javascript part.
function parametros() {
//var nombre = document.parametro.btncolor.value;
//alert(nombre);
contexto.beginPath();
color = document.getElementById("color").value;
ancho = document.getElementById("ancho").value;
alert(color);
alert(ancho);
var boton_te = document.forms[0];
var i;
for (i = 0; i < boton_te.length; i++) {
if (boton_te[i].checked) {
tipoextremo = tipoextremo + boton_te[i].value + " ";
}
}
document.getElementById("tipoextremo").value = tipoextremo;
alert(tipoextremo);
$("button[type='button']").click(function()
{
switch(this.name){
case 'btnarco':
fun_arco(color, ancho, tipoextremo);
alert("Hi");
break;
case 'btncuad':
fun_cuad(color, ancho, tipoextremo);
break;
case 'btnbezier':
fun_bezier(color, ancho, tipoextremo);
break;
case 'btnzigzag':
fun_zigzag(color, ancho, tipoextremo);
break;
case 'btnespiral':
fun_espiral(color, ancho, tipoextremo);
break;
default:
alert("hi");
break;
}
});
}

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

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>

how to reset form in firefox browser by javascript

I want to reset form in firefox browser. When I use previous function in back button, the page is not reset for hidden field. It has previous stage. So, How do I?
<Html>
<Head>
<Title>My Testing for javascript</Title>
<Script type="text/javascript">
function hidetext(){
window.alert('Start save to hidden');
document.getElementById('hid').value = document.getElementById('puttextbox').value;
window.alert('Complete save to hidden');
document.getElementById('puttextbox').value='';
}
function displaytext(){
window.alert('Start display from hidden');
document.getElementById('displaytextbox').value = document.getElementById('hid').value;
window.alert('Complete display from hidden');
}
function resetform(){
document.getElementById('form1').reset();
window.alert('reset is completing.....');
}
</Script>
</Head>
<Body>
<form id="form1">
<div>
Type your hidden text <input type="text" id="puttextbox"/>
<br/>
Display your hidden text <input type="text" id="displaytextbox"/>
<br/>
<input type="hidden" id="hid"/>
<button type="button" id="putbutton" onclick="hidetext();">Put the textbox</button>
<button type="button" id="displaybutton" onclick="displaytext();">Display hidden text</button>
<button type="button" id="resetbutton" onclick="resetform();">Reset</button>
</div>
</form>
</Body>
</Html>
Why not this:
<input type="reset" value="Reset">
? It's HTML-native. Or try this instead:
window.onload = function() {
var inputs = document.getElementsByTagName('input');
for (var i = 0; i < inputs.length; i++) {
inputs[i].value = '';
}
};
It clears each input element in the page.
function clearForm(oForm) {
var elements = oForm.elements;
oForm.reset();
for(i=0; i<elements.length; i++) {
field_type = elements[i].type.toLowerCase();
switch(field_type) {
case "text":
case "password":
case "textarea":
case "hidden":
elements[i].value = "";
break;
case "radio":
case "checkbox":
if (elements[i].checked) {
elements[i].checked = false;
}
break;
case "select-one":
case "select-multi":
elements[i].selectedIndex = -1;
break;
default:
break;
}
}
}
That should do the job.
The most simple version is:
document.form1.reset();
However, this resets all input fields to their default value, i.e. the one sent along with the HTML. If you want all fields cleared, you'd need to loop through them all.

Categories