简体   繁体   中英

Access javascript variable in HTML tags in a JSP

I have a requirement where I need to set html input tags ids with js variables.

example:

<input type='text' id='(here I need js variable)'/>

I know there's a way to do that by creating entire element by

document.createElement('div name');

and I can append to the div, but I want it in a simple way.

If it is a Java variable then I can do it like

<%String myVar = "txtId"%>
<input type='text' id='<%= myVar%>'/>

Is there any simplest way to put a js variable in a html tag?

Update :

Thanks for the answers guys, I know we can create any number of input elements and append to the parent element. And also we could get an element by tag name and can set id for those elements.But my question is, is there a way to use(or) place (or) insert a js variable in html tag just like we could insert a java variable in the html tag as I've shown above.

like,

<script>
var txtId = 'txt1';
</script>
<html>
<input type='text' id='document.write(txtId)'/>
</html>

Is there a way to do like this?

Assign ids to exist element , if you want to use java variable as your new id, you can use jstl tag like this

var inputs = document.getElementsByTagName("input");
for(var i = 0 ; i<inputs.length ; i++){
    inputs[i].id = "newIdWhatYouWant";
}
<input type='text' class="name"/>

you can use attr() jQuery function and set any string you like. so in action:

    var str="newId"
    $('name_or_#id_or_.class').attr('id',str)

I think this will help you.

If you face any problem then tell me.

OR

You can create whole control dynamically and set all data see this link. It's very helpful.

I have tried this one, you will have existing ID then only you can change it's ID :

<script type="text/javascript"> 
 function addName()
 {
     var k ='add';

    document.getElementById('txttt').id = k;
    //document.getElementById('two').value = 'hi'

    var srchdata = document.getElementById(k).id;    
    alert(srchdata);
 } 
</script>

<body onload="addName()">

If your data is dynamic then some problem can be arise. I have used alert to display new ID of textbox.

If you want some other way then tell me how ? And what problem can be arise in this ?

Can you use something like this ?

<script>
    var a = "some_id";
    document.write("<input type='text' id='"+a+"' />");
</script>

http://jsfiddle.net/9DAE4/

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