简体   繁体   中英

Changing input value dynamically before submit/page refresh?

I want to have a hidden input value as either "0" or "1" depending on whether or not a user fills out the phone number field.

This is my current code:

<script>
if(document.getElementById('user-tel').value!='')
{
document.getElementById('send-text').value='1';
} 
else {document.getElementById('send-text').value='0';}
</script>

But I need them to save twice for the hidden #send-text field to update in sql. How can I make it so that this hidden field updates to 1 before submitting form, but rather when they input any digit into the phone field?

You can simply achieve this in jQuery using the form onsubmit Event Attribute :

<form onsubmit="$('#send-text').val(($('#user-tel').val()!='')?'1':'0');">
    <!-- Your form goes here -->
</form>

Read more here : W3 Schools

Your code is true. When you say update in sql i guess you are working with asp.net. If your hidden field is in a ContentPlaceHolder or in a UserControl you must know that in javascript you hidden id is not send-text and its id for javascript is for example:

contentPlaceHolder1_send-text

or

Usercontrol1_send-text

And you can do this on you form submit as mrbm says.

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