Home > Enterprise >  How to create name tag for input tag without any id or class by javascript?
How to create name tag for input tag without any id or class by javascript?

Time:10-06

I am working with a form:

<div class="directions_holder">
                    <h4><i class="fa fa-map-marker"></i> Get Direction</h4>
                    <p>Enter your location</p>
                    <form action="" align="right" onsubmit="calcRoute('routeStart615d1caf4ca70', '10.809556085818913', '106.62590956389425', 'map_canvas615d1caf4ca6f');
                                        return false;">
                        <input type="text" id="routeStart615d1caf4ca70" value="" placeholder="Your Location" style="margin-top:3px"><br><br>
                        <input type="submit" value="Get Direction" class="button" onclick="calcRoute('routeStart615d1caf4ca70', '10.809556085818913', '106.62590956389425', 'map_canvas615d1caf4ca6f');
                                            return false;">
                    </form>
                </div>

And I want to add a name tag name="autocomplete_address" to this input to get the Autocomplete Address Plugin to work but I do not know how to find the input in javascript because this input's id always changed everytime I refresh the page so I do not know how to select it to add the name tag to it.

<input type="text" id="routeStart615d1caf4ca70" value="" placeholder="Your Location" style="margin-top:3px"><br><br>

Please help me. Thanks

CodePudding user response:

document.querySelector('input[type=text]') will get the first input field on the page.

select the form first if you have more than one.

CodePudding user response:

Maybe this you want

Remember one thing name is an attribute not a tag..

let form = document.getElementById("form");
    var input = document.createElement("input");
    input.setAttribute("type", "autocomplete_address");
    form.appendChild(input);

CodePudding user response:

using JQuery you can simply do this

$('.directions_holder input[type="text"]').attr('name','autocomplete_address');

CodePudding user response:

Since you can't use id as you selector maybe you can try something DISTINCT like placeholder selector so you can code like this

var elm = document.querySelectorAll('[placeholder="Your Location"]')[0];
elm.setAttribute("name","autocomplete_address");

//Alert current name
alert(elm.getAttribute("name"));

Or you can change value of querySelectorAll() with other attribute that suite you

  • Related