Xonal
Xonal

Reputation: 1350

Trying to set an html attribute to a javascript variable

I have a variable "count" in javascript and a radio button that I want to depend on that variable. There is a button to generate more radio buttons, which is why I need their name attributes to differ.

My code:

var count = 1;
function newForm(){
...<input name=count type="radio" value="Website" />...
}

But it's just setting the name of each additional radio button to "count" rather than the number "count" represents.

Here's the whole code:

var count = 1;
function newForm(){
var newdiv = document.createElement('div');
newdiv.innerHTML = '<div class="line"></div><br><input type="text" name="Name" 
class="field" placeholder="Full Event Name" /><br><input type="text" name="Location"       
placeholder="Event Location" class="field" /><br> <input type="text" name="Date" 
placeholder="Event Date" class="field" /> <br> <input type="text" name="End" 
placeholder="Event End Date (If Applicable)" class="field" /> <br> <input type="text" 
name="Time" placeholder="Event Time" class="field" /> <br> <input type="text"     
name="Tags" 
placeholder="Relevant Tags" class="field" /> <br> The info is from: <input name=count 
type="radio" value="Tweet" checked="" />Tweet <input name=count type="radio"   
value="Website" 
/>Website <input name=count type="radio" value="Tweet and Website" /> Tweet and  
Website';
if(count < 10) {
    document.getElementById('formSpace').appendChild(newdiv);
    count++;
}

}

That newdiv.innerHTML string above is all on one line in the code, by the way.

Upvotes: 1

Views: 4301

Answers (2)

1nfiniti
1nfiniti

Reputation: 2070

in your long string of innerHTML you need to escape your "count" variable... otherwise it's just a string... i.e.

'<input name='+count+' type="radio" value="Tweet and Website" />';

That will make it work but as everyone else is mentioning - you really shouldn't embed long html strings like this.

Upvotes: 1

adeneo
adeneo

Reputation: 318182

If you're trying to create an element, use createElement() :

var count = 1;

function newForm(){
     var input = document.createElement('input');

     input.name  = count;
     input.type  = 'radio';
     input.value = 'Website';
}

Upvotes: 2

Related Questions