简体   繁体   中英

Changing input text value with jQuery in form

I have 2 checkbox input and 1 input text. 在此处输入图像描述 When i click on checkbox #1 i want to disabled checkbox #2 then, add a text (my-text-1) in input text and make it unchangeable

When i click on checkbox #2 i want to disabled checkbox #1 then, add a text (my-text-2) in input text and make it unchangeable

with jQuery 3.4.1

So, it works but...

When i submit the form, the value of the input text is not recorded in my database. It's like the field is empty.

 $(document).ready(function(){ $("#checkbox1").on('click', function(){ if($(this).is(':checked')) { $("#inputtext").val("my-text-1").prop('disabled', true); $("#checkbox2").prop('disabled', true); } else { $("#inputtext").val("").prop('disabled', false); $("#checkbox2").prop('disabled', false); } }); $("#checkbox2").on('click', function(){ if($(this).is(':checked')) { $("#inputtext").val("my-text-2").prop('disabled', true); $("#checkbox1").prop('disabled', true); } else { $("#inputtext").val("").prop('disabled', false); $("#checkbox1").prop('disabled', false); } }); });
 <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <label>Checkbox #1</label> <input id="checkbox1" type="checkbox" value="" name="checkbox1"><br/> <label>Checkbox #2</label><input id="checkbox2" type="checkbox" value="" name="checkbox2"><br/> <label>Text: </label><input name="inputtext" id="inputtext" type="text" size="50" maxlength="50" value="" />

Instead of using disabled property on the input[text] element use readonly property. Data for disabled elements does not get submitted:

$("#inputtext").val("my-text-1").prop('readonly', true);

Another alternative would be to enable the element prior to submitting the form.

Reference

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