Setting a button's value using javascript

前端 未结 4 1787
庸人自扰
庸人自扰 2020-11-30 07:46

I\'m sure I\'m going to feel stupid after seeing the answer, but I keep running into prehistoric code around the web, which I\'m not sure still applies. My question is \"How

相关标签:
4条回答
  • 2020-11-30 08:28

    Use innerHTML instead of value.

    form.elements["submit-button"].innerHTML = ...
    

    Because you are using a <button> instead of <input type="button">, you need to set the innerHTML. <button>s do not base their text on the value attribute.

    <button> innerHTML </button>
    <input type="button" value="value" />
    
    0 讨论(0)
  • 2020-11-30 08:28

    there's a much better way to do that. use document.getElementById and give the button an ID.

    function myFunc() {
        document.getElementById('my_button').innerHTML = "New<br>Text";
        //"other stuff that actually works."
        return false;
    }
    
    <form onSubmit="return myFunc();">
        <button id="my_button" name="submit-button">Original<br>Text</button>
    </form>
    

    I'm not sure you can put a tag into the value of a button, but who knows. Can't say I've tried it.

    0 讨论(0)
  • 2020-11-30 08:29

    Your code works, but isn't doing what you probably expect. Your followed by shows the text of the button and it's initial value, however your code will change the value before the form is submitted. That means, the receiving page (most often a php/perl/asp script) will see the changed value passed as a GET or POST parameter.

    If you want to change the text w/o submitting the form you might want to try this:

    function changeValue(id, newText) {
        var el       = document.getElementById(id);
        el.value     = newText;  // change the value passed to the next page
        el.innerHTML = newText;  // change the displayed text on the screen
        return false;
    }
    
    <form onsubmit="return false;">
        <button  id="submit-button" 
               name="submit-button" 
            onclick="changeValue(this.id,'Some New Text');" >Original<br>Text</button>
    </form>
    

    see JS Fiddle here

    0 讨论(0)
  • 2020-11-30 08:29

    This might work:

    form.elements["submit-button"][0].innerHTML = "New<br>Text";
    

    form.elements["submit-button"] probably returns all of the elements with that name attribute, which is an array.

    0 讨论(0)
提交回复
热议问题