简体   繁体   中英

change a form element by ID with javascript

The problem:

Working within a Saas environment that processes a form in a way that needs to be altered. It's software-as-a-service so unique changes system wide are not an option.

Attempted Solution:

Attempting to use Javascript which the system is adding to the header area of the page to change the value of a form ID so when the form is submitted it contains the altered value.

The Code: HTML

                <div class="form-group " data-field="how_to_apply">
            <label class="form-label">How to Apply </label>


<div id="application-settings" class="form--move-left clearfix row">
    <div class="form-group form-group__half">
        <input id="via-email" name="ha" value="1" checked="checked" onclick="displayInput(false, 'how_to_apply_1');" type="radio" />
        <label for="via-email" class="form-label">
            By Email<br/>
        </label>
        <input value="systemapplied@emailaddress.com" class="form-control"  name="how_to_apply"  id="how_to_apply_1" type="email" />
    </div>
    <div class="form-group form-group__half">
        <input id="via-site" name="ha" value="2"  onclick="displayInput(false, 'how_to_apply_2');" type="radio" />
        <label for="via-site" class="form-label">
            By URL
        </label>
        <input value="" class="form-control" name="how_to_apply" id="how_to_apply_2" disabled="disabled" type="url" required placeholder="e.g. http://www.yourwebsite.com"/>
    </div>
</div>

Attempting to change the email address assigned to how_to_apply_1 ID

Javascript Used

  document.getElementById("how_to_apply_1").value = "new@emailaddress.com";

It is important to add that this works as expected in a CodePen area but does not on the live site so my assumption is that there is something over writing this someplace I am not seeing, or I need to use something else to force the change, I don't know. Any suggestions or help would be GREATLY appreciated

Thanks in advance...

You need to run your script when the DOM is ready. You can wrap your script in DOMContentLoaded event like this:

document.addEventListener("DOMContentLoaded", function(event) {
    document.getElementById("how_to_apply_1").value = "new@emailaddress.com";
});

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