0

I want to produce buttons through Javascript that can also do the form function. Here is how i am doing but my form function does not work when i click. Please help me out on this.

External Javascript

var onef    
onef="Apple"    
var twof    
twof="Orange"    

Now this is what i am doing in HTML page

<script>
    document.write("<button>")      
    document.write(onef)    
    onClick=("this.form.T4.value++;")
</script>
<script>
    document.write("<button>")
    document.write(twof)
    onClick=("this.form.T5.value++;")
</script>

The script works right but onClick function not working.

Lee Taylor
  • 7,761
  • 16
  • 33
  • 49

2 Answers2

0

ouldn't you have to do this:

<script>
    document.write("<button ")      
    document.write('onClick="this.form.T4.value++;">')
    document.write(onef)    
    document.write("</button>")
</script>

What you are doing in your original code is building the string "<button>apple" and creating a variable called onClick with a value of "this.form.T4.value++;". What I believe you need to do is build a string with the whole button tag in it, which is what the code above is doing.

nikeaa
  • 1,047
  • 7
  • 17
  • can u also help me on this as well: I am trying to minus the value of "f1" from "f2" but when i click the button it reuces everytime the value of f1

    pls help
    – chandra bhushan Mar 25 '13 at 17:28
  • Try removing the square backets from around document.bills.f2.value. Also, if your original question was answers, would you mind marking this a the answer? Thanks. – nikeaa Mar 25 '13 at 19:10
  • I don't see an end form tag in what you pasted? I believe that may be the issue. – nikeaa Mar 25 '13 at 20:42
  • Since this answer seemed to solve your issue, would you minde accepting it? Thanks. – nikeaa Apr 09 '13 at 21:33
0

I have never seen code like this before for creating a button with JavaScript. I would go with something more like this;

var onef ="Apple";
var twof ="Orange"; 

function createButton(context, func, text){
    var button = document.createElement("input");
    button.type = "button";
    button.value = text;
    button.onclick = func;
    context.appendChild(button);
}

createButton(document.body, function(){ this.form.T4.value++; }, onef);
createButton(document.body, function(){ this.form.T5.value++; }, twof);

An example can be seen here http://jsfiddle.net/4yV4V/

This gives you some reusable code for creating the button and passing in what ever you want the onclick even to be. Also you could customise this code for other situations.

Tim B James
  • 20,084
  • 4
  • 73
  • 103