0

How to add id attribute of an element in HTML as a variable which is declared above in javascript.

jQuery

var table_row = $('table').find('tr#'+pid);  
var name = table_row.find('td:nth-child(1)').html();  
table_row.find('td:nth-child(6)').html('<button  type="button" id="what to write here" class ="save_db")>save</button> ');

I want to set id as name.

Thanks

3
  • Not able to get you. Please explain. Commented Apr 9, 2014 at 10:24
  • 1
    Not able to get you. Please explain. Commented Apr 9, 2014 at 10:24
  • (As per my understanding) He wants to set id dynamically by using javascript varibale. Please check 'what to write here' text in his code snippet. Commented Apr 9, 2014 at 10:28

6 Answers 6

1

It can be done using simple string concatenation as follows:

var table_row = $('table').find('tr#'+pid);  
var name = table_row.find('td:nth-child(1)').html();  
table_row.find('td:nth-child(6)')
  .html('<button  type="button" id="'+name+'" class ="save_db">save</button> ');

PS: Also note that your markup contained a seemingly unnecessary closing brace after class attribute. I've removed it in my code.

Sign up to request clarification or add additional context in comments.

Comments

0

So you just want a variable inserted into the html string?

table_row.find('td:nth-child(6)').html`(
    '<button  type="button" id="' + name + '" class ="save_db">save</button> '
)`;

Comments

0

Concatenate name variable to the appending string as ID.

table_row.find('td:nth-child(6)').html('<button  type="button" id="'+ name + '" 
class ="save_db")>save</button>');  

1 Comment

Add single quote before id="
0

Please follow this code:

table_row.setAttribute("id", "id_you_like");

Comments

0

Please try with the below code snippet. Let me know if i am not understand your question.

var id = "btn1";
var table_row = $('table').find('tr#'+pid);  
var name = table_row.find('td:nth-child(1)').html();  
table_row.find('td:nth-child(6)').html('<button  type="button" id="'+id+'" class ="save_db")>save</button> ');

Comments

0

Have you tried this? Try using this:

<button type="button" id='"+name+"' class= "save_db">

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.