简体   繁体   中英

Javascript for submitting form button

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.

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM