1

Consider a code:

<input type="1 == 1 ? 'radio' : 'checkbox'" value="myValue"/>

But it renders as text box input. It seem that javascript do not set type value.

How set html attribute value by javascript?

asked Sep 26, 2015 at 9:17

3 Answers 3

4

Javascript engine doesn't interpret random HTML attributes as source code. Of course you can't do it like you are trying to do. Consider something like this:

<input type="text" value="myValue"/>
<script>
 var input = document.querySelector('input');
 input.type = 1 == 1 ? 'radio' : 'checkbox'
</script>

answered Sep 26, 2015 at 9:24
Sign up to request clarification or add additional context in comments.

Comments

0

A quick, but less elegant, solution would be to change your <input> tag to

<input id="inputFoo" value="myValue"/>

and then put right after it a pair of <script> tags with type-changing code.

<script>
 if(1 == 1) {
 document.getElementById("inputFoo").type = "radio";
 } else {
 document.getElementById("inputFoo").type = "checkbox";
 }
</script>

Or maybe rather:

<script>
 document.getElementById("inputFoo").type = (1 == 1 ? 'radio' : 'checkbox')
</script>
answered Sep 26, 2015 at 9:30

Comments

0

HTML input type text is the default type that is set. HTML cannot do conditional checks, thats the reason for default type being assigned to input.

You can achieve adding the type attribute multiple ways using javascript, here are a couple of ways

<input id="inputTag" value="myValue" />
<script>
 var input = document.getElementById('inputTag');
 input.type = 1 == 1 ? 'radio' : 'checkbox'
</script>

or, use a container div to insert input html inside like this

<div id="container"></div>
<script>
 var div = document.getElementById('container');
 div.innerHTML = 1 == 1 ? '<input type="radio" value="myValue" />' : '<input type="checkbox" value="myValue" />'
</script>

If you are using server side rendering like jsp alike, you can perform the conditional check at the server side and render appropriate HTML without using javascript.

answered Sep 26, 2015 at 9:47

Comments

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.