问题
I would like to ask for help with accessing WTForm fields:
I have following form:
class model_bolt_InputForm(FlaskForm):
# Bolt Inputs
bolt_size = SelectField('Bolt size [mm]', choices=[('M6', 'M6'),('M8', 'M8'),('M10', 'M10'), ('M12', 'M12'), ('M16', 'M16'), ('M20', 'M20'), ('M24', 'M24'), ('M30', 'M30'), ('M36', 'M36'), ('M42', 'M42'), ('M48', 'M48'), ('M56', 'M56'), ('M64', 'M64')], default='M12')
bolt_grade = SelectField('Bolt grade [-]', choices=[('4.6','4.6'), ('4.8','4.8'), ('5.6','5.6'), ('5.8','5.8'), ('6.8','6.8'), ('8.8','8.8'), ('9.8','9.8'), ('10.9','10.9'), ('12.9','12.9')], default='8.8')
bolt_preload = FloatField( label=' Bolt preload [N]', default=32360)
friction_coefficient = FloatField( label=' Thread friction coefficient [-]', default=0.2)
preload_type = RadioField( label='Select preload type', choices=[(1,'Apply torque'),(2,'Apply Axial preload'),(3,'Ratio of total Tensile Strength')], default=2)
my html:
<button id="btn1">Button 1</button>
<p class="para1">sdiuc siduch siudch siudch siudhc siudch siduch </p>
<script>
$(document).ready(function(){
$('#btn1').click(function(){
$('.para1').toggle();
alert(**form.bolt_preload.data**);
});
});
</script>
If i click the button the paragraph hides but I am getting error with trying to print value of bolt_preload field. Can someone give me a hint on how to do that?
What about changing the value in Filed upon click instead of printing it?
Thank you Jakub
回答1:
You cannot access form data in your template the way you are trying to. If you are using javascript to get data from the form then. IF you don't specify an ID for your form elements, WTForm will render them using the variable name as the id attribute as well as the name attribute pf the HTML input. You can use that to select that input by id using javascript/jquery Your jquery code should look like this.
<script>
$(document).ready(function(){
$('#btn1').click(function(){
$('.para1').toggle();
var boltPreloadInput = $('#bolt_preload');
alert(boldPreloadInput.val());
});
});
</script>
When you use WTForms, your form elements render to HTML inputs on page load. Once the page is loaded, you cannot access form data on the client side like you are trying. The only way to interact with the form on click events without first sending the data to the server is by using javascript.
来源:https://stackoverflow.com/questions/52155339/how-access-wtform-with-jquery