Javascript ignoring variable in switch statement - javascript

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;
}
});
}

Related

How can I call a function from different buttons?

I am trying to put different buttons with same function in switch statement. Every button needs to call same function but with different switch parameter.
<button type="submit" onclick="myFunction()" class="dugme1" id="btnSQRT">
SQRT
</button>
<button type="submit" onclick="myFunction()" class="dugme1" id="btnSIN" style="margin-left:
100px;">
SIN
</button>
<button type="submit" onclick="myFunction()" class="dugme1" id="btnCOS" style="margin-left:
100px;">
COS
</button>
<button type="submit" onclick="myFunction()" class="dugme1" id="btnROUND" style="margin-left:
100px;">
ROUND
</button>
And here is JS code,
<script>
function myFunction(){
var x = prompt("Input number beteen 1 i 999");
if(x > 0 && x < 1000){
switch(x){
case 0:
document.getElementById("btnSQRT");
document.write("nesta");
break;
case 1:
document.getElementById("btnSIN");
document.write("nesta");
break;
case 2:
document.getElementById("btnCOS");
document.write("nesta");
break;
case 3:
document.getElementById("btnROUND");
document.write("nesta");
break;
}
}
else{
alert("Thats not a wanted number");
}
}
</script>
Change all of your onclick="myFunction()" to onclick="myFunction(this)" - that will allow you to test for the switch in myFunction - in which case you want to switch on the button ID rather than the prompt value.
function myFunction(el){ // el will be the button that called the function
var x = prompt("Input number between 1 i 999");
if(x > 0 && x < 1000){
switch(el.id){ // switching on the ID of the button which tells us which math to use
case 'btnSQRT':
alert('The square root is ' + Math.sqrt(x));
break;
.....
I am not sure what 'nesta' and document.write was for, so I removed them here.
You are trying to switch between INT numbers, and "prompt" return a STRING. So, It will never get in any switch statement. To solve this, I just added a "parseInt()" in your prompt variable.
I changed "document.write('nesta')" by inner.HTML('nesta'), so, it changes the text in the button. But, to change the text inside the button, you got to set a variable to each button.
HTML:
<button type="submit" onclick="myFunction()" class="dugme1" id="btnSQRT">SQRT</button>
<button type="submit" onclick="myFunction()" class="dugme1" id="btnSIN" style="margin-left: 100px;">SIN</button>
<button type="submit" onclick="myFunction()" class="dugme1" id="btnCOS" style="margin-left: 100px;">COS</button>
<button type="submit" onclick="myFunction()" class="dugme1" id="btnROUND" style="margin-left: 100px;">ROUND</button>
JS:
function myFunction(){
var x = prompt("Input number beteen 1 i 999");
var x = parseInt(x);
if(x > 0 && x < 1000) {
switch(x){
case 1:
var nesta = document.getElementById("btnSQRT");
nesta.innerHTML = 'nesta';
break;
case 2:
var nesta =document.getElementById("btnSIN");
nesta.innerHTML = 'nesta';
break;
case 3:
var nesta = document.getElementById("btnCOS");
nesta.innerHTML = 'nesta';
break;
case 4:
var nesta =document.getElementById("btnROUND");
nesta.innerHTML = 'nesta';
break;
}
} else {
alert("Thats not a wanted number");
}
}
Here you have:
One event listener for all buttons.
getting the "value" from the button using the attribute id. An alternative could be to use a data-attribute (like I did with the 2ed button).
A switch statement for handling what to do next.
It is not completely clear for me if the switch statement is the right approach here. Please comment if you have questions.
document.addEventListener('DOMContentLoaded', e => {
let buttons = document.getElementById('buttons');
let output = document.getElementById('output');
buttons.addEventListener('click', e => {
if (e.target.nodeName == 'BUTTON') {
switch (e.target.id) {
case 'btnSQRT':
output.innerHTML = 'You clicked SQRT';
break;
case 'btnSIN':
output.innerHTML = 'You clicked SIN';
break;
case 'btnCOS':
output.innerHTML = 'You clicked COS';
break;
case 'btnROUND':
output.innerHTML = 'You clicked ROUND';
break;
}
}
});
});
div#buttons {
display: flex;
justify-content: space-between;
}
<div id="buttons">
<button id="btnSQRT">SQRT</button>
<button data-func="SIN" id="btnSIN">SIN</button>
<button id="btnCOS">COS</button>
<button id="btnROUND">ROUND</button>
</div>
<div id="output"></div>

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>

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