Swap Hidden field to text with javascript

Asked

Viewed 1,190 times

1

All right guys ?

So, I have a field of type Hidden, I need to assign a value to it and change it from Hidden to text after the calculation

function calc(){
    var myVar = formCalc.myCamp.value;
    document.getElementById("calcFeito").value = myVar*2;
    document.getElementsByTagName("hidden").setAttribute("type", "text");
}   


<form name="formCalc">
    <br>Digite o Valor:<br>
    <input type="text" name="myCalc">
    <input type="button" value="botão" onClick="calc()"></button><br>
</form>
<input type='hidden' id='calcFeito'>
  • Good evening, something missing in the answer? It solved your problem?

  • I forgot to mark as sure, sorry, corrected by @Guilhermenascimento

  • Imagine, I am grateful :)

2 answers

6


The function document.getElementsByTagName is not used to search for attributes, I recommend you read the documentation, the use is totally wrong, this function searches by tag name, if you want to take elements more easily can use the document.querySelector, or even the document.getElementById.

Also as quoted by Magichat, the tags are incorrect, has a </button> remaining, always try to make the marking as correct as possible, can use tools such as:

Note: do not need to validate 100%, worry about looking at the validations on wrong tags and repeated ids (another thing that can cause problems)

See here I adapted everything to getElementById:

function calc(){
    var myVar = document.getElementById("myCalc").value;
    document.getElementById("calcFeito").value = myVar * 2;
    document.getElementById("calcFeito").setAttribute("type", "text");
}  
<form name="formCalc">
<br>Digite o Valor:<br>
<input type="text" name="myCalc" id="myCalc">
<input type="button" value="botão" onClick="calc()"><br>
</form>
<input type='hidden' id='calcFeito'>

Read the documentation about DOM and learn how each function works before using them:

  • 2

    Is this button closing tag right? Out of curiosity, I’ve never seen it this way...

  • 1

    @Magichat no, thanks for mentioning, was the example of AP that was incorrect, I ended up copying the error.

  • 1

    @Magichat ready edited, thanks :)

0

You can do it in two ways using jQuery.

The first, you change the type=hiddenfor type=text using the function .attr()

Example:

/*Para mostrar*/
$("#calcFeito").attr('type', 'text');

/*Para ocultar*/
$("#calcFeito").attr('type', 'hidden');

Or use your own .show() and .hide() jQuery.

Having <input type='text' id='calcFeito' style='display:none'> as a basis:

/*Para mostrar*/
$("#calcFeito").show();

/*Para ocultar*/
$("#calcFeito").hide();

Browser other questions tagged

You are not signed in. Login or sign up in order to post.