How to set value of button(created in js) to a hidden value (set inside a html)

时间:2018-02-05 12:55:40

标签: javascript jquery html

What is required - We need to set the button text which is created dynamically inside sample.js to a text which we have set in a hidden field in sample.html Piece of html is - sample.html

<div type="hidden" id="readfromhere" value="OK"></div>

Piece of JS logic is -sample.js

$('#id').append("<div><a id="buttontext"></a></div>")
$('#buttontext').val($('#readfromhere').val());

This is not working , can anyone suggest where am i going wrong ?

2 个答案:

答案 0 :(得分:2)

buttontext is an anchor tag, use text/html instead of val and the element of hidden type should be input and not div. div elements don't have a value and type attributes

$('#id').append("<div><a id='buttontext'></a></div>")
$('#buttontext').text($('#readfromhere').val());
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="hidden" id="readfromhere" value="OK">
<div id="id"></div>

答案 1 :(得分:1)

buttontext is an anchor tag, use html instead of val

$('#buttontext').html($('#readfromhere').attr( "value" ));

Note

  • Also note that readfromhere is a div tag, so read attribute value
相关问题